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 that the argument to __builtin_function_start is a function.
199 static bool SemaBuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
200   if (checkArgCount(S, TheCall, 1))
201     return true;
202 
203   ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
204   if (Arg.isInvalid())
205     return true;
206 
207   TheCall->setArg(0, Arg.get());
208   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
209       Arg.get()->getAsBuiltinConstantDeclRef(S.getASTContext()));
210 
211   if (!FD) {
212     S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
213         << TheCall->getSourceRange();
214     return true;
215   }
216 
217   return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
218                                               TheCall->getBeginLoc());
219 }
220 
221 /// Check the number of arguments and set the result type to
222 /// the argument type.
223 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
224   if (checkArgCount(S, TheCall, 1))
225     return true;
226 
227   TheCall->setType(TheCall->getArg(0)->getType());
228   return false;
229 }
230 
231 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
232 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
233 /// type (but not a function pointer) and that the alignment is a power-of-two.
234 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
235   if (checkArgCount(S, TheCall, 2))
236     return true;
237 
238   clang::Expr *Source = TheCall->getArg(0);
239   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
240 
241   auto IsValidIntegerType = [](QualType Ty) {
242     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
243   };
244   QualType SrcTy = Source->getType();
245   // We should also be able to use it with arrays (but not functions!).
246   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
247     SrcTy = S.Context.getDecayedType(SrcTy);
248   }
249   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
250       SrcTy->isFunctionPointerType()) {
251     // FIXME: this is not quite the right error message since we don't allow
252     // floating point types, or member pointers.
253     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
254         << SrcTy;
255     return true;
256   }
257 
258   clang::Expr *AlignOp = TheCall->getArg(1);
259   if (!IsValidIntegerType(AlignOp->getType())) {
260     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
261         << AlignOp->getType();
262     return true;
263   }
264   Expr::EvalResult AlignResult;
265   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
266   // We can't check validity of alignment if it is value dependent.
267   if (!AlignOp->isValueDependent() &&
268       AlignOp->EvaluateAsInt(AlignResult, S.Context,
269                              Expr::SE_AllowSideEffects)) {
270     llvm::APSInt AlignValue = AlignResult.Val.getInt();
271     llvm::APSInt MaxValue(
272         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
273     if (AlignValue < 1) {
274       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
275       return true;
276     }
277     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
278       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
279           << toString(MaxValue, 10);
280       return true;
281     }
282     if (!AlignValue.isPowerOf2()) {
283       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
284       return true;
285     }
286     if (AlignValue == 1) {
287       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
288           << IsBooleanAlignBuiltin;
289     }
290   }
291 
292   ExprResult SrcArg = S.PerformCopyInitialization(
293       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
294       SourceLocation(), Source);
295   if (SrcArg.isInvalid())
296     return true;
297   TheCall->setArg(0, SrcArg.get());
298   ExprResult AlignArg =
299       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
300                                       S.Context, AlignOp->getType(), false),
301                                   SourceLocation(), AlignOp);
302   if (AlignArg.isInvalid())
303     return true;
304   TheCall->setArg(1, AlignArg.get());
305   // For align_up/align_down, the return type is the same as the (potentially
306   // decayed) argument type including qualifiers. For is_aligned(), the result
307   // is always bool.
308   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
309   return false;
310 }
311 
312 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
313                                 unsigned BuiltinID) {
314   if (checkArgCount(S, TheCall, 3))
315     return true;
316 
317   // First two arguments should be integers.
318   for (unsigned I = 0; I < 2; ++I) {
319     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
320     if (Arg.isInvalid()) return true;
321     TheCall->setArg(I, Arg.get());
322 
323     QualType Ty = Arg.get()->getType();
324     if (!Ty->isIntegerType()) {
325       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
326           << Ty << Arg.get()->getSourceRange();
327       return true;
328     }
329   }
330 
331   // Third argument should be a pointer to a non-const integer.
332   // IRGen correctly handles volatile, restrict, and address spaces, and
333   // the other qualifiers aren't possible.
334   {
335     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
336     if (Arg.isInvalid()) return true;
337     TheCall->setArg(2, Arg.get());
338 
339     QualType Ty = Arg.get()->getType();
340     const auto *PtrTy = Ty->getAs<PointerType>();
341     if (!PtrTy ||
342         !PtrTy->getPointeeType()->isIntegerType() ||
343         PtrTy->getPointeeType().isConstQualified()) {
344       S.Diag(Arg.get()->getBeginLoc(),
345              diag::err_overflow_builtin_must_be_ptr_int)
346         << Ty << Arg.get()->getSourceRange();
347       return true;
348     }
349   }
350 
351   // Disallow signed bit-precise integer args larger than 128 bits to mul
352   // function until we improve backend support.
353   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
354     for (unsigned I = 0; I < 3; ++I) {
355       const auto Arg = TheCall->getArg(I);
356       // Third argument will be a pointer.
357       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
358       if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
359           S.getASTContext().getIntWidth(Ty) > 128)
360         return S.Diag(Arg->getBeginLoc(),
361                       diag::err_overflow_builtin_bit_int_max_size)
362                << 128;
363     }
364   }
365 
366   return false;
367 }
368 
369 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
370   if (checkArgCount(S, BuiltinCall, 2))
371     return true;
372 
373   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
374   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
375   Expr *Call = BuiltinCall->getArg(0);
376   Expr *Chain = BuiltinCall->getArg(1);
377 
378   if (Call->getStmtClass() != Stmt::CallExprClass) {
379     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
380         << Call->getSourceRange();
381     return true;
382   }
383 
384   auto CE = cast<CallExpr>(Call);
385   if (CE->getCallee()->getType()->isBlockPointerType()) {
386     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
387         << Call->getSourceRange();
388     return true;
389   }
390 
391   const Decl *TargetDecl = CE->getCalleeDecl();
392   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
393     if (FD->getBuiltinID()) {
394       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
395           << Call->getSourceRange();
396       return true;
397     }
398 
399   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
400     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
401         << Call->getSourceRange();
402     return true;
403   }
404 
405   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
406   if (ChainResult.isInvalid())
407     return true;
408   if (!ChainResult.get()->getType()->isPointerType()) {
409     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
410         << Chain->getSourceRange();
411     return true;
412   }
413 
414   QualType ReturnTy = CE->getCallReturnType(S.Context);
415   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
416   QualType BuiltinTy = S.Context.getFunctionType(
417       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
418   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
419 
420   Builtin =
421       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
422 
423   BuiltinCall->setType(CE->getType());
424   BuiltinCall->setValueKind(CE->getValueKind());
425   BuiltinCall->setObjectKind(CE->getObjectKind());
426   BuiltinCall->setCallee(Builtin);
427   BuiltinCall->setArg(1, ChainResult.get());
428 
429   return false;
430 }
431 
432 namespace {
433 
434 class ScanfDiagnosticFormatHandler
435     : public analyze_format_string::FormatStringHandler {
436   // Accepts the argument index (relative to the first destination index) of the
437   // argument whose size we want.
438   using ComputeSizeFunction =
439       llvm::function_ref<Optional<llvm::APSInt>(unsigned)>;
440 
441   // Accepts the argument index (relative to the first destination index), the
442   // destination size, and the source size).
443   using DiagnoseFunction =
444       llvm::function_ref<void(unsigned, unsigned, unsigned)>;
445 
446   ComputeSizeFunction ComputeSizeArgument;
447   DiagnoseFunction Diagnose;
448 
449 public:
450   ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
451                                DiagnoseFunction Diagnose)
452       : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
453 
454   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
455                             const char *StartSpecifier,
456                             unsigned specifierLen) override {
457     if (!FS.consumesDataArgument())
458       return true;
459 
460     unsigned NulByte = 0;
461     switch ((FS.getConversionSpecifier().getKind())) {
462     default:
463       return true;
464     case analyze_format_string::ConversionSpecifier::sArg:
465     case analyze_format_string::ConversionSpecifier::ScanListArg:
466       NulByte = 1;
467       break;
468     case analyze_format_string::ConversionSpecifier::cArg:
469       break;
470     }
471 
472     analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
473     if (FW.getHowSpecified() !=
474         analyze_format_string::OptionalAmount::HowSpecified::Constant)
475       return true;
476 
477     unsigned SourceSize = FW.getConstantAmount() + NulByte;
478 
479     Optional<llvm::APSInt> DestSizeAPS = ComputeSizeArgument(FS.getArgIndex());
480     if (!DestSizeAPS)
481       return true;
482 
483     unsigned DestSize = DestSizeAPS->getZExtValue();
484 
485     if (DestSize < SourceSize)
486       Diagnose(FS.getArgIndex(), DestSize, SourceSize);
487 
488     return true;
489   }
490 };
491 
492 class EstimateSizeFormatHandler
493     : public analyze_format_string::FormatStringHandler {
494   size_t Size;
495 
496 public:
497   EstimateSizeFormatHandler(StringRef Format)
498       : Size(std::min(Format.find(0), Format.size()) +
499              1 /* null byte always written by sprintf */) {}
500 
501   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
502                              const char *, unsigned SpecifierLen) override {
503 
504     const size_t FieldWidth = computeFieldWidth(FS);
505     const size_t Precision = computePrecision(FS);
506 
507     // The actual format.
508     switch (FS.getConversionSpecifier().getKind()) {
509     // Just a char.
510     case analyze_format_string::ConversionSpecifier::cArg:
511     case analyze_format_string::ConversionSpecifier::CArg:
512       Size += std::max(FieldWidth, (size_t)1);
513       break;
514     // Just an integer.
515     case analyze_format_string::ConversionSpecifier::dArg:
516     case analyze_format_string::ConversionSpecifier::DArg:
517     case analyze_format_string::ConversionSpecifier::iArg:
518     case analyze_format_string::ConversionSpecifier::oArg:
519     case analyze_format_string::ConversionSpecifier::OArg:
520     case analyze_format_string::ConversionSpecifier::uArg:
521     case analyze_format_string::ConversionSpecifier::UArg:
522     case analyze_format_string::ConversionSpecifier::xArg:
523     case analyze_format_string::ConversionSpecifier::XArg:
524       Size += std::max(FieldWidth, Precision);
525       break;
526 
527     // %g style conversion switches between %f or %e style dynamically.
528     // %f always takes less space, so default to it.
529     case analyze_format_string::ConversionSpecifier::gArg:
530     case analyze_format_string::ConversionSpecifier::GArg:
531 
532     // Floating point number in the form '[+]ddd.ddd'.
533     case analyze_format_string::ConversionSpecifier::fArg:
534     case analyze_format_string::ConversionSpecifier::FArg:
535       Size += std::max(FieldWidth, 1 /* integer part */ +
536                                        (Precision ? 1 + Precision
537                                                   : 0) /* period + decimal */);
538       break;
539 
540     // Floating point number in the form '[-]d.ddde[+-]dd'.
541     case analyze_format_string::ConversionSpecifier::eArg:
542     case analyze_format_string::ConversionSpecifier::EArg:
543       Size +=
544           std::max(FieldWidth,
545                    1 /* integer part */ +
546                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
547                        1 /* e or E letter */ + 2 /* exponent */);
548       break;
549 
550     // Floating point number in the form '[-]0xh.hhhhp±dd'.
551     case analyze_format_string::ConversionSpecifier::aArg:
552     case analyze_format_string::ConversionSpecifier::AArg:
553       Size +=
554           std::max(FieldWidth,
555                    2 /* 0x */ + 1 /* integer part */ +
556                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
557                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
558       break;
559 
560     // Just a string.
561     case analyze_format_string::ConversionSpecifier::sArg:
562     case analyze_format_string::ConversionSpecifier::SArg:
563       Size += FieldWidth;
564       break;
565 
566     // Just a pointer in the form '0xddd'.
567     case analyze_format_string::ConversionSpecifier::pArg:
568       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
569       break;
570 
571     // A plain percent.
572     case analyze_format_string::ConversionSpecifier::PercentArg:
573       Size += 1;
574       break;
575 
576     default:
577       break;
578     }
579 
580     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
581 
582     if (FS.hasAlternativeForm()) {
583       switch (FS.getConversionSpecifier().getKind()) {
584       default:
585         break;
586       // Force a leading '0'.
587       case analyze_format_string::ConversionSpecifier::oArg:
588         Size += 1;
589         break;
590       // Force a leading '0x'.
591       case analyze_format_string::ConversionSpecifier::xArg:
592       case analyze_format_string::ConversionSpecifier::XArg:
593         Size += 2;
594         break;
595       // Force a period '.' before decimal, even if precision is 0.
596       case analyze_format_string::ConversionSpecifier::aArg:
597       case analyze_format_string::ConversionSpecifier::AArg:
598       case analyze_format_string::ConversionSpecifier::eArg:
599       case analyze_format_string::ConversionSpecifier::EArg:
600       case analyze_format_string::ConversionSpecifier::fArg:
601       case analyze_format_string::ConversionSpecifier::FArg:
602       case analyze_format_string::ConversionSpecifier::gArg:
603       case analyze_format_string::ConversionSpecifier::GArg:
604         Size += (Precision ? 0 : 1);
605         break;
606       }
607     }
608     assert(SpecifierLen <= Size && "no underflow");
609     Size -= SpecifierLen;
610     return true;
611   }
612 
613   size_t getSizeLowerBound() const { return Size; }
614 
615 private:
616   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
617     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
618     size_t FieldWidth = 0;
619     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
620       FieldWidth = FW.getConstantAmount();
621     return FieldWidth;
622   }
623 
624   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
625     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
626     size_t Precision = 0;
627 
628     // See man 3 printf for default precision value based on the specifier.
629     switch (FW.getHowSpecified()) {
630     case analyze_format_string::OptionalAmount::NotSpecified:
631       switch (FS.getConversionSpecifier().getKind()) {
632       default:
633         break;
634       case analyze_format_string::ConversionSpecifier::dArg: // %d
635       case analyze_format_string::ConversionSpecifier::DArg: // %D
636       case analyze_format_string::ConversionSpecifier::iArg: // %i
637         Precision = 1;
638         break;
639       case analyze_format_string::ConversionSpecifier::oArg: // %d
640       case analyze_format_string::ConversionSpecifier::OArg: // %D
641       case analyze_format_string::ConversionSpecifier::uArg: // %d
642       case analyze_format_string::ConversionSpecifier::UArg: // %D
643       case analyze_format_string::ConversionSpecifier::xArg: // %d
644       case analyze_format_string::ConversionSpecifier::XArg: // %D
645         Precision = 1;
646         break;
647       case analyze_format_string::ConversionSpecifier::fArg: // %f
648       case analyze_format_string::ConversionSpecifier::FArg: // %F
649       case analyze_format_string::ConversionSpecifier::eArg: // %e
650       case analyze_format_string::ConversionSpecifier::EArg: // %E
651       case analyze_format_string::ConversionSpecifier::gArg: // %g
652       case analyze_format_string::ConversionSpecifier::GArg: // %G
653         Precision = 6;
654         break;
655       case analyze_format_string::ConversionSpecifier::pArg: // %d
656         Precision = 1;
657         break;
658       }
659       break;
660     case analyze_format_string::OptionalAmount::Constant:
661       Precision = FW.getConstantAmount();
662       break;
663     default:
664       break;
665     }
666     return Precision;
667   }
668 };
669 
670 } // namespace
671 
672 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
673                                                CallExpr *TheCall) {
674   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
675       isConstantEvaluated())
676     return;
677 
678   bool UseDABAttr = false;
679   const FunctionDecl *UseDecl = FD;
680 
681   const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
682   if (DABAttr) {
683     UseDecl = DABAttr->getFunction();
684     assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
685     UseDABAttr = true;
686   }
687 
688   unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
689 
690   if (!BuiltinID)
691     return;
692 
693   const TargetInfo &TI = getASTContext().getTargetInfo();
694   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
695 
696   auto TranslateIndex = [&](unsigned Index) -> Optional<unsigned> {
697     // If we refer to a diagnose_as_builtin attribute, we need to change the
698     // argument index to refer to the arguments of the called function. Unless
699     // the index is out of bounds, which presumably means it's a variadic
700     // function.
701     if (!UseDABAttr)
702       return Index;
703     unsigned DABIndices = DABAttr->argIndices_size();
704     unsigned NewIndex = Index < DABIndices
705                             ? DABAttr->argIndices_begin()[Index]
706                             : Index - DABIndices + FD->getNumParams();
707     if (NewIndex >= TheCall->getNumArgs())
708       return llvm::None;
709     return NewIndex;
710   };
711 
712   auto ComputeExplicitObjectSizeArgument =
713       [&](unsigned Index) -> Optional<llvm::APSInt> {
714     Optional<unsigned> IndexOptional = TranslateIndex(Index);
715     if (!IndexOptional)
716       return llvm::None;
717     unsigned NewIndex = IndexOptional.getValue();
718     Expr::EvalResult Result;
719     Expr *SizeArg = TheCall->getArg(NewIndex);
720     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
721       return llvm::None;
722     llvm::APSInt Integer = Result.Val.getInt();
723     Integer.setIsUnsigned(true);
724     return Integer;
725   };
726 
727   auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
728     // If the parameter has a pass_object_size attribute, then we should use its
729     // (potentially) more strict checking mode. Otherwise, conservatively assume
730     // type 0.
731     int BOSType = 0;
732     // This check can fail for variadic functions.
733     if (Index < FD->getNumParams()) {
734       if (const auto *POS =
735               FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
736         BOSType = POS->getType();
737     }
738 
739     Optional<unsigned> IndexOptional = TranslateIndex(Index);
740     if (!IndexOptional)
741       return llvm::None;
742     unsigned NewIndex = IndexOptional.getValue();
743 
744     const Expr *ObjArg = TheCall->getArg(NewIndex);
745     uint64_t Result;
746     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
747       return llvm::None;
748 
749     // Get the object size in the target's size_t width.
750     return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
751   };
752 
753   auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
754     Optional<unsigned> IndexOptional = TranslateIndex(Index);
755     if (!IndexOptional)
756       return llvm::None;
757     unsigned NewIndex = IndexOptional.getValue();
758 
759     const Expr *ObjArg = TheCall->getArg(NewIndex);
760     uint64_t Result;
761     if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
762       return llvm::None;
763     // Add 1 for null byte.
764     return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
765   };
766 
767   Optional<llvm::APSInt> SourceSize;
768   Optional<llvm::APSInt> DestinationSize;
769   unsigned DiagID = 0;
770   bool IsChkVariant = false;
771 
772   auto GetFunctionName = [&]() {
773     StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
774     // Skim off the details of whichever builtin was called to produce a better
775     // diagnostic, as it's unlikely that the user wrote the __builtin
776     // explicitly.
777     if (IsChkVariant) {
778       FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
779       FunctionName = FunctionName.drop_back(std::strlen("_chk"));
780     } else if (FunctionName.startswith("__builtin_")) {
781       FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
782     }
783     return FunctionName;
784   };
785 
786   switch (BuiltinID) {
787   default:
788     return;
789   case Builtin::BI__builtin_strcpy:
790   case Builtin::BIstrcpy: {
791     DiagID = diag::warn_fortify_strlen_overflow;
792     SourceSize = ComputeStrLenArgument(1);
793     DestinationSize = ComputeSizeArgument(0);
794     break;
795   }
796 
797   case Builtin::BI__builtin___strcpy_chk: {
798     DiagID = diag::warn_fortify_strlen_overflow;
799     SourceSize = ComputeStrLenArgument(1);
800     DestinationSize = ComputeExplicitObjectSizeArgument(2);
801     IsChkVariant = true;
802     break;
803   }
804 
805   case Builtin::BIscanf:
806   case Builtin::BIfscanf:
807   case Builtin::BIsscanf: {
808     unsigned FormatIndex = 1;
809     unsigned DataIndex = 2;
810     if (BuiltinID == Builtin::BIscanf) {
811       FormatIndex = 0;
812       DataIndex = 1;
813     }
814 
815     const auto *FormatExpr =
816         TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
817 
818     const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
819     if (!Format)
820       return;
821 
822     if (!Format->isAscii() && !Format->isUTF8())
823       return;
824 
825     auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
826                         unsigned SourceSize) {
827       DiagID = diag::warn_fortify_scanf_overflow;
828       unsigned Index = ArgIndex + DataIndex;
829       StringRef FunctionName = GetFunctionName();
830       DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
831                           PDiag(DiagID) << FunctionName << (Index + 1)
832                                         << DestSize << SourceSize);
833     };
834 
835     StringRef FormatStrRef = Format->getString();
836     auto ShiftedComputeSizeArgument = [&](unsigned Index) {
837       return ComputeSizeArgument(Index + DataIndex);
838     };
839     ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
840     const char *FormatBytes = FormatStrRef.data();
841     const ConstantArrayType *T =
842         Context.getAsConstantArrayType(Format->getType());
843     assert(T && "String literal not of constant array type!");
844     size_t TypeSize = T->getSize().getZExtValue();
845 
846     // In case there's a null byte somewhere.
847     size_t StrLen =
848         std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
849 
850     analyze_format_string::ParseScanfString(H, FormatBytes,
851                                             FormatBytes + StrLen, getLangOpts(),
852                                             Context.getTargetInfo());
853 
854     // Unlike the other cases, in this one we have already issued the diagnostic
855     // here, so no need to continue (because unlike the other cases, here the
856     // diagnostic refers to the argument number).
857     return;
858   }
859 
860   case Builtin::BIsprintf:
861   case Builtin::BI__builtin___sprintf_chk: {
862     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
863     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
864 
865     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
866 
867       if (!Format->isAscii() && !Format->isUTF8())
868         return;
869 
870       StringRef FormatStrRef = Format->getString();
871       EstimateSizeFormatHandler H(FormatStrRef);
872       const char *FormatBytes = FormatStrRef.data();
873       const ConstantArrayType *T =
874           Context.getAsConstantArrayType(Format->getType());
875       assert(T && "String literal not of constant array type!");
876       size_t TypeSize = T->getSize().getZExtValue();
877 
878       // In case there's a null byte somewhere.
879       size_t StrLen =
880           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
881       if (!analyze_format_string::ParsePrintfString(
882               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
883               Context.getTargetInfo(), false)) {
884         DiagID = diag::warn_fortify_source_format_overflow;
885         SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
886                          .extOrTrunc(SizeTypeWidth);
887         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
888           DestinationSize = ComputeExplicitObjectSizeArgument(2);
889           IsChkVariant = true;
890         } else {
891           DestinationSize = ComputeSizeArgument(0);
892         }
893         break;
894       }
895     }
896     return;
897   }
898   case Builtin::BI__builtin___memcpy_chk:
899   case Builtin::BI__builtin___memmove_chk:
900   case Builtin::BI__builtin___memset_chk:
901   case Builtin::BI__builtin___strlcat_chk:
902   case Builtin::BI__builtin___strlcpy_chk:
903   case Builtin::BI__builtin___strncat_chk:
904   case Builtin::BI__builtin___strncpy_chk:
905   case Builtin::BI__builtin___stpncpy_chk:
906   case Builtin::BI__builtin___memccpy_chk:
907   case Builtin::BI__builtin___mempcpy_chk: {
908     DiagID = diag::warn_builtin_chk_overflow;
909     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
910     DestinationSize =
911         ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
912     IsChkVariant = true;
913     break;
914   }
915 
916   case Builtin::BI__builtin___snprintf_chk:
917   case Builtin::BI__builtin___vsnprintf_chk: {
918     DiagID = diag::warn_builtin_chk_overflow;
919     SourceSize = ComputeExplicitObjectSizeArgument(1);
920     DestinationSize = ComputeExplicitObjectSizeArgument(3);
921     IsChkVariant = true;
922     break;
923   }
924 
925   case Builtin::BIstrncat:
926   case Builtin::BI__builtin_strncat:
927   case Builtin::BIstrncpy:
928   case Builtin::BI__builtin_strncpy:
929   case Builtin::BIstpncpy:
930   case Builtin::BI__builtin_stpncpy: {
931     // Whether these functions overflow depends on the runtime strlen of the
932     // string, not just the buffer size, so emitting the "always overflow"
933     // diagnostic isn't quite right. We should still diagnose passing a buffer
934     // size larger than the destination buffer though; this is a runtime abort
935     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
936     DiagID = diag::warn_fortify_source_size_mismatch;
937     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
938     DestinationSize = ComputeSizeArgument(0);
939     break;
940   }
941 
942   case Builtin::BImemcpy:
943   case Builtin::BI__builtin_memcpy:
944   case Builtin::BImemmove:
945   case Builtin::BI__builtin_memmove:
946   case Builtin::BImemset:
947   case Builtin::BI__builtin_memset:
948   case Builtin::BImempcpy:
949   case Builtin::BI__builtin_mempcpy: {
950     DiagID = diag::warn_fortify_source_overflow;
951     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
952     DestinationSize = ComputeSizeArgument(0);
953     break;
954   }
955   case Builtin::BIsnprintf:
956   case Builtin::BI__builtin_snprintf:
957   case Builtin::BIvsnprintf:
958   case Builtin::BI__builtin_vsnprintf: {
959     DiagID = diag::warn_fortify_source_size_mismatch;
960     SourceSize = ComputeExplicitObjectSizeArgument(1);
961     DestinationSize = ComputeSizeArgument(0);
962     break;
963   }
964   }
965 
966   if (!SourceSize || !DestinationSize ||
967       llvm::APSInt::compareValues(SourceSize.getValue(),
968                                   DestinationSize.getValue()) <= 0)
969     return;
970 
971   StringRef FunctionName = GetFunctionName();
972 
973   SmallString<16> DestinationStr;
974   SmallString<16> SourceStr;
975   DestinationSize->toString(DestinationStr, /*Radix=*/10);
976   SourceSize->toString(SourceStr, /*Radix=*/10);
977   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
978                       PDiag(DiagID)
979                           << FunctionName << DestinationStr << SourceStr);
980 }
981 
982 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
983                                      Scope::ScopeFlags NeededScopeFlags,
984                                      unsigned DiagID) {
985   // Scopes aren't available during instantiation. Fortunately, builtin
986   // functions cannot be template args so they cannot be formed through template
987   // instantiation. Therefore checking once during the parse is sufficient.
988   if (SemaRef.inTemplateInstantiation())
989     return false;
990 
991   Scope *S = SemaRef.getCurScope();
992   while (S && !S->isSEHExceptScope())
993     S = S->getParent();
994   if (!S || !(S->getFlags() & NeededScopeFlags)) {
995     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
996     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
997         << DRE->getDecl()->getIdentifier();
998     return true;
999   }
1000 
1001   return false;
1002 }
1003 
1004 static inline bool isBlockPointer(Expr *Arg) {
1005   return Arg->getType()->isBlockPointerType();
1006 }
1007 
1008 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
1009 /// void*, which is a requirement of device side enqueue.
1010 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
1011   const BlockPointerType *BPT =
1012       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1013   ArrayRef<QualType> Params =
1014       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
1015   unsigned ArgCounter = 0;
1016   bool IllegalParams = false;
1017   // Iterate through the block parameters until either one is found that is not
1018   // a local void*, or the block is valid.
1019   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
1020        I != E; ++I, ++ArgCounter) {
1021     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
1022         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
1023             LangAS::opencl_local) {
1024       // Get the location of the error. If a block literal has been passed
1025       // (BlockExpr) then we can point straight to the offending argument,
1026       // else we just point to the variable reference.
1027       SourceLocation ErrorLoc;
1028       if (isa<BlockExpr>(BlockArg)) {
1029         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
1030         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
1031       } else if (isa<DeclRefExpr>(BlockArg)) {
1032         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
1033       }
1034       S.Diag(ErrorLoc,
1035              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
1036       IllegalParams = true;
1037     }
1038   }
1039 
1040   return IllegalParams;
1041 }
1042 
1043 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
1044   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) {
1045     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
1046         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
1047     return true;
1048   }
1049   return false;
1050 }
1051 
1052 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
1053   if (checkArgCount(S, TheCall, 2))
1054     return true;
1055 
1056   if (checkOpenCLSubgroupExt(S, TheCall))
1057     return true;
1058 
1059   // First argument is an ndrange_t type.
1060   Expr *NDRangeArg = TheCall->getArg(0);
1061   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1062     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1063         << TheCall->getDirectCallee() << "'ndrange_t'";
1064     return true;
1065   }
1066 
1067   Expr *BlockArg = TheCall->getArg(1);
1068   if (!isBlockPointer(BlockArg)) {
1069     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1070         << TheCall->getDirectCallee() << "block";
1071     return true;
1072   }
1073   return checkOpenCLBlockArgs(S, BlockArg);
1074 }
1075 
1076 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
1077 /// get_kernel_work_group_size
1078 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
1079 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
1080   if (checkArgCount(S, TheCall, 1))
1081     return true;
1082 
1083   Expr *BlockArg = TheCall->getArg(0);
1084   if (!isBlockPointer(BlockArg)) {
1085     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1086         << TheCall->getDirectCallee() << "block";
1087     return true;
1088   }
1089   return checkOpenCLBlockArgs(S, BlockArg);
1090 }
1091 
1092 /// Diagnose integer type and any valid implicit conversion to it.
1093 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
1094                                       const QualType &IntType);
1095 
1096 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
1097                                             unsigned Start, unsigned End) {
1098   bool IllegalParams = false;
1099   for (unsigned I = Start; I <= End; ++I)
1100     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
1101                                               S.Context.getSizeType());
1102   return IllegalParams;
1103 }
1104 
1105 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
1106 /// 'local void*' parameter of passed block.
1107 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
1108                                            Expr *BlockArg,
1109                                            unsigned NumNonVarArgs) {
1110   const BlockPointerType *BPT =
1111       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1112   unsigned NumBlockParams =
1113       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
1114   unsigned TotalNumArgs = TheCall->getNumArgs();
1115 
1116   // For each argument passed to the block, a corresponding uint needs to
1117   // be passed to describe the size of the local memory.
1118   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
1119     S.Diag(TheCall->getBeginLoc(),
1120            diag::err_opencl_enqueue_kernel_local_size_args);
1121     return true;
1122   }
1123 
1124   // Check that the sizes of the local memory are specified by integers.
1125   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
1126                                          TotalNumArgs - 1);
1127 }
1128 
1129 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
1130 /// overload formats specified in Table 6.13.17.1.
1131 /// int enqueue_kernel(queue_t queue,
1132 ///                    kernel_enqueue_flags_t flags,
1133 ///                    const ndrange_t ndrange,
1134 ///                    void (^block)(void))
1135 /// int enqueue_kernel(queue_t queue,
1136 ///                    kernel_enqueue_flags_t flags,
1137 ///                    const ndrange_t ndrange,
1138 ///                    uint num_events_in_wait_list,
1139 ///                    clk_event_t *event_wait_list,
1140 ///                    clk_event_t *event_ret,
1141 ///                    void (^block)(void))
1142 /// int enqueue_kernel(queue_t queue,
1143 ///                    kernel_enqueue_flags_t flags,
1144 ///                    const ndrange_t ndrange,
1145 ///                    void (^block)(local void*, ...),
1146 ///                    uint size0, ...)
1147 /// int enqueue_kernel(queue_t queue,
1148 ///                    kernel_enqueue_flags_t flags,
1149 ///                    const ndrange_t ndrange,
1150 ///                    uint num_events_in_wait_list,
1151 ///                    clk_event_t *event_wait_list,
1152 ///                    clk_event_t *event_ret,
1153 ///                    void (^block)(local void*, ...),
1154 ///                    uint size0, ...)
1155 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
1156   unsigned NumArgs = TheCall->getNumArgs();
1157 
1158   if (NumArgs < 4) {
1159     S.Diag(TheCall->getBeginLoc(),
1160            diag::err_typecheck_call_too_few_args_at_least)
1161         << 0 << 4 << NumArgs;
1162     return true;
1163   }
1164 
1165   Expr *Arg0 = TheCall->getArg(0);
1166   Expr *Arg1 = TheCall->getArg(1);
1167   Expr *Arg2 = TheCall->getArg(2);
1168   Expr *Arg3 = TheCall->getArg(3);
1169 
1170   // First argument always needs to be a queue_t type.
1171   if (!Arg0->getType()->isQueueT()) {
1172     S.Diag(TheCall->getArg(0)->getBeginLoc(),
1173            diag::err_opencl_builtin_expected_type)
1174         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
1175     return true;
1176   }
1177 
1178   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
1179   if (!Arg1->getType()->isIntegerType()) {
1180     S.Diag(TheCall->getArg(1)->getBeginLoc(),
1181            diag::err_opencl_builtin_expected_type)
1182         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
1183     return true;
1184   }
1185 
1186   // Third argument is always an ndrange_t type.
1187   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1188     S.Diag(TheCall->getArg(2)->getBeginLoc(),
1189            diag::err_opencl_builtin_expected_type)
1190         << TheCall->getDirectCallee() << "'ndrange_t'";
1191     return true;
1192   }
1193 
1194   // With four arguments, there is only one form that the function could be
1195   // called in: no events and no variable arguments.
1196   if (NumArgs == 4) {
1197     // check that the last argument is the right block type.
1198     if (!isBlockPointer(Arg3)) {
1199       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1200           << TheCall->getDirectCallee() << "block";
1201       return true;
1202     }
1203     // we have a block type, check the prototype
1204     const BlockPointerType *BPT =
1205         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1206     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1207       S.Diag(Arg3->getBeginLoc(),
1208              diag::err_opencl_enqueue_kernel_blocks_no_args);
1209       return true;
1210     }
1211     return false;
1212   }
1213   // we can have block + varargs.
1214   if (isBlockPointer(Arg3))
1215     return (checkOpenCLBlockArgs(S, Arg3) ||
1216             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1217   // last two cases with either exactly 7 args or 7 args and varargs.
1218   if (NumArgs >= 7) {
1219     // check common block argument.
1220     Expr *Arg6 = TheCall->getArg(6);
1221     if (!isBlockPointer(Arg6)) {
1222       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1223           << TheCall->getDirectCallee() << "block";
1224       return true;
1225     }
1226     if (checkOpenCLBlockArgs(S, Arg6))
1227       return true;
1228 
1229     // Forth argument has to be any integer type.
1230     if (!Arg3->getType()->isIntegerType()) {
1231       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1232              diag::err_opencl_builtin_expected_type)
1233           << TheCall->getDirectCallee() << "integer";
1234       return true;
1235     }
1236     // check remaining common arguments.
1237     Expr *Arg4 = TheCall->getArg(4);
1238     Expr *Arg5 = TheCall->getArg(5);
1239 
1240     // Fifth argument is always passed as a pointer to clk_event_t.
1241     if (!Arg4->isNullPointerConstant(S.Context,
1242                                      Expr::NPC_ValueDependentIsNotNull) &&
1243         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1244       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1245              diag::err_opencl_builtin_expected_type)
1246           << TheCall->getDirectCallee()
1247           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1248       return true;
1249     }
1250 
1251     // Sixth argument is always passed as a pointer to clk_event_t.
1252     if (!Arg5->isNullPointerConstant(S.Context,
1253                                      Expr::NPC_ValueDependentIsNotNull) &&
1254         !(Arg5->getType()->isPointerType() &&
1255           Arg5->getType()->getPointeeType()->isClkEventT())) {
1256       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1257              diag::err_opencl_builtin_expected_type)
1258           << TheCall->getDirectCallee()
1259           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1260       return true;
1261     }
1262 
1263     if (NumArgs == 7)
1264       return false;
1265 
1266     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1267   }
1268 
1269   // None of the specific case has been detected, give generic error
1270   S.Diag(TheCall->getBeginLoc(),
1271          diag::err_opencl_enqueue_kernel_incorrect_args);
1272   return true;
1273 }
1274 
1275 /// Returns OpenCL access qual.
1276 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1277     return D->getAttr<OpenCLAccessAttr>();
1278 }
1279 
1280 /// Returns true if pipe element type is different from the pointer.
1281 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1282   const Expr *Arg0 = Call->getArg(0);
1283   // First argument type should always be pipe.
1284   if (!Arg0->getType()->isPipeType()) {
1285     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1286         << Call->getDirectCallee() << Arg0->getSourceRange();
1287     return true;
1288   }
1289   OpenCLAccessAttr *AccessQual =
1290       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1291   // Validates the access qualifier is compatible with the call.
1292   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1293   // read_only and write_only, and assumed to be read_only if no qualifier is
1294   // specified.
1295   switch (Call->getDirectCallee()->getBuiltinID()) {
1296   case Builtin::BIread_pipe:
1297   case Builtin::BIreserve_read_pipe:
1298   case Builtin::BIcommit_read_pipe:
1299   case Builtin::BIwork_group_reserve_read_pipe:
1300   case Builtin::BIsub_group_reserve_read_pipe:
1301   case Builtin::BIwork_group_commit_read_pipe:
1302   case Builtin::BIsub_group_commit_read_pipe:
1303     if (!(!AccessQual || AccessQual->isReadOnly())) {
1304       S.Diag(Arg0->getBeginLoc(),
1305              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1306           << "read_only" << Arg0->getSourceRange();
1307       return true;
1308     }
1309     break;
1310   case Builtin::BIwrite_pipe:
1311   case Builtin::BIreserve_write_pipe:
1312   case Builtin::BIcommit_write_pipe:
1313   case Builtin::BIwork_group_reserve_write_pipe:
1314   case Builtin::BIsub_group_reserve_write_pipe:
1315   case Builtin::BIwork_group_commit_write_pipe:
1316   case Builtin::BIsub_group_commit_write_pipe:
1317     if (!(AccessQual && AccessQual->isWriteOnly())) {
1318       S.Diag(Arg0->getBeginLoc(),
1319              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1320           << "write_only" << Arg0->getSourceRange();
1321       return true;
1322     }
1323     break;
1324   default:
1325     break;
1326   }
1327   return false;
1328 }
1329 
1330 /// Returns true if pipe element type is different from the pointer.
1331 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1332   const Expr *Arg0 = Call->getArg(0);
1333   const Expr *ArgIdx = Call->getArg(Idx);
1334   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1335   const QualType EltTy = PipeTy->getElementType();
1336   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1337   // The Idx argument should be a pointer and the type of the pointer and
1338   // the type of pipe element should also be the same.
1339   if (!ArgTy ||
1340       !S.Context.hasSameType(
1341           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1342     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1343         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1344         << ArgIdx->getType() << ArgIdx->getSourceRange();
1345     return true;
1346   }
1347   return false;
1348 }
1349 
1350 // Performs semantic analysis for the read/write_pipe call.
1351 // \param S Reference to the semantic analyzer.
1352 // \param Call A pointer to the builtin call.
1353 // \return True if a semantic error has been found, false otherwise.
1354 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1355   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1356   // functions have two forms.
1357   switch (Call->getNumArgs()) {
1358   case 2:
1359     if (checkOpenCLPipeArg(S, Call))
1360       return true;
1361     // The call with 2 arguments should be
1362     // read/write_pipe(pipe T, T*).
1363     // Check packet type T.
1364     if (checkOpenCLPipePacketType(S, Call, 1))
1365       return true;
1366     break;
1367 
1368   case 4: {
1369     if (checkOpenCLPipeArg(S, Call))
1370       return true;
1371     // The call with 4 arguments should be
1372     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1373     // Check reserve_id_t.
1374     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1375       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1376           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1377           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1378       return true;
1379     }
1380 
1381     // Check the index.
1382     const Expr *Arg2 = Call->getArg(2);
1383     if (!Arg2->getType()->isIntegerType() &&
1384         !Arg2->getType()->isUnsignedIntegerType()) {
1385       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1386           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1387           << Arg2->getType() << Arg2->getSourceRange();
1388       return true;
1389     }
1390 
1391     // Check packet type T.
1392     if (checkOpenCLPipePacketType(S, Call, 3))
1393       return true;
1394   } break;
1395   default:
1396     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1397         << Call->getDirectCallee() << Call->getSourceRange();
1398     return true;
1399   }
1400 
1401   return false;
1402 }
1403 
1404 // Performs a semantic analysis on the {work_group_/sub_group_
1405 //        /_}reserve_{read/write}_pipe
1406 // \param S Reference to the semantic analyzer.
1407 // \param Call The call to the builtin function to be analyzed.
1408 // \return True if a semantic error was found, false otherwise.
1409 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1410   if (checkArgCount(S, Call, 2))
1411     return true;
1412 
1413   if (checkOpenCLPipeArg(S, Call))
1414     return true;
1415 
1416   // Check the reserve size.
1417   if (!Call->getArg(1)->getType()->isIntegerType() &&
1418       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1419     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1420         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1421         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1422     return true;
1423   }
1424 
1425   // Since return type of reserve_read/write_pipe built-in function is
1426   // reserve_id_t, which is not defined in the builtin def file , we used int
1427   // as return type and need to override the return type of these functions.
1428   Call->setType(S.Context.OCLReserveIDTy);
1429 
1430   return false;
1431 }
1432 
1433 // Performs a semantic analysis on {work_group_/sub_group_
1434 //        /_}commit_{read/write}_pipe
1435 // \param S Reference to the semantic analyzer.
1436 // \param Call The call to the builtin function to be analyzed.
1437 // \return True if a semantic error was found, false otherwise.
1438 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1439   if (checkArgCount(S, Call, 2))
1440     return true;
1441 
1442   if (checkOpenCLPipeArg(S, Call))
1443     return true;
1444 
1445   // Check reserve_id_t.
1446   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1447     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1448         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1449         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1450     return true;
1451   }
1452 
1453   return false;
1454 }
1455 
1456 // Performs a semantic analysis on the call to built-in Pipe
1457 //        Query Functions.
1458 // \param S Reference to the semantic analyzer.
1459 // \param Call The call to the builtin function to be analyzed.
1460 // \return True if a semantic error was found, false otherwise.
1461 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1462   if (checkArgCount(S, Call, 1))
1463     return true;
1464 
1465   if (!Call->getArg(0)->getType()->isPipeType()) {
1466     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1467         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1468     return true;
1469   }
1470 
1471   return false;
1472 }
1473 
1474 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1475 // Performs semantic analysis for the to_global/local/private call.
1476 // \param S Reference to the semantic analyzer.
1477 // \param BuiltinID ID of the builtin function.
1478 // \param Call A pointer to the builtin call.
1479 // \return True if a semantic error has been found, false otherwise.
1480 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1481                                     CallExpr *Call) {
1482   if (checkArgCount(S, Call, 1))
1483     return true;
1484 
1485   auto RT = Call->getArg(0)->getType();
1486   if (!RT->isPointerType() || RT->getPointeeType()
1487       .getAddressSpace() == LangAS::opencl_constant) {
1488     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1489         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1490     return true;
1491   }
1492 
1493   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1494     S.Diag(Call->getArg(0)->getBeginLoc(),
1495            diag::warn_opencl_generic_address_space_arg)
1496         << Call->getDirectCallee()->getNameInfo().getAsString()
1497         << Call->getArg(0)->getSourceRange();
1498   }
1499 
1500   RT = RT->getPointeeType();
1501   auto Qual = RT.getQualifiers();
1502   switch (BuiltinID) {
1503   case Builtin::BIto_global:
1504     Qual.setAddressSpace(LangAS::opencl_global);
1505     break;
1506   case Builtin::BIto_local:
1507     Qual.setAddressSpace(LangAS::opencl_local);
1508     break;
1509   case Builtin::BIto_private:
1510     Qual.setAddressSpace(LangAS::opencl_private);
1511     break;
1512   default:
1513     llvm_unreachable("Invalid builtin function");
1514   }
1515   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1516       RT.getUnqualifiedType(), Qual)));
1517 
1518   return false;
1519 }
1520 
1521 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1522   if (checkArgCount(S, TheCall, 1))
1523     return ExprError();
1524 
1525   // Compute __builtin_launder's parameter type from the argument.
1526   // The parameter type is:
1527   //  * The type of the argument if it's not an array or function type,
1528   //  Otherwise,
1529   //  * The decayed argument type.
1530   QualType ParamTy = [&]() {
1531     QualType ArgTy = TheCall->getArg(0)->getType();
1532     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1533       return S.Context.getPointerType(Ty->getElementType());
1534     if (ArgTy->isFunctionType()) {
1535       return S.Context.getPointerType(ArgTy);
1536     }
1537     return ArgTy;
1538   }();
1539 
1540   TheCall->setType(ParamTy);
1541 
1542   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1543     if (!ParamTy->isPointerType())
1544       return 0;
1545     if (ParamTy->isFunctionPointerType())
1546       return 1;
1547     if (ParamTy->isVoidPointerType())
1548       return 2;
1549     return llvm::Optional<unsigned>{};
1550   }();
1551   if (DiagSelect.hasValue()) {
1552     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1553         << DiagSelect.getValue() << TheCall->getSourceRange();
1554     return ExprError();
1555   }
1556 
1557   // We either have an incomplete class type, or we have a class template
1558   // whose instantiation has not been forced. Example:
1559   //
1560   //   template <class T> struct Foo { T value; };
1561   //   Foo<int> *p = nullptr;
1562   //   auto *d = __builtin_launder(p);
1563   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1564                             diag::err_incomplete_type))
1565     return ExprError();
1566 
1567   assert(ParamTy->getPointeeType()->isObjectType() &&
1568          "Unhandled non-object pointer case");
1569 
1570   InitializedEntity Entity =
1571       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1572   ExprResult Arg =
1573       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1574   if (Arg.isInvalid())
1575     return ExprError();
1576   TheCall->setArg(0, Arg.get());
1577 
1578   return TheCall;
1579 }
1580 
1581 // Emit an error and return true if the current architecture is not in the list
1582 // of supported architectures.
1583 static bool
1584 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1585                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1586   llvm::Triple::ArchType CurArch =
1587       S.getASTContext().getTargetInfo().getTriple().getArch();
1588   if (llvm::is_contained(SupportedArchs, CurArch))
1589     return false;
1590   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1591       << TheCall->getSourceRange();
1592   return true;
1593 }
1594 
1595 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1596                                  SourceLocation CallSiteLoc);
1597 
1598 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1599                                       CallExpr *TheCall) {
1600   switch (TI.getTriple().getArch()) {
1601   default:
1602     // Some builtins don't require additional checking, so just consider these
1603     // acceptable.
1604     return false;
1605   case llvm::Triple::arm:
1606   case llvm::Triple::armeb:
1607   case llvm::Triple::thumb:
1608   case llvm::Triple::thumbeb:
1609     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1610   case llvm::Triple::aarch64:
1611   case llvm::Triple::aarch64_32:
1612   case llvm::Triple::aarch64_be:
1613     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1614   case llvm::Triple::bpfeb:
1615   case llvm::Triple::bpfel:
1616     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1617   case llvm::Triple::hexagon:
1618     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1619   case llvm::Triple::mips:
1620   case llvm::Triple::mipsel:
1621   case llvm::Triple::mips64:
1622   case llvm::Triple::mips64el:
1623     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1624   case llvm::Triple::systemz:
1625     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1626   case llvm::Triple::x86:
1627   case llvm::Triple::x86_64:
1628     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1629   case llvm::Triple::ppc:
1630   case llvm::Triple::ppcle:
1631   case llvm::Triple::ppc64:
1632   case llvm::Triple::ppc64le:
1633     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1634   case llvm::Triple::amdgcn:
1635     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1636   case llvm::Triple::riscv32:
1637   case llvm::Triple::riscv64:
1638     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1639   }
1640 }
1641 
1642 ExprResult
1643 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1644                                CallExpr *TheCall) {
1645   ExprResult TheCallResult(TheCall);
1646 
1647   // Find out if any arguments are required to be integer constant expressions.
1648   unsigned ICEArguments = 0;
1649   ASTContext::GetBuiltinTypeError Error;
1650   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1651   if (Error != ASTContext::GE_None)
1652     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1653 
1654   // If any arguments are required to be ICE's, check and diagnose.
1655   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1656     // Skip arguments not required to be ICE's.
1657     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1658 
1659     llvm::APSInt Result;
1660     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1661       return true;
1662     ICEArguments &= ~(1 << ArgNo);
1663   }
1664 
1665   switch (BuiltinID) {
1666   case Builtin::BI__builtin___CFStringMakeConstantString:
1667     assert(TheCall->getNumArgs() == 1 &&
1668            "Wrong # arguments to builtin CFStringMakeConstantString");
1669     if (CheckObjCString(TheCall->getArg(0)))
1670       return ExprError();
1671     break;
1672   case Builtin::BI__builtin_ms_va_start:
1673   case Builtin::BI__builtin_stdarg_start:
1674   case Builtin::BI__builtin_va_start:
1675     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1676       return ExprError();
1677     break;
1678   case Builtin::BI__va_start: {
1679     switch (Context.getTargetInfo().getTriple().getArch()) {
1680     case llvm::Triple::aarch64:
1681     case llvm::Triple::arm:
1682     case llvm::Triple::thumb:
1683       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1684         return ExprError();
1685       break;
1686     default:
1687       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1688         return ExprError();
1689       break;
1690     }
1691     break;
1692   }
1693 
1694   // The acquire, release, and no fence variants are ARM and AArch64 only.
1695   case Builtin::BI_interlockedbittestandset_acq:
1696   case Builtin::BI_interlockedbittestandset_rel:
1697   case Builtin::BI_interlockedbittestandset_nf:
1698   case Builtin::BI_interlockedbittestandreset_acq:
1699   case Builtin::BI_interlockedbittestandreset_rel:
1700   case Builtin::BI_interlockedbittestandreset_nf:
1701     if (CheckBuiltinTargetSupport(
1702             *this, BuiltinID, TheCall,
1703             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1704       return ExprError();
1705     break;
1706 
1707   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1708   case Builtin::BI_bittest64:
1709   case Builtin::BI_bittestandcomplement64:
1710   case Builtin::BI_bittestandreset64:
1711   case Builtin::BI_bittestandset64:
1712   case Builtin::BI_interlockedbittestandreset64:
1713   case Builtin::BI_interlockedbittestandset64:
1714     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1715                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1716                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1717       return ExprError();
1718     break;
1719 
1720   case Builtin::BI__builtin_isgreater:
1721   case Builtin::BI__builtin_isgreaterequal:
1722   case Builtin::BI__builtin_isless:
1723   case Builtin::BI__builtin_islessequal:
1724   case Builtin::BI__builtin_islessgreater:
1725   case Builtin::BI__builtin_isunordered:
1726     if (SemaBuiltinUnorderedCompare(TheCall))
1727       return ExprError();
1728     break;
1729   case Builtin::BI__builtin_fpclassify:
1730     if (SemaBuiltinFPClassification(TheCall, 6))
1731       return ExprError();
1732     break;
1733   case Builtin::BI__builtin_isfinite:
1734   case Builtin::BI__builtin_isinf:
1735   case Builtin::BI__builtin_isinf_sign:
1736   case Builtin::BI__builtin_isnan:
1737   case Builtin::BI__builtin_isnormal:
1738   case Builtin::BI__builtin_signbit:
1739   case Builtin::BI__builtin_signbitf:
1740   case Builtin::BI__builtin_signbitl:
1741     if (SemaBuiltinFPClassification(TheCall, 1))
1742       return ExprError();
1743     break;
1744   case Builtin::BI__builtin_shufflevector:
1745     return SemaBuiltinShuffleVector(TheCall);
1746     // TheCall will be freed by the smart pointer here, but that's fine, since
1747     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1748   case Builtin::BI__builtin_prefetch:
1749     if (SemaBuiltinPrefetch(TheCall))
1750       return ExprError();
1751     break;
1752   case Builtin::BI__builtin_alloca_with_align:
1753     if (SemaBuiltinAllocaWithAlign(TheCall))
1754       return ExprError();
1755     LLVM_FALLTHROUGH;
1756   case Builtin::BI__builtin_alloca:
1757     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1758         << TheCall->getDirectCallee();
1759     break;
1760   case Builtin::BI__arithmetic_fence:
1761     if (SemaBuiltinArithmeticFence(TheCall))
1762       return ExprError();
1763     break;
1764   case Builtin::BI__assume:
1765   case Builtin::BI__builtin_assume:
1766     if (SemaBuiltinAssume(TheCall))
1767       return ExprError();
1768     break;
1769   case Builtin::BI__builtin_assume_aligned:
1770     if (SemaBuiltinAssumeAligned(TheCall))
1771       return ExprError();
1772     break;
1773   case Builtin::BI__builtin_dynamic_object_size:
1774   case Builtin::BI__builtin_object_size:
1775     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1776       return ExprError();
1777     break;
1778   case Builtin::BI__builtin_longjmp:
1779     if (SemaBuiltinLongjmp(TheCall))
1780       return ExprError();
1781     break;
1782   case Builtin::BI__builtin_setjmp:
1783     if (SemaBuiltinSetjmp(TheCall))
1784       return ExprError();
1785     break;
1786   case Builtin::BI__builtin_classify_type:
1787     if (checkArgCount(*this, TheCall, 1)) return true;
1788     TheCall->setType(Context.IntTy);
1789     break;
1790   case Builtin::BI__builtin_complex:
1791     if (SemaBuiltinComplex(TheCall))
1792       return ExprError();
1793     break;
1794   case Builtin::BI__builtin_constant_p: {
1795     if (checkArgCount(*this, TheCall, 1)) return true;
1796     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1797     if (Arg.isInvalid()) return true;
1798     TheCall->setArg(0, Arg.get());
1799     TheCall->setType(Context.IntTy);
1800     break;
1801   }
1802   case Builtin::BI__builtin_launder:
1803     return SemaBuiltinLaunder(*this, TheCall);
1804   case Builtin::BI__sync_fetch_and_add:
1805   case Builtin::BI__sync_fetch_and_add_1:
1806   case Builtin::BI__sync_fetch_and_add_2:
1807   case Builtin::BI__sync_fetch_and_add_4:
1808   case Builtin::BI__sync_fetch_and_add_8:
1809   case Builtin::BI__sync_fetch_and_add_16:
1810   case Builtin::BI__sync_fetch_and_sub:
1811   case Builtin::BI__sync_fetch_and_sub_1:
1812   case Builtin::BI__sync_fetch_and_sub_2:
1813   case Builtin::BI__sync_fetch_and_sub_4:
1814   case Builtin::BI__sync_fetch_and_sub_8:
1815   case Builtin::BI__sync_fetch_and_sub_16:
1816   case Builtin::BI__sync_fetch_and_or:
1817   case Builtin::BI__sync_fetch_and_or_1:
1818   case Builtin::BI__sync_fetch_and_or_2:
1819   case Builtin::BI__sync_fetch_and_or_4:
1820   case Builtin::BI__sync_fetch_and_or_8:
1821   case Builtin::BI__sync_fetch_and_or_16:
1822   case Builtin::BI__sync_fetch_and_and:
1823   case Builtin::BI__sync_fetch_and_and_1:
1824   case Builtin::BI__sync_fetch_and_and_2:
1825   case Builtin::BI__sync_fetch_and_and_4:
1826   case Builtin::BI__sync_fetch_and_and_8:
1827   case Builtin::BI__sync_fetch_and_and_16:
1828   case Builtin::BI__sync_fetch_and_xor:
1829   case Builtin::BI__sync_fetch_and_xor_1:
1830   case Builtin::BI__sync_fetch_and_xor_2:
1831   case Builtin::BI__sync_fetch_and_xor_4:
1832   case Builtin::BI__sync_fetch_and_xor_8:
1833   case Builtin::BI__sync_fetch_and_xor_16:
1834   case Builtin::BI__sync_fetch_and_nand:
1835   case Builtin::BI__sync_fetch_and_nand_1:
1836   case Builtin::BI__sync_fetch_and_nand_2:
1837   case Builtin::BI__sync_fetch_and_nand_4:
1838   case Builtin::BI__sync_fetch_and_nand_8:
1839   case Builtin::BI__sync_fetch_and_nand_16:
1840   case Builtin::BI__sync_add_and_fetch:
1841   case Builtin::BI__sync_add_and_fetch_1:
1842   case Builtin::BI__sync_add_and_fetch_2:
1843   case Builtin::BI__sync_add_and_fetch_4:
1844   case Builtin::BI__sync_add_and_fetch_8:
1845   case Builtin::BI__sync_add_and_fetch_16:
1846   case Builtin::BI__sync_sub_and_fetch:
1847   case Builtin::BI__sync_sub_and_fetch_1:
1848   case Builtin::BI__sync_sub_and_fetch_2:
1849   case Builtin::BI__sync_sub_and_fetch_4:
1850   case Builtin::BI__sync_sub_and_fetch_8:
1851   case Builtin::BI__sync_sub_and_fetch_16:
1852   case Builtin::BI__sync_and_and_fetch:
1853   case Builtin::BI__sync_and_and_fetch_1:
1854   case Builtin::BI__sync_and_and_fetch_2:
1855   case Builtin::BI__sync_and_and_fetch_4:
1856   case Builtin::BI__sync_and_and_fetch_8:
1857   case Builtin::BI__sync_and_and_fetch_16:
1858   case Builtin::BI__sync_or_and_fetch:
1859   case Builtin::BI__sync_or_and_fetch_1:
1860   case Builtin::BI__sync_or_and_fetch_2:
1861   case Builtin::BI__sync_or_and_fetch_4:
1862   case Builtin::BI__sync_or_and_fetch_8:
1863   case Builtin::BI__sync_or_and_fetch_16:
1864   case Builtin::BI__sync_xor_and_fetch:
1865   case Builtin::BI__sync_xor_and_fetch_1:
1866   case Builtin::BI__sync_xor_and_fetch_2:
1867   case Builtin::BI__sync_xor_and_fetch_4:
1868   case Builtin::BI__sync_xor_and_fetch_8:
1869   case Builtin::BI__sync_xor_and_fetch_16:
1870   case Builtin::BI__sync_nand_and_fetch:
1871   case Builtin::BI__sync_nand_and_fetch_1:
1872   case Builtin::BI__sync_nand_and_fetch_2:
1873   case Builtin::BI__sync_nand_and_fetch_4:
1874   case Builtin::BI__sync_nand_and_fetch_8:
1875   case Builtin::BI__sync_nand_and_fetch_16:
1876   case Builtin::BI__sync_val_compare_and_swap:
1877   case Builtin::BI__sync_val_compare_and_swap_1:
1878   case Builtin::BI__sync_val_compare_and_swap_2:
1879   case Builtin::BI__sync_val_compare_and_swap_4:
1880   case Builtin::BI__sync_val_compare_and_swap_8:
1881   case Builtin::BI__sync_val_compare_and_swap_16:
1882   case Builtin::BI__sync_bool_compare_and_swap:
1883   case Builtin::BI__sync_bool_compare_and_swap_1:
1884   case Builtin::BI__sync_bool_compare_and_swap_2:
1885   case Builtin::BI__sync_bool_compare_and_swap_4:
1886   case Builtin::BI__sync_bool_compare_and_swap_8:
1887   case Builtin::BI__sync_bool_compare_and_swap_16:
1888   case Builtin::BI__sync_lock_test_and_set:
1889   case Builtin::BI__sync_lock_test_and_set_1:
1890   case Builtin::BI__sync_lock_test_and_set_2:
1891   case Builtin::BI__sync_lock_test_and_set_4:
1892   case Builtin::BI__sync_lock_test_and_set_8:
1893   case Builtin::BI__sync_lock_test_and_set_16:
1894   case Builtin::BI__sync_lock_release:
1895   case Builtin::BI__sync_lock_release_1:
1896   case Builtin::BI__sync_lock_release_2:
1897   case Builtin::BI__sync_lock_release_4:
1898   case Builtin::BI__sync_lock_release_8:
1899   case Builtin::BI__sync_lock_release_16:
1900   case Builtin::BI__sync_swap:
1901   case Builtin::BI__sync_swap_1:
1902   case Builtin::BI__sync_swap_2:
1903   case Builtin::BI__sync_swap_4:
1904   case Builtin::BI__sync_swap_8:
1905   case Builtin::BI__sync_swap_16:
1906     return SemaBuiltinAtomicOverloaded(TheCallResult);
1907   case Builtin::BI__sync_synchronize:
1908     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1909         << TheCall->getCallee()->getSourceRange();
1910     break;
1911   case Builtin::BI__builtin_nontemporal_load:
1912   case Builtin::BI__builtin_nontemporal_store:
1913     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1914   case Builtin::BI__builtin_memcpy_inline: {
1915     clang::Expr *SizeOp = TheCall->getArg(2);
1916     // We warn about copying to or from `nullptr` pointers when `size` is
1917     // greater than 0. When `size` is value dependent we cannot evaluate its
1918     // value so we bail out.
1919     if (SizeOp->isValueDependent())
1920       break;
1921     if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
1922       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1923       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1924     }
1925     break;
1926   }
1927 #define BUILTIN(ID, TYPE, ATTRS)
1928 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1929   case Builtin::BI##ID: \
1930     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1931 #include "clang/Basic/Builtins.def"
1932   case Builtin::BI__annotation:
1933     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1934       return ExprError();
1935     break;
1936   case Builtin::BI__builtin_annotation:
1937     if (SemaBuiltinAnnotation(*this, TheCall))
1938       return ExprError();
1939     break;
1940   case Builtin::BI__builtin_addressof:
1941     if (SemaBuiltinAddressof(*this, TheCall))
1942       return ExprError();
1943     break;
1944   case Builtin::BI__builtin_function_start:
1945     if (SemaBuiltinFunctionStart(*this, TheCall))
1946       return ExprError();
1947     break;
1948   case Builtin::BI__builtin_is_aligned:
1949   case Builtin::BI__builtin_align_up:
1950   case Builtin::BI__builtin_align_down:
1951     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1952       return ExprError();
1953     break;
1954   case Builtin::BI__builtin_add_overflow:
1955   case Builtin::BI__builtin_sub_overflow:
1956   case Builtin::BI__builtin_mul_overflow:
1957     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1958       return ExprError();
1959     break;
1960   case Builtin::BI__builtin_operator_new:
1961   case Builtin::BI__builtin_operator_delete: {
1962     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1963     ExprResult Res =
1964         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1965     if (Res.isInvalid())
1966       CorrectDelayedTyposInExpr(TheCallResult.get());
1967     return Res;
1968   }
1969   case Builtin::BI__builtin_dump_struct: {
1970     // We first want to ensure we are called with 2 arguments
1971     if (checkArgCount(*this, TheCall, 2))
1972       return ExprError();
1973     // Ensure that the first argument is of type 'struct XX *'
1974     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1975     const QualType PtrArgType = PtrArg->getType();
1976     if (!PtrArgType->isPointerType() ||
1977         !PtrArgType->getPointeeType()->isRecordType()) {
1978       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1979           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1980           << "structure pointer";
1981       return ExprError();
1982     }
1983 
1984     // Ensure that the second argument is of type 'FunctionType'
1985     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1986     const QualType FnPtrArgType = FnPtrArg->getType();
1987     if (!FnPtrArgType->isPointerType()) {
1988       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1989           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1990           << FnPtrArgType << "'int (*)(const char *, ...)'";
1991       return ExprError();
1992     }
1993 
1994     const auto *FuncType =
1995         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1996 
1997     if (!FuncType) {
1998       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1999           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
2000           << FnPtrArgType << "'int (*)(const char *, ...)'";
2001       return ExprError();
2002     }
2003 
2004     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
2005       if (!FT->getNumParams()) {
2006         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2007             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
2008             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
2009         return ExprError();
2010       }
2011       QualType PT = FT->getParamType(0);
2012       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
2013           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
2014           !PT->getPointeeType().isConstQualified()) {
2015         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2016             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
2017             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
2018         return ExprError();
2019       }
2020     }
2021 
2022     TheCall->setType(Context.IntTy);
2023     break;
2024   }
2025   case Builtin::BI__builtin_expect_with_probability: {
2026     // We first want to ensure we are called with 3 arguments
2027     if (checkArgCount(*this, TheCall, 3))
2028       return ExprError();
2029     // then check probability is constant float in range [0.0, 1.0]
2030     const Expr *ProbArg = TheCall->getArg(2);
2031     SmallVector<PartialDiagnosticAt, 8> Notes;
2032     Expr::EvalResult Eval;
2033     Eval.Diag = &Notes;
2034     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
2035         !Eval.Val.isFloat()) {
2036       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
2037           << ProbArg->getSourceRange();
2038       for (const PartialDiagnosticAt &PDiag : Notes)
2039         Diag(PDiag.first, PDiag.second);
2040       return ExprError();
2041     }
2042     llvm::APFloat Probability = Eval.Val.getFloat();
2043     bool LoseInfo = false;
2044     Probability.convert(llvm::APFloat::IEEEdouble(),
2045                         llvm::RoundingMode::Dynamic, &LoseInfo);
2046     if (!(Probability >= llvm::APFloat(0.0) &&
2047           Probability <= llvm::APFloat(1.0))) {
2048       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
2049           << ProbArg->getSourceRange();
2050       return ExprError();
2051     }
2052     break;
2053   }
2054   case Builtin::BI__builtin_preserve_access_index:
2055     if (SemaBuiltinPreserveAI(*this, TheCall))
2056       return ExprError();
2057     break;
2058   case Builtin::BI__builtin_call_with_static_chain:
2059     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
2060       return ExprError();
2061     break;
2062   case Builtin::BI__exception_code:
2063   case Builtin::BI_exception_code:
2064     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
2065                                  diag::err_seh___except_block))
2066       return ExprError();
2067     break;
2068   case Builtin::BI__exception_info:
2069   case Builtin::BI_exception_info:
2070     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
2071                                  diag::err_seh___except_filter))
2072       return ExprError();
2073     break;
2074   case Builtin::BI__GetExceptionInfo:
2075     if (checkArgCount(*this, TheCall, 1))
2076       return ExprError();
2077 
2078     if (CheckCXXThrowOperand(
2079             TheCall->getBeginLoc(),
2080             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
2081             TheCall))
2082       return ExprError();
2083 
2084     TheCall->setType(Context.VoidPtrTy);
2085     break;
2086   // OpenCL v2.0, s6.13.16 - Pipe functions
2087   case Builtin::BIread_pipe:
2088   case Builtin::BIwrite_pipe:
2089     // Since those two functions are declared with var args, we need a semantic
2090     // check for the argument.
2091     if (SemaBuiltinRWPipe(*this, TheCall))
2092       return ExprError();
2093     break;
2094   case Builtin::BIreserve_read_pipe:
2095   case Builtin::BIreserve_write_pipe:
2096   case Builtin::BIwork_group_reserve_read_pipe:
2097   case Builtin::BIwork_group_reserve_write_pipe:
2098     if (SemaBuiltinReserveRWPipe(*this, TheCall))
2099       return ExprError();
2100     break;
2101   case Builtin::BIsub_group_reserve_read_pipe:
2102   case Builtin::BIsub_group_reserve_write_pipe:
2103     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2104         SemaBuiltinReserveRWPipe(*this, TheCall))
2105       return ExprError();
2106     break;
2107   case Builtin::BIcommit_read_pipe:
2108   case Builtin::BIcommit_write_pipe:
2109   case Builtin::BIwork_group_commit_read_pipe:
2110   case Builtin::BIwork_group_commit_write_pipe:
2111     if (SemaBuiltinCommitRWPipe(*this, TheCall))
2112       return ExprError();
2113     break;
2114   case Builtin::BIsub_group_commit_read_pipe:
2115   case Builtin::BIsub_group_commit_write_pipe:
2116     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2117         SemaBuiltinCommitRWPipe(*this, TheCall))
2118       return ExprError();
2119     break;
2120   case Builtin::BIget_pipe_num_packets:
2121   case Builtin::BIget_pipe_max_packets:
2122     if (SemaBuiltinPipePackets(*this, TheCall))
2123       return ExprError();
2124     break;
2125   case Builtin::BIto_global:
2126   case Builtin::BIto_local:
2127   case Builtin::BIto_private:
2128     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
2129       return ExprError();
2130     break;
2131   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
2132   case Builtin::BIenqueue_kernel:
2133     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
2134       return ExprError();
2135     break;
2136   case Builtin::BIget_kernel_work_group_size:
2137   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
2138     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
2139       return ExprError();
2140     break;
2141   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
2142   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
2143     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
2144       return ExprError();
2145     break;
2146   case Builtin::BI__builtin_os_log_format:
2147     Cleanup.setExprNeedsCleanups(true);
2148     LLVM_FALLTHROUGH;
2149   case Builtin::BI__builtin_os_log_format_buffer_size:
2150     if (SemaBuiltinOSLogFormat(TheCall))
2151       return ExprError();
2152     break;
2153   case Builtin::BI__builtin_frame_address:
2154   case Builtin::BI__builtin_return_address: {
2155     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
2156       return ExprError();
2157 
2158     // -Wframe-address warning if non-zero passed to builtin
2159     // return/frame address.
2160     Expr::EvalResult Result;
2161     if (!TheCall->getArg(0)->isValueDependent() &&
2162         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
2163         Result.Val.getInt() != 0)
2164       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
2165           << ((BuiltinID == Builtin::BI__builtin_return_address)
2166                   ? "__builtin_return_address"
2167                   : "__builtin_frame_address")
2168           << TheCall->getSourceRange();
2169     break;
2170   }
2171 
2172   // __builtin_elementwise_abs restricts the element type to signed integers or
2173   // floating point types only.
2174   case Builtin::BI__builtin_elementwise_abs: {
2175     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2176       return ExprError();
2177 
2178     QualType ArgTy = TheCall->getArg(0)->getType();
2179     QualType EltTy = ArgTy;
2180 
2181     if (auto *VecTy = EltTy->getAs<VectorType>())
2182       EltTy = VecTy->getElementType();
2183     if (EltTy->isUnsignedIntegerType()) {
2184       Diag(TheCall->getArg(0)->getBeginLoc(),
2185            diag::err_builtin_invalid_arg_type)
2186           << 1 << /* signed integer or float ty*/ 3 << ArgTy;
2187       return ExprError();
2188     }
2189     break;
2190   }
2191 
2192   // These builtins restrict the element type to floating point
2193   // types only.
2194   case Builtin::BI__builtin_elementwise_ceil:
2195   case Builtin::BI__builtin_elementwise_floor:
2196   case Builtin::BI__builtin_elementwise_roundeven:
2197   case Builtin::BI__builtin_elementwise_trunc: {
2198     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2199       return ExprError();
2200 
2201     QualType ArgTy = TheCall->getArg(0)->getType();
2202     QualType EltTy = ArgTy;
2203 
2204     if (auto *VecTy = EltTy->getAs<VectorType>())
2205       EltTy = VecTy->getElementType();
2206     if (!EltTy->isFloatingType()) {
2207       Diag(TheCall->getArg(0)->getBeginLoc(),
2208            diag::err_builtin_invalid_arg_type)
2209           << 1 << /* float ty*/ 5 << ArgTy;
2210 
2211       return ExprError();
2212     }
2213     break;
2214   }
2215 
2216   case Builtin::BI__builtin_elementwise_min:
2217   case Builtin::BI__builtin_elementwise_max:
2218     if (SemaBuiltinElementwiseMath(TheCall))
2219       return ExprError();
2220     break;
2221   case Builtin::BI__builtin_reduce_max:
2222   case Builtin::BI__builtin_reduce_min: {
2223     if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2224       return ExprError();
2225 
2226     const Expr *Arg = TheCall->getArg(0);
2227     const auto *TyA = Arg->getType()->getAs<VectorType>();
2228     if (!TyA) {
2229       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2230           << 1 << /* vector ty*/ 4 << Arg->getType();
2231       return ExprError();
2232     }
2233 
2234     TheCall->setType(TyA->getElementType());
2235     break;
2236   }
2237 
2238   // __builtin_reduce_xor supports vector of integers only.
2239   case Builtin::BI__builtin_reduce_xor: {
2240     if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2241       return ExprError();
2242 
2243     const Expr *Arg = TheCall->getArg(0);
2244     const auto *TyA = Arg->getType()->getAs<VectorType>();
2245     if (!TyA || !TyA->getElementType()->isIntegerType()) {
2246       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2247           << 1  << /* vector of integers */ 6 << Arg->getType();
2248       return ExprError();
2249     }
2250     TheCall->setType(TyA->getElementType());
2251     break;
2252   }
2253 
2254   case Builtin::BI__builtin_matrix_transpose:
2255     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
2256 
2257   case Builtin::BI__builtin_matrix_column_major_load:
2258     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
2259 
2260   case Builtin::BI__builtin_matrix_column_major_store:
2261     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
2262 
2263   case Builtin::BI__builtin_get_device_side_mangled_name: {
2264     auto Check = [](CallExpr *TheCall) {
2265       if (TheCall->getNumArgs() != 1)
2266         return false;
2267       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
2268       if (!DRE)
2269         return false;
2270       auto *D = DRE->getDecl();
2271       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
2272         return false;
2273       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
2274              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2275     };
2276     if (!Check(TheCall)) {
2277       Diag(TheCall->getBeginLoc(),
2278            diag::err_hip_invalid_args_builtin_mangled_name);
2279       return ExprError();
2280     }
2281   }
2282   }
2283 
2284   // Since the target specific builtins for each arch overlap, only check those
2285   // of the arch we are compiling for.
2286   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2287     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2288       assert(Context.getAuxTargetInfo() &&
2289              "Aux Target Builtin, but not an aux target?");
2290 
2291       if (CheckTSBuiltinFunctionCall(
2292               *Context.getAuxTargetInfo(),
2293               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2294         return ExprError();
2295     } else {
2296       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2297                                      TheCall))
2298         return ExprError();
2299     }
2300   }
2301 
2302   return TheCallResult;
2303 }
2304 
2305 // Get the valid immediate range for the specified NEON type code.
2306 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2307   NeonTypeFlags Type(t);
2308   int IsQuad = ForceQuad ? true : Type.isQuad();
2309   switch (Type.getEltType()) {
2310   case NeonTypeFlags::Int8:
2311   case NeonTypeFlags::Poly8:
2312     return shift ? 7 : (8 << IsQuad) - 1;
2313   case NeonTypeFlags::Int16:
2314   case NeonTypeFlags::Poly16:
2315     return shift ? 15 : (4 << IsQuad) - 1;
2316   case NeonTypeFlags::Int32:
2317     return shift ? 31 : (2 << IsQuad) - 1;
2318   case NeonTypeFlags::Int64:
2319   case NeonTypeFlags::Poly64:
2320     return shift ? 63 : (1 << IsQuad) - 1;
2321   case NeonTypeFlags::Poly128:
2322     return shift ? 127 : (1 << IsQuad) - 1;
2323   case NeonTypeFlags::Float16:
2324     assert(!shift && "cannot shift float types!");
2325     return (4 << IsQuad) - 1;
2326   case NeonTypeFlags::Float32:
2327     assert(!shift && "cannot shift float types!");
2328     return (2 << IsQuad) - 1;
2329   case NeonTypeFlags::Float64:
2330     assert(!shift && "cannot shift float types!");
2331     return (1 << IsQuad) - 1;
2332   case NeonTypeFlags::BFloat16:
2333     assert(!shift && "cannot shift float types!");
2334     return (4 << IsQuad) - 1;
2335   }
2336   llvm_unreachable("Invalid NeonTypeFlag!");
2337 }
2338 
2339 /// getNeonEltType - Return the QualType corresponding to the elements of
2340 /// the vector type specified by the NeonTypeFlags.  This is used to check
2341 /// the pointer arguments for Neon load/store intrinsics.
2342 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2343                                bool IsPolyUnsigned, bool IsInt64Long) {
2344   switch (Flags.getEltType()) {
2345   case NeonTypeFlags::Int8:
2346     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2347   case NeonTypeFlags::Int16:
2348     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2349   case NeonTypeFlags::Int32:
2350     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2351   case NeonTypeFlags::Int64:
2352     if (IsInt64Long)
2353       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2354     else
2355       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2356                                 : Context.LongLongTy;
2357   case NeonTypeFlags::Poly8:
2358     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2359   case NeonTypeFlags::Poly16:
2360     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2361   case NeonTypeFlags::Poly64:
2362     if (IsInt64Long)
2363       return Context.UnsignedLongTy;
2364     else
2365       return Context.UnsignedLongLongTy;
2366   case NeonTypeFlags::Poly128:
2367     break;
2368   case NeonTypeFlags::Float16:
2369     return Context.HalfTy;
2370   case NeonTypeFlags::Float32:
2371     return Context.FloatTy;
2372   case NeonTypeFlags::Float64:
2373     return Context.DoubleTy;
2374   case NeonTypeFlags::BFloat16:
2375     return Context.BFloat16Ty;
2376   }
2377   llvm_unreachable("Invalid NeonTypeFlag!");
2378 }
2379 
2380 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2381   // Range check SVE intrinsics that take immediate values.
2382   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2383 
2384   switch (BuiltinID) {
2385   default:
2386     return false;
2387 #define GET_SVE_IMMEDIATE_CHECK
2388 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2389 #undef GET_SVE_IMMEDIATE_CHECK
2390   }
2391 
2392   // Perform all the immediate checks for this builtin call.
2393   bool HasError = false;
2394   for (auto &I : ImmChecks) {
2395     int ArgNum, CheckTy, ElementSizeInBits;
2396     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2397 
2398     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2399 
2400     // Function that checks whether the operand (ArgNum) is an immediate
2401     // that is one of the predefined values.
2402     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2403                                    int ErrDiag) -> bool {
2404       // We can't check the value of a dependent argument.
2405       Expr *Arg = TheCall->getArg(ArgNum);
2406       if (Arg->isTypeDependent() || Arg->isValueDependent())
2407         return false;
2408 
2409       // Check constant-ness first.
2410       llvm::APSInt Imm;
2411       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2412         return true;
2413 
2414       if (!CheckImm(Imm.getSExtValue()))
2415         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2416       return false;
2417     };
2418 
2419     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2420     case SVETypeFlags::ImmCheck0_31:
2421       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2422         HasError = true;
2423       break;
2424     case SVETypeFlags::ImmCheck0_13:
2425       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2426         HasError = true;
2427       break;
2428     case SVETypeFlags::ImmCheck1_16:
2429       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2430         HasError = true;
2431       break;
2432     case SVETypeFlags::ImmCheck0_7:
2433       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2434         HasError = true;
2435       break;
2436     case SVETypeFlags::ImmCheckExtract:
2437       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2438                                       (2048 / ElementSizeInBits) - 1))
2439         HasError = true;
2440       break;
2441     case SVETypeFlags::ImmCheckShiftRight:
2442       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2443         HasError = true;
2444       break;
2445     case SVETypeFlags::ImmCheckShiftRightNarrow:
2446       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2447                                       ElementSizeInBits / 2))
2448         HasError = true;
2449       break;
2450     case SVETypeFlags::ImmCheckShiftLeft:
2451       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2452                                       ElementSizeInBits - 1))
2453         HasError = true;
2454       break;
2455     case SVETypeFlags::ImmCheckLaneIndex:
2456       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2457                                       (128 / (1 * ElementSizeInBits)) - 1))
2458         HasError = true;
2459       break;
2460     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2461       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2462                                       (128 / (2 * ElementSizeInBits)) - 1))
2463         HasError = true;
2464       break;
2465     case SVETypeFlags::ImmCheckLaneIndexDot:
2466       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2467                                       (128 / (4 * ElementSizeInBits)) - 1))
2468         HasError = true;
2469       break;
2470     case SVETypeFlags::ImmCheckComplexRot90_270:
2471       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2472                               diag::err_rotation_argument_to_cadd))
2473         HasError = true;
2474       break;
2475     case SVETypeFlags::ImmCheckComplexRotAll90:
2476       if (CheckImmediateInSet(
2477               [](int64_t V) {
2478                 return V == 0 || V == 90 || V == 180 || V == 270;
2479               },
2480               diag::err_rotation_argument_to_cmla))
2481         HasError = true;
2482       break;
2483     case SVETypeFlags::ImmCheck0_1:
2484       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2485         HasError = true;
2486       break;
2487     case SVETypeFlags::ImmCheck0_2:
2488       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2489         HasError = true;
2490       break;
2491     case SVETypeFlags::ImmCheck0_3:
2492       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2493         HasError = true;
2494       break;
2495     }
2496   }
2497 
2498   return HasError;
2499 }
2500 
2501 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2502                                         unsigned BuiltinID, CallExpr *TheCall) {
2503   llvm::APSInt Result;
2504   uint64_t mask = 0;
2505   unsigned TV = 0;
2506   int PtrArgNum = -1;
2507   bool HasConstPtr = false;
2508   switch (BuiltinID) {
2509 #define GET_NEON_OVERLOAD_CHECK
2510 #include "clang/Basic/arm_neon.inc"
2511 #include "clang/Basic/arm_fp16.inc"
2512 #undef GET_NEON_OVERLOAD_CHECK
2513   }
2514 
2515   // For NEON intrinsics which are overloaded on vector element type, validate
2516   // the immediate which specifies which variant to emit.
2517   unsigned ImmArg = TheCall->getNumArgs()-1;
2518   if (mask) {
2519     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2520       return true;
2521 
2522     TV = Result.getLimitedValue(64);
2523     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2524       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2525              << TheCall->getArg(ImmArg)->getSourceRange();
2526   }
2527 
2528   if (PtrArgNum >= 0) {
2529     // Check that pointer arguments have the specified type.
2530     Expr *Arg = TheCall->getArg(PtrArgNum);
2531     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2532       Arg = ICE->getSubExpr();
2533     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2534     QualType RHSTy = RHS.get()->getType();
2535 
2536     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2537     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2538                           Arch == llvm::Triple::aarch64_32 ||
2539                           Arch == llvm::Triple::aarch64_be;
2540     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2541     QualType EltTy =
2542         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2543     if (HasConstPtr)
2544       EltTy = EltTy.withConst();
2545     QualType LHSTy = Context.getPointerType(EltTy);
2546     AssignConvertType ConvTy;
2547     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2548     if (RHS.isInvalid())
2549       return true;
2550     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2551                                  RHS.get(), AA_Assigning))
2552       return true;
2553   }
2554 
2555   // For NEON intrinsics which take an immediate value as part of the
2556   // instruction, range check them here.
2557   unsigned i = 0, l = 0, u = 0;
2558   switch (BuiltinID) {
2559   default:
2560     return false;
2561   #define GET_NEON_IMMEDIATE_CHECK
2562   #include "clang/Basic/arm_neon.inc"
2563   #include "clang/Basic/arm_fp16.inc"
2564   #undef GET_NEON_IMMEDIATE_CHECK
2565   }
2566 
2567   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2568 }
2569 
2570 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2571   switch (BuiltinID) {
2572   default:
2573     return false;
2574   #include "clang/Basic/arm_mve_builtin_sema.inc"
2575   }
2576 }
2577 
2578 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2579                                        CallExpr *TheCall) {
2580   bool Err = false;
2581   switch (BuiltinID) {
2582   default:
2583     return false;
2584 #include "clang/Basic/arm_cde_builtin_sema.inc"
2585   }
2586 
2587   if (Err)
2588     return true;
2589 
2590   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2591 }
2592 
2593 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2594                                         const Expr *CoprocArg, bool WantCDE) {
2595   if (isConstantEvaluated())
2596     return false;
2597 
2598   // We can't check the value of a dependent argument.
2599   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2600     return false;
2601 
2602   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2603   int64_t CoprocNo = CoprocNoAP.getExtValue();
2604   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2605 
2606   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2607   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2608 
2609   if (IsCDECoproc != WantCDE)
2610     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2611            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2612 
2613   return false;
2614 }
2615 
2616 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2617                                         unsigned MaxWidth) {
2618   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2619           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2620           BuiltinID == ARM::BI__builtin_arm_strex ||
2621           BuiltinID == ARM::BI__builtin_arm_stlex ||
2622           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2623           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2624           BuiltinID == AArch64::BI__builtin_arm_strex ||
2625           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2626          "unexpected ARM builtin");
2627   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2628                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2629                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2630                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2631 
2632   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2633 
2634   // Ensure that we have the proper number of arguments.
2635   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2636     return true;
2637 
2638   // Inspect the pointer argument of the atomic builtin.  This should always be
2639   // a pointer type, whose element is an integral scalar or pointer type.
2640   // Because it is a pointer type, we don't have to worry about any implicit
2641   // casts here.
2642   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2643   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2644   if (PointerArgRes.isInvalid())
2645     return true;
2646   PointerArg = PointerArgRes.get();
2647 
2648   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2649   if (!pointerType) {
2650     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2651         << PointerArg->getType() << PointerArg->getSourceRange();
2652     return true;
2653   }
2654 
2655   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2656   // task is to insert the appropriate casts into the AST. First work out just
2657   // what the appropriate type is.
2658   QualType ValType = pointerType->getPointeeType();
2659   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2660   if (IsLdrex)
2661     AddrType.addConst();
2662 
2663   // Issue a warning if the cast is dodgy.
2664   CastKind CastNeeded = CK_NoOp;
2665   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2666     CastNeeded = CK_BitCast;
2667     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2668         << PointerArg->getType() << Context.getPointerType(AddrType)
2669         << AA_Passing << PointerArg->getSourceRange();
2670   }
2671 
2672   // Finally, do the cast and replace the argument with the corrected version.
2673   AddrType = Context.getPointerType(AddrType);
2674   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2675   if (PointerArgRes.isInvalid())
2676     return true;
2677   PointerArg = PointerArgRes.get();
2678 
2679   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2680 
2681   // In general, we allow ints, floats and pointers to be loaded and stored.
2682   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2683       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2684     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2685         << PointerArg->getType() << PointerArg->getSourceRange();
2686     return true;
2687   }
2688 
2689   // But ARM doesn't have instructions to deal with 128-bit versions.
2690   if (Context.getTypeSize(ValType) > MaxWidth) {
2691     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2692     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2693         << PointerArg->getType() << PointerArg->getSourceRange();
2694     return true;
2695   }
2696 
2697   switch (ValType.getObjCLifetime()) {
2698   case Qualifiers::OCL_None:
2699   case Qualifiers::OCL_ExplicitNone:
2700     // okay
2701     break;
2702 
2703   case Qualifiers::OCL_Weak:
2704   case Qualifiers::OCL_Strong:
2705   case Qualifiers::OCL_Autoreleasing:
2706     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2707         << ValType << PointerArg->getSourceRange();
2708     return true;
2709   }
2710 
2711   if (IsLdrex) {
2712     TheCall->setType(ValType);
2713     return false;
2714   }
2715 
2716   // Initialize the argument to be stored.
2717   ExprResult ValArg = TheCall->getArg(0);
2718   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2719       Context, ValType, /*consume*/ false);
2720   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2721   if (ValArg.isInvalid())
2722     return true;
2723   TheCall->setArg(0, ValArg.get());
2724 
2725   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2726   // but the custom checker bypasses all default analysis.
2727   TheCall->setType(Context.IntTy);
2728   return false;
2729 }
2730 
2731 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2732                                        CallExpr *TheCall) {
2733   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2734       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2735       BuiltinID == ARM::BI__builtin_arm_strex ||
2736       BuiltinID == ARM::BI__builtin_arm_stlex) {
2737     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2738   }
2739 
2740   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2741     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2742       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2743   }
2744 
2745   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2746       BuiltinID == ARM::BI__builtin_arm_wsr64)
2747     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2748 
2749   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2750       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2751       BuiltinID == ARM::BI__builtin_arm_wsr ||
2752       BuiltinID == ARM::BI__builtin_arm_wsrp)
2753     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2754 
2755   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2756     return true;
2757   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2758     return true;
2759   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2760     return true;
2761 
2762   // For intrinsics which take an immediate value as part of the instruction,
2763   // range check them here.
2764   // FIXME: VFP Intrinsics should error if VFP not present.
2765   switch (BuiltinID) {
2766   default: return false;
2767   case ARM::BI__builtin_arm_ssat:
2768     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2769   case ARM::BI__builtin_arm_usat:
2770     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2771   case ARM::BI__builtin_arm_ssat16:
2772     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2773   case ARM::BI__builtin_arm_usat16:
2774     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2775   case ARM::BI__builtin_arm_vcvtr_f:
2776   case ARM::BI__builtin_arm_vcvtr_d:
2777     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2778   case ARM::BI__builtin_arm_dmb:
2779   case ARM::BI__builtin_arm_dsb:
2780   case ARM::BI__builtin_arm_isb:
2781   case ARM::BI__builtin_arm_dbg:
2782     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2783   case ARM::BI__builtin_arm_cdp:
2784   case ARM::BI__builtin_arm_cdp2:
2785   case ARM::BI__builtin_arm_mcr:
2786   case ARM::BI__builtin_arm_mcr2:
2787   case ARM::BI__builtin_arm_mrc:
2788   case ARM::BI__builtin_arm_mrc2:
2789   case ARM::BI__builtin_arm_mcrr:
2790   case ARM::BI__builtin_arm_mcrr2:
2791   case ARM::BI__builtin_arm_mrrc:
2792   case ARM::BI__builtin_arm_mrrc2:
2793   case ARM::BI__builtin_arm_ldc:
2794   case ARM::BI__builtin_arm_ldcl:
2795   case ARM::BI__builtin_arm_ldc2:
2796   case ARM::BI__builtin_arm_ldc2l:
2797   case ARM::BI__builtin_arm_stc:
2798   case ARM::BI__builtin_arm_stcl:
2799   case ARM::BI__builtin_arm_stc2:
2800   case ARM::BI__builtin_arm_stc2l:
2801     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2802            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2803                                         /*WantCDE*/ false);
2804   }
2805 }
2806 
2807 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2808                                            unsigned BuiltinID,
2809                                            CallExpr *TheCall) {
2810   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2811       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2812       BuiltinID == AArch64::BI__builtin_arm_strex ||
2813       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2814     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2815   }
2816 
2817   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2818     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2819       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2820       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2821       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2822   }
2823 
2824   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2825       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2826     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2827 
2828   // Memory Tagging Extensions (MTE) Intrinsics
2829   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2830       BuiltinID == AArch64::BI__builtin_arm_addg ||
2831       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2832       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2833       BuiltinID == AArch64::BI__builtin_arm_stg ||
2834       BuiltinID == AArch64::BI__builtin_arm_subp) {
2835     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2836   }
2837 
2838   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2839       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2840       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2841       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2842     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2843 
2844   // Only check the valid encoding range. Any constant in this range would be
2845   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2846   // an exception for incorrect registers. This matches MSVC behavior.
2847   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2848       BuiltinID == AArch64::BI_WriteStatusReg)
2849     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2850 
2851   if (BuiltinID == AArch64::BI__getReg)
2852     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2853 
2854   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2855     return true;
2856 
2857   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2858     return true;
2859 
2860   // For intrinsics which take an immediate value as part of the instruction,
2861   // range check them here.
2862   unsigned i = 0, l = 0, u = 0;
2863   switch (BuiltinID) {
2864   default: return false;
2865   case AArch64::BI__builtin_arm_dmb:
2866   case AArch64::BI__builtin_arm_dsb:
2867   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2868   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2869   }
2870 
2871   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2872 }
2873 
2874 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2875   if (Arg->getType()->getAsPlaceholderType())
2876     return false;
2877 
2878   // The first argument needs to be a record field access.
2879   // If it is an array element access, we delay decision
2880   // to BPF backend to check whether the access is a
2881   // field access or not.
2882   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2883           isa<MemberExpr>(Arg->IgnoreParens()) ||
2884           isa<ArraySubscriptExpr>(Arg->IgnoreParens()));
2885 }
2886 
2887 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2888                             QualType VectorTy, QualType EltTy) {
2889   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2890   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2891     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2892         << Call->getSourceRange() << VectorEltTy << EltTy;
2893     return false;
2894   }
2895   return true;
2896 }
2897 
2898 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2899   QualType ArgType = Arg->getType();
2900   if (ArgType->getAsPlaceholderType())
2901     return false;
2902 
2903   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2904   // format:
2905   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2906   //   2. <type> var;
2907   //      __builtin_preserve_type_info(var, flag);
2908   if (!isa<DeclRefExpr>(Arg->IgnoreParens()) &&
2909       !isa<UnaryOperator>(Arg->IgnoreParens()))
2910     return false;
2911 
2912   // Typedef type.
2913   if (ArgType->getAs<TypedefType>())
2914     return true;
2915 
2916   // Record type or Enum type.
2917   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2918   if (const auto *RT = Ty->getAs<RecordType>()) {
2919     if (!RT->getDecl()->getDeclName().isEmpty())
2920       return true;
2921   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2922     if (!ET->getDecl()->getDeclName().isEmpty())
2923       return true;
2924   }
2925 
2926   return false;
2927 }
2928 
2929 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2930   QualType ArgType = Arg->getType();
2931   if (ArgType->getAsPlaceholderType())
2932     return false;
2933 
2934   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2935   // format:
2936   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2937   //                                 flag);
2938   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2939   if (!UO)
2940     return false;
2941 
2942   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2943   if (!CE)
2944     return false;
2945   if (CE->getCastKind() != CK_IntegralToPointer &&
2946       CE->getCastKind() != CK_NullToPointer)
2947     return false;
2948 
2949   // The integer must be from an EnumConstantDecl.
2950   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2951   if (!DR)
2952     return false;
2953 
2954   const EnumConstantDecl *Enumerator =
2955       dyn_cast<EnumConstantDecl>(DR->getDecl());
2956   if (!Enumerator)
2957     return false;
2958 
2959   // The type must be EnumType.
2960   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2961   const auto *ET = Ty->getAs<EnumType>();
2962   if (!ET)
2963     return false;
2964 
2965   // The enum value must be supported.
2966   return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
2967 }
2968 
2969 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2970                                        CallExpr *TheCall) {
2971   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2972           BuiltinID == BPF::BI__builtin_btf_type_id ||
2973           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2974           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2975          "unexpected BPF builtin");
2976 
2977   if (checkArgCount(*this, TheCall, 2))
2978     return true;
2979 
2980   // The second argument needs to be a constant int
2981   Expr *Arg = TheCall->getArg(1);
2982   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2983   diag::kind kind;
2984   if (!Value) {
2985     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2986       kind = diag::err_preserve_field_info_not_const;
2987     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2988       kind = diag::err_btf_type_id_not_const;
2989     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2990       kind = diag::err_preserve_type_info_not_const;
2991     else
2992       kind = diag::err_preserve_enum_value_not_const;
2993     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2994     return true;
2995   }
2996 
2997   // The first argument
2998   Arg = TheCall->getArg(0);
2999   bool InvalidArg = false;
3000   bool ReturnUnsignedInt = true;
3001   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
3002     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
3003       InvalidArg = true;
3004       kind = diag::err_preserve_field_info_not_field;
3005     }
3006   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
3007     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
3008       InvalidArg = true;
3009       kind = diag::err_preserve_type_info_invalid;
3010     }
3011   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
3012     if (!isValidBPFPreserveEnumValueArg(Arg)) {
3013       InvalidArg = true;
3014       kind = diag::err_preserve_enum_value_invalid;
3015     }
3016     ReturnUnsignedInt = false;
3017   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
3018     ReturnUnsignedInt = false;
3019   }
3020 
3021   if (InvalidArg) {
3022     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
3023     return true;
3024   }
3025 
3026   if (ReturnUnsignedInt)
3027     TheCall->setType(Context.UnsignedIntTy);
3028   else
3029     TheCall->setType(Context.UnsignedLongTy);
3030   return false;
3031 }
3032 
3033 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3034   struct ArgInfo {
3035     uint8_t OpNum;
3036     bool IsSigned;
3037     uint8_t BitWidth;
3038     uint8_t Align;
3039   };
3040   struct BuiltinInfo {
3041     unsigned BuiltinID;
3042     ArgInfo Infos[2];
3043   };
3044 
3045   static BuiltinInfo Infos[] = {
3046     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
3047     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
3048     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
3049     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
3050     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
3051     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
3052     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
3053     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
3054     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
3055     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
3056     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
3057 
3058     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
3059     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
3060     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
3061     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
3062     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
3063     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
3064     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
3065     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
3066     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
3067     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
3068     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
3069 
3070     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
3071     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
3072     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
3073     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
3074     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
3075     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
3076     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
3077     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
3078     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
3079     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
3080     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
3081     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
3082     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
3083     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
3084     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
3085     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
3086     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
3087     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
3088     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
3089     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
3090     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
3091     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
3092     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
3093     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
3094     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
3095     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
3096     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
3097     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
3098     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
3099     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
3100     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
3101     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
3102     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
3103     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
3104     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
3105     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
3106     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
3107     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
3108     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
3109     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
3110     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
3111     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
3112     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
3113     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
3114     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
3115     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
3116     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
3117     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
3118     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
3119     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
3120     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
3121     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
3122                                                       {{ 1, false, 6,  0 }} },
3123     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
3124     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
3125     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
3126     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
3127     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
3128     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
3129     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
3130                                                       {{ 1, false, 5,  0 }} },
3131     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
3132     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
3133     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
3134     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
3135     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
3136     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
3137                                                        { 2, false, 5,  0 }} },
3138     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
3139                                                        { 2, false, 6,  0 }} },
3140     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
3141                                                        { 3, false, 5,  0 }} },
3142     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
3143                                                        { 3, false, 6,  0 }} },
3144     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
3145     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
3146     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
3147     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
3148     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
3149     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
3150     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
3151     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
3152     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
3153     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
3154     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
3155     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
3156     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
3157     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
3158     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
3159     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
3160                                                       {{ 2, false, 4,  0 },
3161                                                        { 3, false, 5,  0 }} },
3162     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
3163                                                       {{ 2, false, 4,  0 },
3164                                                        { 3, false, 5,  0 }} },
3165     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
3166                                                       {{ 2, false, 4,  0 },
3167                                                        { 3, false, 5,  0 }} },
3168     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
3169                                                       {{ 2, false, 4,  0 },
3170                                                        { 3, false, 5,  0 }} },
3171     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
3172     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
3173     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
3174     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
3175     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
3176     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
3177     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
3178     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
3179     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
3180     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
3181     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
3182                                                        { 2, false, 5,  0 }} },
3183     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
3184                                                        { 2, false, 6,  0 }} },
3185     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
3186     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
3187     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
3188     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
3189     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
3190     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
3191     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
3192     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
3193     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
3194                                                       {{ 1, false, 4,  0 }} },
3195     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
3196     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
3197                                                       {{ 1, false, 4,  0 }} },
3198     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
3199     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
3200     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
3201     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
3202     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
3203     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
3204     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
3205     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
3206     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
3207     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
3208     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
3209     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
3210     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
3211     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
3212     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
3213     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
3214     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
3215     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
3216     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
3217     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
3218                                                       {{ 3, false, 1,  0 }} },
3219     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
3220     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
3221     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
3222     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
3223                                                       {{ 3, false, 1,  0 }} },
3224     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
3225     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
3226     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
3227     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
3228                                                       {{ 3, false, 1,  0 }} },
3229   };
3230 
3231   // Use a dynamically initialized static to sort the table exactly once on
3232   // first run.
3233   static const bool SortOnce =
3234       (llvm::sort(Infos,
3235                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
3236                    return LHS.BuiltinID < RHS.BuiltinID;
3237                  }),
3238        true);
3239   (void)SortOnce;
3240 
3241   const BuiltinInfo *F = llvm::partition_point(
3242       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
3243   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
3244     return false;
3245 
3246   bool Error = false;
3247 
3248   for (const ArgInfo &A : F->Infos) {
3249     // Ignore empty ArgInfo elements.
3250     if (A.BitWidth == 0)
3251       continue;
3252 
3253     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
3254     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
3255     if (!A.Align) {
3256       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3257     } else {
3258       unsigned M = 1 << A.Align;
3259       Min *= M;
3260       Max *= M;
3261       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3262       Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
3263     }
3264   }
3265   return Error;
3266 }
3267 
3268 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
3269                                            CallExpr *TheCall) {
3270   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3271 }
3272 
3273 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
3274                                         unsigned BuiltinID, CallExpr *TheCall) {
3275   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
3276          CheckMipsBuiltinArgument(BuiltinID, TheCall);
3277 }
3278 
3279 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
3280                                CallExpr *TheCall) {
3281 
3282   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3283       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3284     if (!TI.hasFeature("dsp"))
3285       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3286   }
3287 
3288   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3289       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3290     if (!TI.hasFeature("dspr2"))
3291       return Diag(TheCall->getBeginLoc(),
3292                   diag::err_mips_builtin_requires_dspr2);
3293   }
3294 
3295   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3296       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3297     if (!TI.hasFeature("msa"))
3298       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3299   }
3300 
3301   return false;
3302 }
3303 
3304 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3305 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3306 // ordering for DSP is unspecified. MSA is ordered by the data format used
3307 // by the underlying instruction i.e., df/m, df/n and then by size.
3308 //
3309 // FIXME: The size tests here should instead be tablegen'd along with the
3310 //        definitions from include/clang/Basic/BuiltinsMips.def.
3311 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3312 //        be too.
3313 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3314   unsigned i = 0, l = 0, u = 0, m = 0;
3315   switch (BuiltinID) {
3316   default: return false;
3317   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3318   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3319   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3320   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3321   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3322   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3323   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3324   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3325   // df/m field.
3326   // These intrinsics take an unsigned 3 bit immediate.
3327   case Mips::BI__builtin_msa_bclri_b:
3328   case Mips::BI__builtin_msa_bnegi_b:
3329   case Mips::BI__builtin_msa_bseti_b:
3330   case Mips::BI__builtin_msa_sat_s_b:
3331   case Mips::BI__builtin_msa_sat_u_b:
3332   case Mips::BI__builtin_msa_slli_b:
3333   case Mips::BI__builtin_msa_srai_b:
3334   case Mips::BI__builtin_msa_srari_b:
3335   case Mips::BI__builtin_msa_srli_b:
3336   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3337   case Mips::BI__builtin_msa_binsli_b:
3338   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3339   // These intrinsics take an unsigned 4 bit immediate.
3340   case Mips::BI__builtin_msa_bclri_h:
3341   case Mips::BI__builtin_msa_bnegi_h:
3342   case Mips::BI__builtin_msa_bseti_h:
3343   case Mips::BI__builtin_msa_sat_s_h:
3344   case Mips::BI__builtin_msa_sat_u_h:
3345   case Mips::BI__builtin_msa_slli_h:
3346   case Mips::BI__builtin_msa_srai_h:
3347   case Mips::BI__builtin_msa_srari_h:
3348   case Mips::BI__builtin_msa_srli_h:
3349   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3350   case Mips::BI__builtin_msa_binsli_h:
3351   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3352   // These intrinsics take an unsigned 5 bit immediate.
3353   // The first block of intrinsics actually have an unsigned 5 bit field,
3354   // not a df/n field.
3355   case Mips::BI__builtin_msa_cfcmsa:
3356   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3357   case Mips::BI__builtin_msa_clei_u_b:
3358   case Mips::BI__builtin_msa_clei_u_h:
3359   case Mips::BI__builtin_msa_clei_u_w:
3360   case Mips::BI__builtin_msa_clei_u_d:
3361   case Mips::BI__builtin_msa_clti_u_b:
3362   case Mips::BI__builtin_msa_clti_u_h:
3363   case Mips::BI__builtin_msa_clti_u_w:
3364   case Mips::BI__builtin_msa_clti_u_d:
3365   case Mips::BI__builtin_msa_maxi_u_b:
3366   case Mips::BI__builtin_msa_maxi_u_h:
3367   case Mips::BI__builtin_msa_maxi_u_w:
3368   case Mips::BI__builtin_msa_maxi_u_d:
3369   case Mips::BI__builtin_msa_mini_u_b:
3370   case Mips::BI__builtin_msa_mini_u_h:
3371   case Mips::BI__builtin_msa_mini_u_w:
3372   case Mips::BI__builtin_msa_mini_u_d:
3373   case Mips::BI__builtin_msa_addvi_b:
3374   case Mips::BI__builtin_msa_addvi_h:
3375   case Mips::BI__builtin_msa_addvi_w:
3376   case Mips::BI__builtin_msa_addvi_d:
3377   case Mips::BI__builtin_msa_bclri_w:
3378   case Mips::BI__builtin_msa_bnegi_w:
3379   case Mips::BI__builtin_msa_bseti_w:
3380   case Mips::BI__builtin_msa_sat_s_w:
3381   case Mips::BI__builtin_msa_sat_u_w:
3382   case Mips::BI__builtin_msa_slli_w:
3383   case Mips::BI__builtin_msa_srai_w:
3384   case Mips::BI__builtin_msa_srari_w:
3385   case Mips::BI__builtin_msa_srli_w:
3386   case Mips::BI__builtin_msa_srlri_w:
3387   case Mips::BI__builtin_msa_subvi_b:
3388   case Mips::BI__builtin_msa_subvi_h:
3389   case Mips::BI__builtin_msa_subvi_w:
3390   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3391   case Mips::BI__builtin_msa_binsli_w:
3392   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3393   // These intrinsics take an unsigned 6 bit immediate.
3394   case Mips::BI__builtin_msa_bclri_d:
3395   case Mips::BI__builtin_msa_bnegi_d:
3396   case Mips::BI__builtin_msa_bseti_d:
3397   case Mips::BI__builtin_msa_sat_s_d:
3398   case Mips::BI__builtin_msa_sat_u_d:
3399   case Mips::BI__builtin_msa_slli_d:
3400   case Mips::BI__builtin_msa_srai_d:
3401   case Mips::BI__builtin_msa_srari_d:
3402   case Mips::BI__builtin_msa_srli_d:
3403   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3404   case Mips::BI__builtin_msa_binsli_d:
3405   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3406   // These intrinsics take a signed 5 bit immediate.
3407   case Mips::BI__builtin_msa_ceqi_b:
3408   case Mips::BI__builtin_msa_ceqi_h:
3409   case Mips::BI__builtin_msa_ceqi_w:
3410   case Mips::BI__builtin_msa_ceqi_d:
3411   case Mips::BI__builtin_msa_clti_s_b:
3412   case Mips::BI__builtin_msa_clti_s_h:
3413   case Mips::BI__builtin_msa_clti_s_w:
3414   case Mips::BI__builtin_msa_clti_s_d:
3415   case Mips::BI__builtin_msa_clei_s_b:
3416   case Mips::BI__builtin_msa_clei_s_h:
3417   case Mips::BI__builtin_msa_clei_s_w:
3418   case Mips::BI__builtin_msa_clei_s_d:
3419   case Mips::BI__builtin_msa_maxi_s_b:
3420   case Mips::BI__builtin_msa_maxi_s_h:
3421   case Mips::BI__builtin_msa_maxi_s_w:
3422   case Mips::BI__builtin_msa_maxi_s_d:
3423   case Mips::BI__builtin_msa_mini_s_b:
3424   case Mips::BI__builtin_msa_mini_s_h:
3425   case Mips::BI__builtin_msa_mini_s_w:
3426   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3427   // These intrinsics take an unsigned 8 bit immediate.
3428   case Mips::BI__builtin_msa_andi_b:
3429   case Mips::BI__builtin_msa_nori_b:
3430   case Mips::BI__builtin_msa_ori_b:
3431   case Mips::BI__builtin_msa_shf_b:
3432   case Mips::BI__builtin_msa_shf_h:
3433   case Mips::BI__builtin_msa_shf_w:
3434   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3435   case Mips::BI__builtin_msa_bseli_b:
3436   case Mips::BI__builtin_msa_bmnzi_b:
3437   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3438   // df/n format
3439   // These intrinsics take an unsigned 4 bit immediate.
3440   case Mips::BI__builtin_msa_copy_s_b:
3441   case Mips::BI__builtin_msa_copy_u_b:
3442   case Mips::BI__builtin_msa_insve_b:
3443   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3444   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3445   // These intrinsics take an unsigned 3 bit immediate.
3446   case Mips::BI__builtin_msa_copy_s_h:
3447   case Mips::BI__builtin_msa_copy_u_h:
3448   case Mips::BI__builtin_msa_insve_h:
3449   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3450   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3451   // These intrinsics take an unsigned 2 bit immediate.
3452   case Mips::BI__builtin_msa_copy_s_w:
3453   case Mips::BI__builtin_msa_copy_u_w:
3454   case Mips::BI__builtin_msa_insve_w:
3455   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3456   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3457   // These intrinsics take an unsigned 1 bit immediate.
3458   case Mips::BI__builtin_msa_copy_s_d:
3459   case Mips::BI__builtin_msa_copy_u_d:
3460   case Mips::BI__builtin_msa_insve_d:
3461   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3462   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3463   // Memory offsets and immediate loads.
3464   // These intrinsics take a signed 10 bit immediate.
3465   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3466   case Mips::BI__builtin_msa_ldi_h:
3467   case Mips::BI__builtin_msa_ldi_w:
3468   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3469   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3470   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3471   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3472   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3473   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3474   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3475   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3476   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3477   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3478   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3479   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3480   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3481   }
3482 
3483   if (!m)
3484     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3485 
3486   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3487          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3488 }
3489 
3490 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3491 /// advancing the pointer over the consumed characters. The decoded type is
3492 /// returned. If the decoded type represents a constant integer with a
3493 /// constraint on its value then Mask is set to that value. The type descriptors
3494 /// used in Str are specific to PPC MMA builtins and are documented in the file
3495 /// defining the PPC builtins.
3496 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3497                                         unsigned &Mask) {
3498   bool RequireICE = false;
3499   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3500   switch (*Str++) {
3501   case 'V':
3502     return Context.getVectorType(Context.UnsignedCharTy, 16,
3503                                  VectorType::VectorKind::AltiVecVector);
3504   case 'i': {
3505     char *End;
3506     unsigned size = strtoul(Str, &End, 10);
3507     assert(End != Str && "Missing constant parameter constraint");
3508     Str = End;
3509     Mask = size;
3510     return Context.IntTy;
3511   }
3512   case 'W': {
3513     char *End;
3514     unsigned size = strtoul(Str, &End, 10);
3515     assert(End != Str && "Missing PowerPC MMA type size");
3516     Str = End;
3517     QualType Type;
3518     switch (size) {
3519   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3520     case size: Type = Context.Id##Ty; break;
3521   #include "clang/Basic/PPCTypes.def"
3522     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3523     }
3524     bool CheckVectorArgs = false;
3525     while (!CheckVectorArgs) {
3526       switch (*Str++) {
3527       case '*':
3528         Type = Context.getPointerType(Type);
3529         break;
3530       case 'C':
3531         Type = Type.withConst();
3532         break;
3533       default:
3534         CheckVectorArgs = true;
3535         --Str;
3536         break;
3537       }
3538     }
3539     return Type;
3540   }
3541   default:
3542     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3543   }
3544 }
3545 
3546 static bool isPPC_64Builtin(unsigned BuiltinID) {
3547   // These builtins only work on PPC 64bit targets.
3548   switch (BuiltinID) {
3549   case PPC::BI__builtin_divde:
3550   case PPC::BI__builtin_divdeu:
3551   case PPC::BI__builtin_bpermd:
3552   case PPC::BI__builtin_ppc_ldarx:
3553   case PPC::BI__builtin_ppc_stdcx:
3554   case PPC::BI__builtin_ppc_tdw:
3555   case PPC::BI__builtin_ppc_trapd:
3556   case PPC::BI__builtin_ppc_cmpeqb:
3557   case PPC::BI__builtin_ppc_setb:
3558   case PPC::BI__builtin_ppc_mulhd:
3559   case PPC::BI__builtin_ppc_mulhdu:
3560   case PPC::BI__builtin_ppc_maddhd:
3561   case PPC::BI__builtin_ppc_maddhdu:
3562   case PPC::BI__builtin_ppc_maddld:
3563   case PPC::BI__builtin_ppc_load8r:
3564   case PPC::BI__builtin_ppc_store8r:
3565   case PPC::BI__builtin_ppc_insert_exp:
3566   case PPC::BI__builtin_ppc_extract_sig:
3567   case PPC::BI__builtin_ppc_addex:
3568   case PPC::BI__builtin_darn:
3569   case PPC::BI__builtin_darn_raw:
3570   case PPC::BI__builtin_ppc_compare_and_swaplp:
3571   case PPC::BI__builtin_ppc_fetch_and_addlp:
3572   case PPC::BI__builtin_ppc_fetch_and_andlp:
3573   case PPC::BI__builtin_ppc_fetch_and_orlp:
3574   case PPC::BI__builtin_ppc_fetch_and_swaplp:
3575     return true;
3576   }
3577   return false;
3578 }
3579 
3580 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3581                              StringRef FeatureToCheck, unsigned DiagID,
3582                              StringRef DiagArg = "") {
3583   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3584     return false;
3585 
3586   if (DiagArg.empty())
3587     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3588   else
3589     S.Diag(TheCall->getBeginLoc(), DiagID)
3590         << DiagArg << TheCall->getSourceRange();
3591 
3592   return true;
3593 }
3594 
3595 /// Returns true if the argument consists of one contiguous run of 1s with any
3596 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3597 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3598 /// since all 1s are not contiguous.
3599 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3600   llvm::APSInt Result;
3601   // We can't check the value of a dependent argument.
3602   Expr *Arg = TheCall->getArg(ArgNum);
3603   if (Arg->isTypeDependent() || Arg->isValueDependent())
3604     return false;
3605 
3606   // Check constant-ness first.
3607   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3608     return true;
3609 
3610   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3611   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3612     return false;
3613 
3614   return Diag(TheCall->getBeginLoc(),
3615               diag::err_argument_not_contiguous_bit_field)
3616          << ArgNum << Arg->getSourceRange();
3617 }
3618 
3619 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3620                                        CallExpr *TheCall) {
3621   unsigned i = 0, l = 0, u = 0;
3622   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3623   llvm::APSInt Result;
3624 
3625   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3626     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3627            << TheCall->getSourceRange();
3628 
3629   switch (BuiltinID) {
3630   default: return false;
3631   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3632   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3633     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3634            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3635   case PPC::BI__builtin_altivec_dss:
3636     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3637   case PPC::BI__builtin_tbegin:
3638   case PPC::BI__builtin_tend:
3639     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 1) ||
3640            SemaFeatureCheck(*this, TheCall, "htm",
3641                             diag::err_ppc_builtin_requires_htm);
3642   case PPC::BI__builtin_tsr:
3643     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3644            SemaFeatureCheck(*this, TheCall, "htm",
3645                             diag::err_ppc_builtin_requires_htm);
3646   case PPC::BI__builtin_tabortwc:
3647   case PPC::BI__builtin_tabortdc:
3648     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3649            SemaFeatureCheck(*this, TheCall, "htm",
3650                             diag::err_ppc_builtin_requires_htm);
3651   case PPC::BI__builtin_tabortwci:
3652   case PPC::BI__builtin_tabortdci:
3653     return SemaFeatureCheck(*this, TheCall, "htm",
3654                             diag::err_ppc_builtin_requires_htm) ||
3655            (SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3656             SemaBuiltinConstantArgRange(TheCall, 2, 0, 31));
3657   case PPC::BI__builtin_tabort:
3658   case PPC::BI__builtin_tcheck:
3659   case PPC::BI__builtin_treclaim:
3660   case PPC::BI__builtin_trechkpt:
3661   case PPC::BI__builtin_tendall:
3662   case PPC::BI__builtin_tresume:
3663   case PPC::BI__builtin_tsuspend:
3664   case PPC::BI__builtin_get_texasr:
3665   case PPC::BI__builtin_get_texasru:
3666   case PPC::BI__builtin_get_tfhar:
3667   case PPC::BI__builtin_get_tfiar:
3668   case PPC::BI__builtin_set_texasr:
3669   case PPC::BI__builtin_set_texasru:
3670   case PPC::BI__builtin_set_tfhar:
3671   case PPC::BI__builtin_set_tfiar:
3672   case PPC::BI__builtin_ttest:
3673     return SemaFeatureCheck(*this, TheCall, "htm",
3674                             diag::err_ppc_builtin_requires_htm);
3675   // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05',
3676   // __builtin_(un)pack_longdouble are available only if long double uses IBM
3677   // extended double representation.
3678   case PPC::BI__builtin_unpack_longdouble:
3679     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1))
3680       return true;
3681     LLVM_FALLTHROUGH;
3682   case PPC::BI__builtin_pack_longdouble:
3683     if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble())
3684       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi)
3685              << "ibmlongdouble";
3686     return false;
3687   case PPC::BI__builtin_altivec_dst:
3688   case PPC::BI__builtin_altivec_dstt:
3689   case PPC::BI__builtin_altivec_dstst:
3690   case PPC::BI__builtin_altivec_dststt:
3691     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3692   case PPC::BI__builtin_vsx_xxpermdi:
3693   case PPC::BI__builtin_vsx_xxsldwi:
3694     return SemaBuiltinVSX(TheCall);
3695   case PPC::BI__builtin_divwe:
3696   case PPC::BI__builtin_divweu:
3697   case PPC::BI__builtin_divde:
3698   case PPC::BI__builtin_divdeu:
3699     return SemaFeatureCheck(*this, TheCall, "extdiv",
3700                             diag::err_ppc_builtin_only_on_arch, "7");
3701   case PPC::BI__builtin_bpermd:
3702     return SemaFeatureCheck(*this, TheCall, "bpermd",
3703                             diag::err_ppc_builtin_only_on_arch, "7");
3704   case PPC::BI__builtin_unpack_vector_int128:
3705     return SemaFeatureCheck(*this, TheCall, "vsx",
3706                             diag::err_ppc_builtin_only_on_arch, "7") ||
3707            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3708   case PPC::BI__builtin_pack_vector_int128:
3709     return SemaFeatureCheck(*this, TheCall, "vsx",
3710                             diag::err_ppc_builtin_only_on_arch, "7");
3711   case PPC::BI__builtin_altivec_vgnb:
3712      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3713   case PPC::BI__builtin_altivec_vec_replace_elt:
3714   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3715     QualType VecTy = TheCall->getArg(0)->getType();
3716     QualType EltTy = TheCall->getArg(1)->getType();
3717     unsigned Width = Context.getIntWidth(EltTy);
3718     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3719            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3720   }
3721   case PPC::BI__builtin_vsx_xxeval:
3722      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3723   case PPC::BI__builtin_altivec_vsldbi:
3724      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3725   case PPC::BI__builtin_altivec_vsrdbi:
3726      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3727   case PPC::BI__builtin_vsx_xxpermx:
3728      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3729   case PPC::BI__builtin_ppc_tw:
3730   case PPC::BI__builtin_ppc_tdw:
3731     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3732   case PPC::BI__builtin_ppc_cmpeqb:
3733   case PPC::BI__builtin_ppc_setb:
3734   case PPC::BI__builtin_ppc_maddhd:
3735   case PPC::BI__builtin_ppc_maddhdu:
3736   case PPC::BI__builtin_ppc_maddld:
3737     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3738                             diag::err_ppc_builtin_only_on_arch, "9");
3739   case PPC::BI__builtin_ppc_cmprb:
3740     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3741                             diag::err_ppc_builtin_only_on_arch, "9") ||
3742            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3743   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3744   // be a constant that represents a contiguous bit field.
3745   case PPC::BI__builtin_ppc_rlwnm:
3746     return SemaValueIsRunOfOnes(TheCall, 2);
3747   case PPC::BI__builtin_ppc_rlwimi:
3748   case PPC::BI__builtin_ppc_rldimi:
3749     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3750            SemaValueIsRunOfOnes(TheCall, 3);
3751   case PPC::BI__builtin_ppc_extract_exp:
3752   case PPC::BI__builtin_ppc_extract_sig:
3753   case PPC::BI__builtin_ppc_insert_exp:
3754     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3755                             diag::err_ppc_builtin_only_on_arch, "9");
3756   case PPC::BI__builtin_ppc_addex: {
3757     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3758                          diag::err_ppc_builtin_only_on_arch, "9") ||
3759         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
3760       return true;
3761     // Output warning for reserved values 1 to 3.
3762     int ArgValue =
3763         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
3764     if (ArgValue != 0)
3765       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
3766           << ArgValue;
3767     return false;
3768   }
3769   case PPC::BI__builtin_ppc_mtfsb0:
3770   case PPC::BI__builtin_ppc_mtfsb1:
3771     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3772   case PPC::BI__builtin_ppc_mtfsf:
3773     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3774   case PPC::BI__builtin_ppc_mtfsfi:
3775     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3776            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3777   case PPC::BI__builtin_ppc_alignx:
3778     return SemaBuiltinConstantArgPower2(TheCall, 0);
3779   case PPC::BI__builtin_ppc_rdlam:
3780     return SemaValueIsRunOfOnes(TheCall, 2);
3781   case PPC::BI__builtin_ppc_icbt:
3782   case PPC::BI__builtin_ppc_sthcx:
3783   case PPC::BI__builtin_ppc_stbcx:
3784   case PPC::BI__builtin_ppc_lharx:
3785   case PPC::BI__builtin_ppc_lbarx:
3786     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3787                             diag::err_ppc_builtin_only_on_arch, "8");
3788   case PPC::BI__builtin_vsx_ldrmb:
3789   case PPC::BI__builtin_vsx_strmb:
3790     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3791                             diag::err_ppc_builtin_only_on_arch, "8") ||
3792            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3793   case PPC::BI__builtin_altivec_vcntmbb:
3794   case PPC::BI__builtin_altivec_vcntmbh:
3795   case PPC::BI__builtin_altivec_vcntmbw:
3796   case PPC::BI__builtin_altivec_vcntmbd:
3797     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3798   case PPC::BI__builtin_darn:
3799   case PPC::BI__builtin_darn_raw:
3800   case PPC::BI__builtin_darn_32:
3801     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3802                             diag::err_ppc_builtin_only_on_arch, "9");
3803   case PPC::BI__builtin_vsx_xxgenpcvbm:
3804   case PPC::BI__builtin_vsx_xxgenpcvhm:
3805   case PPC::BI__builtin_vsx_xxgenpcvwm:
3806   case PPC::BI__builtin_vsx_xxgenpcvdm:
3807     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3808   case PPC::BI__builtin_ppc_compare_exp_uo:
3809   case PPC::BI__builtin_ppc_compare_exp_lt:
3810   case PPC::BI__builtin_ppc_compare_exp_gt:
3811   case PPC::BI__builtin_ppc_compare_exp_eq:
3812     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3813                             diag::err_ppc_builtin_only_on_arch, "9") ||
3814            SemaFeatureCheck(*this, TheCall, "vsx",
3815                             diag::err_ppc_builtin_requires_vsx);
3816   case PPC::BI__builtin_ppc_test_data_class: {
3817     // Check if the first argument of the __builtin_ppc_test_data_class call is
3818     // valid. The argument must be either a 'float' or a 'double'.
3819     QualType ArgType = TheCall->getArg(0)->getType();
3820     if (ArgType != QualType(Context.FloatTy) &&
3821         ArgType != QualType(Context.DoubleTy))
3822       return Diag(TheCall->getBeginLoc(),
3823                   diag::err_ppc_invalid_test_data_class_type);
3824     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3825                             diag::err_ppc_builtin_only_on_arch, "9") ||
3826            SemaFeatureCheck(*this, TheCall, "vsx",
3827                             diag::err_ppc_builtin_requires_vsx) ||
3828            SemaBuiltinConstantArgRange(TheCall, 1, 0, 127);
3829   }
3830   case PPC::BI__builtin_ppc_load8r:
3831   case PPC::BI__builtin_ppc_store8r:
3832     return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions",
3833                             diag::err_ppc_builtin_only_on_arch, "7");
3834 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc)                                 \
3835   case PPC::BI__builtin_##Name:                                                \
3836     return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types);
3837 #include "clang/Basic/BuiltinsPPC.def"
3838   }
3839   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3840 }
3841 
3842 // Check if the given type is a non-pointer PPC MMA type. This function is used
3843 // in Sema to prevent invalid uses of restricted PPC MMA types.
3844 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3845   if (Type->isPointerType() || Type->isArrayType())
3846     return false;
3847 
3848   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3849 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3850   if (false
3851 #include "clang/Basic/PPCTypes.def"
3852      ) {
3853     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3854     return true;
3855   }
3856   return false;
3857 }
3858 
3859 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3860                                           CallExpr *TheCall) {
3861   // position of memory order and scope arguments in the builtin
3862   unsigned OrderIndex, ScopeIndex;
3863   switch (BuiltinID) {
3864   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3865   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3866   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3867   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3868     OrderIndex = 2;
3869     ScopeIndex = 3;
3870     break;
3871   case AMDGPU::BI__builtin_amdgcn_fence:
3872     OrderIndex = 0;
3873     ScopeIndex = 1;
3874     break;
3875   default:
3876     return false;
3877   }
3878 
3879   ExprResult Arg = TheCall->getArg(OrderIndex);
3880   auto ArgExpr = Arg.get();
3881   Expr::EvalResult ArgResult;
3882 
3883   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3884     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3885            << ArgExpr->getType();
3886   auto Ord = ArgResult.Val.getInt().getZExtValue();
3887 
3888   // Check validity of memory ordering as per C11 / C++11's memody model.
3889   // Only fence needs check. Atomic dec/inc allow all memory orders.
3890   if (!llvm::isValidAtomicOrderingCABI(Ord))
3891     return Diag(ArgExpr->getBeginLoc(),
3892                 diag::warn_atomic_op_has_invalid_memory_order)
3893            << ArgExpr->getSourceRange();
3894   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3895   case llvm::AtomicOrderingCABI::relaxed:
3896   case llvm::AtomicOrderingCABI::consume:
3897     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3898       return Diag(ArgExpr->getBeginLoc(),
3899                   diag::warn_atomic_op_has_invalid_memory_order)
3900              << ArgExpr->getSourceRange();
3901     break;
3902   case llvm::AtomicOrderingCABI::acquire:
3903   case llvm::AtomicOrderingCABI::release:
3904   case llvm::AtomicOrderingCABI::acq_rel:
3905   case llvm::AtomicOrderingCABI::seq_cst:
3906     break;
3907   }
3908 
3909   Arg = TheCall->getArg(ScopeIndex);
3910   ArgExpr = Arg.get();
3911   Expr::EvalResult ArgResult1;
3912   // Check that sync scope is a constant literal
3913   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3914     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3915            << ArgExpr->getType();
3916 
3917   return false;
3918 }
3919 
3920 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3921   llvm::APSInt Result;
3922 
3923   // We can't check the value of a dependent argument.
3924   Expr *Arg = TheCall->getArg(ArgNum);
3925   if (Arg->isTypeDependent() || Arg->isValueDependent())
3926     return false;
3927 
3928   // Check constant-ness first.
3929   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3930     return true;
3931 
3932   int64_t Val = Result.getSExtValue();
3933   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3934     return false;
3935 
3936   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3937          << Arg->getSourceRange();
3938 }
3939 
3940 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3941                                          unsigned BuiltinID,
3942                                          CallExpr *TheCall) {
3943   // CodeGenFunction can also detect this, but this gives a better error
3944   // message.
3945   bool FeatureMissing = false;
3946   SmallVector<StringRef> ReqFeatures;
3947   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3948   Features.split(ReqFeatures, ',');
3949 
3950   // Check if each required feature is included
3951   for (StringRef F : ReqFeatures) {
3952     if (TI.hasFeature(F))
3953       continue;
3954 
3955     // If the feature is 64bit, alter the string so it will print better in
3956     // the diagnostic.
3957     if (F == "64bit")
3958       F = "RV64";
3959 
3960     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3961     F.consume_front("experimental-");
3962     std::string FeatureStr = F.str();
3963     FeatureStr[0] = std::toupper(FeatureStr[0]);
3964 
3965     // Error message
3966     FeatureMissing = true;
3967     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3968         << TheCall->getSourceRange() << StringRef(FeatureStr);
3969   }
3970 
3971   if (FeatureMissing)
3972     return true;
3973 
3974   switch (BuiltinID) {
3975   case RISCVVector::BI__builtin_rvv_vsetvli:
3976     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3977            CheckRISCVLMUL(TheCall, 2);
3978   case RISCVVector::BI__builtin_rvv_vsetvlimax:
3979     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3980            CheckRISCVLMUL(TheCall, 1);
3981   }
3982 
3983   return false;
3984 }
3985 
3986 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3987                                            CallExpr *TheCall) {
3988   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3989     Expr *Arg = TheCall->getArg(0);
3990     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3991       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3992         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3993                << Arg->getSourceRange();
3994   }
3995 
3996   // For intrinsics which take an immediate value as part of the instruction,
3997   // range check them here.
3998   unsigned i = 0, l = 0, u = 0;
3999   switch (BuiltinID) {
4000   default: return false;
4001   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
4002   case SystemZ::BI__builtin_s390_verimb:
4003   case SystemZ::BI__builtin_s390_verimh:
4004   case SystemZ::BI__builtin_s390_verimf:
4005   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
4006   case SystemZ::BI__builtin_s390_vfaeb:
4007   case SystemZ::BI__builtin_s390_vfaeh:
4008   case SystemZ::BI__builtin_s390_vfaef:
4009   case SystemZ::BI__builtin_s390_vfaebs:
4010   case SystemZ::BI__builtin_s390_vfaehs:
4011   case SystemZ::BI__builtin_s390_vfaefs:
4012   case SystemZ::BI__builtin_s390_vfaezb:
4013   case SystemZ::BI__builtin_s390_vfaezh:
4014   case SystemZ::BI__builtin_s390_vfaezf:
4015   case SystemZ::BI__builtin_s390_vfaezbs:
4016   case SystemZ::BI__builtin_s390_vfaezhs:
4017   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
4018   case SystemZ::BI__builtin_s390_vfisb:
4019   case SystemZ::BI__builtin_s390_vfidb:
4020     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
4021            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
4022   case SystemZ::BI__builtin_s390_vftcisb:
4023   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
4024   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
4025   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
4026   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
4027   case SystemZ::BI__builtin_s390_vstrcb:
4028   case SystemZ::BI__builtin_s390_vstrch:
4029   case SystemZ::BI__builtin_s390_vstrcf:
4030   case SystemZ::BI__builtin_s390_vstrczb:
4031   case SystemZ::BI__builtin_s390_vstrczh:
4032   case SystemZ::BI__builtin_s390_vstrczf:
4033   case SystemZ::BI__builtin_s390_vstrcbs:
4034   case SystemZ::BI__builtin_s390_vstrchs:
4035   case SystemZ::BI__builtin_s390_vstrcfs:
4036   case SystemZ::BI__builtin_s390_vstrczbs:
4037   case SystemZ::BI__builtin_s390_vstrczhs:
4038   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
4039   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
4040   case SystemZ::BI__builtin_s390_vfminsb:
4041   case SystemZ::BI__builtin_s390_vfmaxsb:
4042   case SystemZ::BI__builtin_s390_vfmindb:
4043   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
4044   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
4045   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
4046   case SystemZ::BI__builtin_s390_vclfnhs:
4047   case SystemZ::BI__builtin_s390_vclfnls:
4048   case SystemZ::BI__builtin_s390_vcfn:
4049   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
4050   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
4051   }
4052   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
4053 }
4054 
4055 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
4056 /// This checks that the target supports __builtin_cpu_supports and
4057 /// that the string argument is constant and valid.
4058 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
4059                                    CallExpr *TheCall) {
4060   Expr *Arg = TheCall->getArg(0);
4061 
4062   // Check if the argument is a string literal.
4063   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4064     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4065            << Arg->getSourceRange();
4066 
4067   // Check the contents of the string.
4068   StringRef Feature =
4069       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4070   if (!TI.validateCpuSupports(Feature))
4071     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
4072            << Arg->getSourceRange();
4073   return false;
4074 }
4075 
4076 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
4077 /// This checks that the target supports __builtin_cpu_is and
4078 /// that the string argument is constant and valid.
4079 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
4080   Expr *Arg = TheCall->getArg(0);
4081 
4082   // Check if the argument is a string literal.
4083   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4084     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4085            << Arg->getSourceRange();
4086 
4087   // Check the contents of the string.
4088   StringRef Feature =
4089       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4090   if (!TI.validateCpuIs(Feature))
4091     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
4092            << Arg->getSourceRange();
4093   return false;
4094 }
4095 
4096 // Check if the rounding mode is legal.
4097 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
4098   // Indicates if this instruction has rounding control or just SAE.
4099   bool HasRC = false;
4100 
4101   unsigned ArgNum = 0;
4102   switch (BuiltinID) {
4103   default:
4104     return false;
4105   case X86::BI__builtin_ia32_vcvttsd2si32:
4106   case X86::BI__builtin_ia32_vcvttsd2si64:
4107   case X86::BI__builtin_ia32_vcvttsd2usi32:
4108   case X86::BI__builtin_ia32_vcvttsd2usi64:
4109   case X86::BI__builtin_ia32_vcvttss2si32:
4110   case X86::BI__builtin_ia32_vcvttss2si64:
4111   case X86::BI__builtin_ia32_vcvttss2usi32:
4112   case X86::BI__builtin_ia32_vcvttss2usi64:
4113   case X86::BI__builtin_ia32_vcvttsh2si32:
4114   case X86::BI__builtin_ia32_vcvttsh2si64:
4115   case X86::BI__builtin_ia32_vcvttsh2usi32:
4116   case X86::BI__builtin_ia32_vcvttsh2usi64:
4117     ArgNum = 1;
4118     break;
4119   case X86::BI__builtin_ia32_maxpd512:
4120   case X86::BI__builtin_ia32_maxps512:
4121   case X86::BI__builtin_ia32_minpd512:
4122   case X86::BI__builtin_ia32_minps512:
4123   case X86::BI__builtin_ia32_maxph512:
4124   case X86::BI__builtin_ia32_minph512:
4125     ArgNum = 2;
4126     break;
4127   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
4128   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
4129   case X86::BI__builtin_ia32_cvtps2pd512_mask:
4130   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
4131   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
4132   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
4133   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
4134   case X86::BI__builtin_ia32_cvttps2dq512_mask:
4135   case X86::BI__builtin_ia32_cvttps2qq512_mask:
4136   case X86::BI__builtin_ia32_cvttps2udq512_mask:
4137   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
4138   case X86::BI__builtin_ia32_vcvttph2w512_mask:
4139   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
4140   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
4141   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
4142   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
4143   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
4144   case X86::BI__builtin_ia32_exp2pd_mask:
4145   case X86::BI__builtin_ia32_exp2ps_mask:
4146   case X86::BI__builtin_ia32_getexppd512_mask:
4147   case X86::BI__builtin_ia32_getexpps512_mask:
4148   case X86::BI__builtin_ia32_getexpph512_mask:
4149   case X86::BI__builtin_ia32_rcp28pd_mask:
4150   case X86::BI__builtin_ia32_rcp28ps_mask:
4151   case X86::BI__builtin_ia32_rsqrt28pd_mask:
4152   case X86::BI__builtin_ia32_rsqrt28ps_mask:
4153   case X86::BI__builtin_ia32_vcomisd:
4154   case X86::BI__builtin_ia32_vcomiss:
4155   case X86::BI__builtin_ia32_vcomish:
4156   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
4157     ArgNum = 3;
4158     break;
4159   case X86::BI__builtin_ia32_cmppd512_mask:
4160   case X86::BI__builtin_ia32_cmpps512_mask:
4161   case X86::BI__builtin_ia32_cmpsd_mask:
4162   case X86::BI__builtin_ia32_cmpss_mask:
4163   case X86::BI__builtin_ia32_cmpsh_mask:
4164   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
4165   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
4166   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
4167   case X86::BI__builtin_ia32_getexpsd128_round_mask:
4168   case X86::BI__builtin_ia32_getexpss128_round_mask:
4169   case X86::BI__builtin_ia32_getexpsh128_round_mask:
4170   case X86::BI__builtin_ia32_getmantpd512_mask:
4171   case X86::BI__builtin_ia32_getmantps512_mask:
4172   case X86::BI__builtin_ia32_getmantph512_mask:
4173   case X86::BI__builtin_ia32_maxsd_round_mask:
4174   case X86::BI__builtin_ia32_maxss_round_mask:
4175   case X86::BI__builtin_ia32_maxsh_round_mask:
4176   case X86::BI__builtin_ia32_minsd_round_mask:
4177   case X86::BI__builtin_ia32_minss_round_mask:
4178   case X86::BI__builtin_ia32_minsh_round_mask:
4179   case X86::BI__builtin_ia32_rcp28sd_round_mask:
4180   case X86::BI__builtin_ia32_rcp28ss_round_mask:
4181   case X86::BI__builtin_ia32_reducepd512_mask:
4182   case X86::BI__builtin_ia32_reduceps512_mask:
4183   case X86::BI__builtin_ia32_reduceph512_mask:
4184   case X86::BI__builtin_ia32_rndscalepd_mask:
4185   case X86::BI__builtin_ia32_rndscaleps_mask:
4186   case X86::BI__builtin_ia32_rndscaleph_mask:
4187   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
4188   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
4189     ArgNum = 4;
4190     break;
4191   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4192   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4193   case X86::BI__builtin_ia32_fixupimmps512_mask:
4194   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4195   case X86::BI__builtin_ia32_fixupimmsd_mask:
4196   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4197   case X86::BI__builtin_ia32_fixupimmss_mask:
4198   case X86::BI__builtin_ia32_fixupimmss_maskz:
4199   case X86::BI__builtin_ia32_getmantsd_round_mask:
4200   case X86::BI__builtin_ia32_getmantss_round_mask:
4201   case X86::BI__builtin_ia32_getmantsh_round_mask:
4202   case X86::BI__builtin_ia32_rangepd512_mask:
4203   case X86::BI__builtin_ia32_rangeps512_mask:
4204   case X86::BI__builtin_ia32_rangesd128_round_mask:
4205   case X86::BI__builtin_ia32_rangess128_round_mask:
4206   case X86::BI__builtin_ia32_reducesd_mask:
4207   case X86::BI__builtin_ia32_reducess_mask:
4208   case X86::BI__builtin_ia32_reducesh_mask:
4209   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4210   case X86::BI__builtin_ia32_rndscaless_round_mask:
4211   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4212     ArgNum = 5;
4213     break;
4214   case X86::BI__builtin_ia32_vcvtsd2si64:
4215   case X86::BI__builtin_ia32_vcvtsd2si32:
4216   case X86::BI__builtin_ia32_vcvtsd2usi32:
4217   case X86::BI__builtin_ia32_vcvtsd2usi64:
4218   case X86::BI__builtin_ia32_vcvtss2si32:
4219   case X86::BI__builtin_ia32_vcvtss2si64:
4220   case X86::BI__builtin_ia32_vcvtss2usi32:
4221   case X86::BI__builtin_ia32_vcvtss2usi64:
4222   case X86::BI__builtin_ia32_vcvtsh2si32:
4223   case X86::BI__builtin_ia32_vcvtsh2si64:
4224   case X86::BI__builtin_ia32_vcvtsh2usi32:
4225   case X86::BI__builtin_ia32_vcvtsh2usi64:
4226   case X86::BI__builtin_ia32_sqrtpd512:
4227   case X86::BI__builtin_ia32_sqrtps512:
4228   case X86::BI__builtin_ia32_sqrtph512:
4229     ArgNum = 1;
4230     HasRC = true;
4231     break;
4232   case X86::BI__builtin_ia32_addph512:
4233   case X86::BI__builtin_ia32_divph512:
4234   case X86::BI__builtin_ia32_mulph512:
4235   case X86::BI__builtin_ia32_subph512:
4236   case X86::BI__builtin_ia32_addpd512:
4237   case X86::BI__builtin_ia32_addps512:
4238   case X86::BI__builtin_ia32_divpd512:
4239   case X86::BI__builtin_ia32_divps512:
4240   case X86::BI__builtin_ia32_mulpd512:
4241   case X86::BI__builtin_ia32_mulps512:
4242   case X86::BI__builtin_ia32_subpd512:
4243   case X86::BI__builtin_ia32_subps512:
4244   case X86::BI__builtin_ia32_cvtsi2sd64:
4245   case X86::BI__builtin_ia32_cvtsi2ss32:
4246   case X86::BI__builtin_ia32_cvtsi2ss64:
4247   case X86::BI__builtin_ia32_cvtusi2sd64:
4248   case X86::BI__builtin_ia32_cvtusi2ss32:
4249   case X86::BI__builtin_ia32_cvtusi2ss64:
4250   case X86::BI__builtin_ia32_vcvtusi2sh:
4251   case X86::BI__builtin_ia32_vcvtusi642sh:
4252   case X86::BI__builtin_ia32_vcvtsi2sh:
4253   case X86::BI__builtin_ia32_vcvtsi642sh:
4254     ArgNum = 2;
4255     HasRC = true;
4256     break;
4257   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
4258   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
4259   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
4260   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
4261   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
4262   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
4263   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
4264   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
4265   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
4266   case X86::BI__builtin_ia32_cvtps2dq512_mask:
4267   case X86::BI__builtin_ia32_cvtps2qq512_mask:
4268   case X86::BI__builtin_ia32_cvtps2udq512_mask:
4269   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
4270   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
4271   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
4272   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
4273   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
4274   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
4275   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
4276   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
4277   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
4278   case X86::BI__builtin_ia32_vcvtph2w512_mask:
4279   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
4280   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
4281   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
4282   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
4283   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
4284   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
4285   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
4286     ArgNum = 3;
4287     HasRC = true;
4288     break;
4289   case X86::BI__builtin_ia32_addsh_round_mask:
4290   case X86::BI__builtin_ia32_addss_round_mask:
4291   case X86::BI__builtin_ia32_addsd_round_mask:
4292   case X86::BI__builtin_ia32_divsh_round_mask:
4293   case X86::BI__builtin_ia32_divss_round_mask:
4294   case X86::BI__builtin_ia32_divsd_round_mask:
4295   case X86::BI__builtin_ia32_mulsh_round_mask:
4296   case X86::BI__builtin_ia32_mulss_round_mask:
4297   case X86::BI__builtin_ia32_mulsd_round_mask:
4298   case X86::BI__builtin_ia32_subsh_round_mask:
4299   case X86::BI__builtin_ia32_subss_round_mask:
4300   case X86::BI__builtin_ia32_subsd_round_mask:
4301   case X86::BI__builtin_ia32_scalefph512_mask:
4302   case X86::BI__builtin_ia32_scalefpd512_mask:
4303   case X86::BI__builtin_ia32_scalefps512_mask:
4304   case X86::BI__builtin_ia32_scalefsd_round_mask:
4305   case X86::BI__builtin_ia32_scalefss_round_mask:
4306   case X86::BI__builtin_ia32_scalefsh_round_mask:
4307   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4308   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4309   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4310   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4311   case X86::BI__builtin_ia32_sqrtss_round_mask:
4312   case X86::BI__builtin_ia32_sqrtsh_round_mask:
4313   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4314   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4315   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4316   case X86::BI__builtin_ia32_vfmaddss3_mask:
4317   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4318   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4319   case X86::BI__builtin_ia32_vfmaddsh3_mask:
4320   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4321   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4322   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4323   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4324   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4325   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4326   case X86::BI__builtin_ia32_vfmaddps512_mask:
4327   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4328   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4329   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4330   case X86::BI__builtin_ia32_vfmaddph512_mask:
4331   case X86::BI__builtin_ia32_vfmaddph512_maskz:
4332   case X86::BI__builtin_ia32_vfmaddph512_mask3:
4333   case X86::BI__builtin_ia32_vfmsubph512_mask3:
4334   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4335   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4336   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4337   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4338   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4339   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4340   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4341   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4342   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4343   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4344   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4345   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4346   case X86::BI__builtin_ia32_vfmaddcsh_mask:
4347   case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
4348   case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
4349   case X86::BI__builtin_ia32_vfmaddcph512_mask:
4350   case X86::BI__builtin_ia32_vfmaddcph512_maskz:
4351   case X86::BI__builtin_ia32_vfmaddcph512_mask3:
4352   case X86::BI__builtin_ia32_vfcmaddcsh_mask:
4353   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
4354   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
4355   case X86::BI__builtin_ia32_vfcmaddcph512_mask:
4356   case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
4357   case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
4358   case X86::BI__builtin_ia32_vfmulcsh_mask:
4359   case X86::BI__builtin_ia32_vfmulcph512_mask:
4360   case X86::BI__builtin_ia32_vfcmulcsh_mask:
4361   case X86::BI__builtin_ia32_vfcmulcph512_mask:
4362     ArgNum = 4;
4363     HasRC = true;
4364     break;
4365   }
4366 
4367   llvm::APSInt Result;
4368 
4369   // We can't check the value of a dependent argument.
4370   Expr *Arg = TheCall->getArg(ArgNum);
4371   if (Arg->isTypeDependent() || Arg->isValueDependent())
4372     return false;
4373 
4374   // Check constant-ness first.
4375   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4376     return true;
4377 
4378   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4379   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4380   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4381   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4382   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4383       Result == 8/*ROUND_NO_EXC*/ ||
4384       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4385       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4386     return false;
4387 
4388   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4389          << Arg->getSourceRange();
4390 }
4391 
4392 // Check if the gather/scatter scale is legal.
4393 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4394                                              CallExpr *TheCall) {
4395   unsigned ArgNum = 0;
4396   switch (BuiltinID) {
4397   default:
4398     return false;
4399   case X86::BI__builtin_ia32_gatherpfdpd:
4400   case X86::BI__builtin_ia32_gatherpfdps:
4401   case X86::BI__builtin_ia32_gatherpfqpd:
4402   case X86::BI__builtin_ia32_gatherpfqps:
4403   case X86::BI__builtin_ia32_scatterpfdpd:
4404   case X86::BI__builtin_ia32_scatterpfdps:
4405   case X86::BI__builtin_ia32_scatterpfqpd:
4406   case X86::BI__builtin_ia32_scatterpfqps:
4407     ArgNum = 3;
4408     break;
4409   case X86::BI__builtin_ia32_gatherd_pd:
4410   case X86::BI__builtin_ia32_gatherd_pd256:
4411   case X86::BI__builtin_ia32_gatherq_pd:
4412   case X86::BI__builtin_ia32_gatherq_pd256:
4413   case X86::BI__builtin_ia32_gatherd_ps:
4414   case X86::BI__builtin_ia32_gatherd_ps256:
4415   case X86::BI__builtin_ia32_gatherq_ps:
4416   case X86::BI__builtin_ia32_gatherq_ps256:
4417   case X86::BI__builtin_ia32_gatherd_q:
4418   case X86::BI__builtin_ia32_gatherd_q256:
4419   case X86::BI__builtin_ia32_gatherq_q:
4420   case X86::BI__builtin_ia32_gatherq_q256:
4421   case X86::BI__builtin_ia32_gatherd_d:
4422   case X86::BI__builtin_ia32_gatherd_d256:
4423   case X86::BI__builtin_ia32_gatherq_d:
4424   case X86::BI__builtin_ia32_gatherq_d256:
4425   case X86::BI__builtin_ia32_gather3div2df:
4426   case X86::BI__builtin_ia32_gather3div2di:
4427   case X86::BI__builtin_ia32_gather3div4df:
4428   case X86::BI__builtin_ia32_gather3div4di:
4429   case X86::BI__builtin_ia32_gather3div4sf:
4430   case X86::BI__builtin_ia32_gather3div4si:
4431   case X86::BI__builtin_ia32_gather3div8sf:
4432   case X86::BI__builtin_ia32_gather3div8si:
4433   case X86::BI__builtin_ia32_gather3siv2df:
4434   case X86::BI__builtin_ia32_gather3siv2di:
4435   case X86::BI__builtin_ia32_gather3siv4df:
4436   case X86::BI__builtin_ia32_gather3siv4di:
4437   case X86::BI__builtin_ia32_gather3siv4sf:
4438   case X86::BI__builtin_ia32_gather3siv4si:
4439   case X86::BI__builtin_ia32_gather3siv8sf:
4440   case X86::BI__builtin_ia32_gather3siv8si:
4441   case X86::BI__builtin_ia32_gathersiv8df:
4442   case X86::BI__builtin_ia32_gathersiv16sf:
4443   case X86::BI__builtin_ia32_gatherdiv8df:
4444   case X86::BI__builtin_ia32_gatherdiv16sf:
4445   case X86::BI__builtin_ia32_gathersiv8di:
4446   case X86::BI__builtin_ia32_gathersiv16si:
4447   case X86::BI__builtin_ia32_gatherdiv8di:
4448   case X86::BI__builtin_ia32_gatherdiv16si:
4449   case X86::BI__builtin_ia32_scatterdiv2df:
4450   case X86::BI__builtin_ia32_scatterdiv2di:
4451   case X86::BI__builtin_ia32_scatterdiv4df:
4452   case X86::BI__builtin_ia32_scatterdiv4di:
4453   case X86::BI__builtin_ia32_scatterdiv4sf:
4454   case X86::BI__builtin_ia32_scatterdiv4si:
4455   case X86::BI__builtin_ia32_scatterdiv8sf:
4456   case X86::BI__builtin_ia32_scatterdiv8si:
4457   case X86::BI__builtin_ia32_scattersiv2df:
4458   case X86::BI__builtin_ia32_scattersiv2di:
4459   case X86::BI__builtin_ia32_scattersiv4df:
4460   case X86::BI__builtin_ia32_scattersiv4di:
4461   case X86::BI__builtin_ia32_scattersiv4sf:
4462   case X86::BI__builtin_ia32_scattersiv4si:
4463   case X86::BI__builtin_ia32_scattersiv8sf:
4464   case X86::BI__builtin_ia32_scattersiv8si:
4465   case X86::BI__builtin_ia32_scattersiv8df:
4466   case X86::BI__builtin_ia32_scattersiv16sf:
4467   case X86::BI__builtin_ia32_scatterdiv8df:
4468   case X86::BI__builtin_ia32_scatterdiv16sf:
4469   case X86::BI__builtin_ia32_scattersiv8di:
4470   case X86::BI__builtin_ia32_scattersiv16si:
4471   case X86::BI__builtin_ia32_scatterdiv8di:
4472   case X86::BI__builtin_ia32_scatterdiv16si:
4473     ArgNum = 4;
4474     break;
4475   }
4476 
4477   llvm::APSInt Result;
4478 
4479   // We can't check the value of a dependent argument.
4480   Expr *Arg = TheCall->getArg(ArgNum);
4481   if (Arg->isTypeDependent() || Arg->isValueDependent())
4482     return false;
4483 
4484   // Check constant-ness first.
4485   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4486     return true;
4487 
4488   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4489     return false;
4490 
4491   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4492          << Arg->getSourceRange();
4493 }
4494 
4495 enum { TileRegLow = 0, TileRegHigh = 7 };
4496 
4497 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4498                                              ArrayRef<int> ArgNums) {
4499   for (int ArgNum : ArgNums) {
4500     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4501       return true;
4502   }
4503   return false;
4504 }
4505 
4506 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4507                                         ArrayRef<int> ArgNums) {
4508   // Because the max number of tile register is TileRegHigh + 1, so here we use
4509   // each bit to represent the usage of them in bitset.
4510   std::bitset<TileRegHigh + 1> ArgValues;
4511   for (int ArgNum : ArgNums) {
4512     Expr *Arg = TheCall->getArg(ArgNum);
4513     if (Arg->isTypeDependent() || Arg->isValueDependent())
4514       continue;
4515 
4516     llvm::APSInt Result;
4517     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4518       return true;
4519     int ArgExtValue = Result.getExtValue();
4520     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4521            "Incorrect tile register num.");
4522     if (ArgValues.test(ArgExtValue))
4523       return Diag(TheCall->getBeginLoc(),
4524                   diag::err_x86_builtin_tile_arg_duplicate)
4525              << TheCall->getArg(ArgNum)->getSourceRange();
4526     ArgValues.set(ArgExtValue);
4527   }
4528   return false;
4529 }
4530 
4531 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4532                                                 ArrayRef<int> ArgNums) {
4533   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4534          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4535 }
4536 
4537 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4538   switch (BuiltinID) {
4539   default:
4540     return false;
4541   case X86::BI__builtin_ia32_tileloadd64:
4542   case X86::BI__builtin_ia32_tileloaddt164:
4543   case X86::BI__builtin_ia32_tilestored64:
4544   case X86::BI__builtin_ia32_tilezero:
4545     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4546   case X86::BI__builtin_ia32_tdpbssd:
4547   case X86::BI__builtin_ia32_tdpbsud:
4548   case X86::BI__builtin_ia32_tdpbusd:
4549   case X86::BI__builtin_ia32_tdpbuud:
4550   case X86::BI__builtin_ia32_tdpbf16ps:
4551     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4552   }
4553 }
4554 static bool isX86_32Builtin(unsigned BuiltinID) {
4555   // These builtins only work on x86-32 targets.
4556   switch (BuiltinID) {
4557   case X86::BI__builtin_ia32_readeflags_u32:
4558   case X86::BI__builtin_ia32_writeeflags_u32:
4559     return true;
4560   }
4561 
4562   return false;
4563 }
4564 
4565 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4566                                        CallExpr *TheCall) {
4567   if (BuiltinID == X86::BI__builtin_cpu_supports)
4568     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4569 
4570   if (BuiltinID == X86::BI__builtin_cpu_is)
4571     return SemaBuiltinCpuIs(*this, TI, TheCall);
4572 
4573   // Check for 32-bit only builtins on a 64-bit target.
4574   const llvm::Triple &TT = TI.getTriple();
4575   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4576     return Diag(TheCall->getCallee()->getBeginLoc(),
4577                 diag::err_32_bit_builtin_64_bit_tgt);
4578 
4579   // If the intrinsic has rounding or SAE make sure its valid.
4580   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4581     return true;
4582 
4583   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4584   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4585     return true;
4586 
4587   // If the intrinsic has a tile arguments, make sure they are valid.
4588   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4589     return true;
4590 
4591   // For intrinsics which take an immediate value as part of the instruction,
4592   // range check them here.
4593   int i = 0, l = 0, u = 0;
4594   switch (BuiltinID) {
4595   default:
4596     return false;
4597   case X86::BI__builtin_ia32_vec_ext_v2si:
4598   case X86::BI__builtin_ia32_vec_ext_v2di:
4599   case X86::BI__builtin_ia32_vextractf128_pd256:
4600   case X86::BI__builtin_ia32_vextractf128_ps256:
4601   case X86::BI__builtin_ia32_vextractf128_si256:
4602   case X86::BI__builtin_ia32_extract128i256:
4603   case X86::BI__builtin_ia32_extractf64x4_mask:
4604   case X86::BI__builtin_ia32_extracti64x4_mask:
4605   case X86::BI__builtin_ia32_extractf32x8_mask:
4606   case X86::BI__builtin_ia32_extracti32x8_mask:
4607   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4608   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4609   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4610   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4611     i = 1; l = 0; u = 1;
4612     break;
4613   case X86::BI__builtin_ia32_vec_set_v2di:
4614   case X86::BI__builtin_ia32_vinsertf128_pd256:
4615   case X86::BI__builtin_ia32_vinsertf128_ps256:
4616   case X86::BI__builtin_ia32_vinsertf128_si256:
4617   case X86::BI__builtin_ia32_insert128i256:
4618   case X86::BI__builtin_ia32_insertf32x8:
4619   case X86::BI__builtin_ia32_inserti32x8:
4620   case X86::BI__builtin_ia32_insertf64x4:
4621   case X86::BI__builtin_ia32_inserti64x4:
4622   case X86::BI__builtin_ia32_insertf64x2_256:
4623   case X86::BI__builtin_ia32_inserti64x2_256:
4624   case X86::BI__builtin_ia32_insertf32x4_256:
4625   case X86::BI__builtin_ia32_inserti32x4_256:
4626     i = 2; l = 0; u = 1;
4627     break;
4628   case X86::BI__builtin_ia32_vpermilpd:
4629   case X86::BI__builtin_ia32_vec_ext_v4hi:
4630   case X86::BI__builtin_ia32_vec_ext_v4si:
4631   case X86::BI__builtin_ia32_vec_ext_v4sf:
4632   case X86::BI__builtin_ia32_vec_ext_v4di:
4633   case X86::BI__builtin_ia32_extractf32x4_mask:
4634   case X86::BI__builtin_ia32_extracti32x4_mask:
4635   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4636   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4637     i = 1; l = 0; u = 3;
4638     break;
4639   case X86::BI_mm_prefetch:
4640   case X86::BI__builtin_ia32_vec_ext_v8hi:
4641   case X86::BI__builtin_ia32_vec_ext_v8si:
4642     i = 1; l = 0; u = 7;
4643     break;
4644   case X86::BI__builtin_ia32_sha1rnds4:
4645   case X86::BI__builtin_ia32_blendpd:
4646   case X86::BI__builtin_ia32_shufpd:
4647   case X86::BI__builtin_ia32_vec_set_v4hi:
4648   case X86::BI__builtin_ia32_vec_set_v4si:
4649   case X86::BI__builtin_ia32_vec_set_v4di:
4650   case X86::BI__builtin_ia32_shuf_f32x4_256:
4651   case X86::BI__builtin_ia32_shuf_f64x2_256:
4652   case X86::BI__builtin_ia32_shuf_i32x4_256:
4653   case X86::BI__builtin_ia32_shuf_i64x2_256:
4654   case X86::BI__builtin_ia32_insertf64x2_512:
4655   case X86::BI__builtin_ia32_inserti64x2_512:
4656   case X86::BI__builtin_ia32_insertf32x4:
4657   case X86::BI__builtin_ia32_inserti32x4:
4658     i = 2; l = 0; u = 3;
4659     break;
4660   case X86::BI__builtin_ia32_vpermil2pd:
4661   case X86::BI__builtin_ia32_vpermil2pd256:
4662   case X86::BI__builtin_ia32_vpermil2ps:
4663   case X86::BI__builtin_ia32_vpermil2ps256:
4664     i = 3; l = 0; u = 3;
4665     break;
4666   case X86::BI__builtin_ia32_cmpb128_mask:
4667   case X86::BI__builtin_ia32_cmpw128_mask:
4668   case X86::BI__builtin_ia32_cmpd128_mask:
4669   case X86::BI__builtin_ia32_cmpq128_mask:
4670   case X86::BI__builtin_ia32_cmpb256_mask:
4671   case X86::BI__builtin_ia32_cmpw256_mask:
4672   case X86::BI__builtin_ia32_cmpd256_mask:
4673   case X86::BI__builtin_ia32_cmpq256_mask:
4674   case X86::BI__builtin_ia32_cmpb512_mask:
4675   case X86::BI__builtin_ia32_cmpw512_mask:
4676   case X86::BI__builtin_ia32_cmpd512_mask:
4677   case X86::BI__builtin_ia32_cmpq512_mask:
4678   case X86::BI__builtin_ia32_ucmpb128_mask:
4679   case X86::BI__builtin_ia32_ucmpw128_mask:
4680   case X86::BI__builtin_ia32_ucmpd128_mask:
4681   case X86::BI__builtin_ia32_ucmpq128_mask:
4682   case X86::BI__builtin_ia32_ucmpb256_mask:
4683   case X86::BI__builtin_ia32_ucmpw256_mask:
4684   case X86::BI__builtin_ia32_ucmpd256_mask:
4685   case X86::BI__builtin_ia32_ucmpq256_mask:
4686   case X86::BI__builtin_ia32_ucmpb512_mask:
4687   case X86::BI__builtin_ia32_ucmpw512_mask:
4688   case X86::BI__builtin_ia32_ucmpd512_mask:
4689   case X86::BI__builtin_ia32_ucmpq512_mask:
4690   case X86::BI__builtin_ia32_vpcomub:
4691   case X86::BI__builtin_ia32_vpcomuw:
4692   case X86::BI__builtin_ia32_vpcomud:
4693   case X86::BI__builtin_ia32_vpcomuq:
4694   case X86::BI__builtin_ia32_vpcomb:
4695   case X86::BI__builtin_ia32_vpcomw:
4696   case X86::BI__builtin_ia32_vpcomd:
4697   case X86::BI__builtin_ia32_vpcomq:
4698   case X86::BI__builtin_ia32_vec_set_v8hi:
4699   case X86::BI__builtin_ia32_vec_set_v8si:
4700     i = 2; l = 0; u = 7;
4701     break;
4702   case X86::BI__builtin_ia32_vpermilpd256:
4703   case X86::BI__builtin_ia32_roundps:
4704   case X86::BI__builtin_ia32_roundpd:
4705   case X86::BI__builtin_ia32_roundps256:
4706   case X86::BI__builtin_ia32_roundpd256:
4707   case X86::BI__builtin_ia32_getmantpd128_mask:
4708   case X86::BI__builtin_ia32_getmantpd256_mask:
4709   case X86::BI__builtin_ia32_getmantps128_mask:
4710   case X86::BI__builtin_ia32_getmantps256_mask:
4711   case X86::BI__builtin_ia32_getmantpd512_mask:
4712   case X86::BI__builtin_ia32_getmantps512_mask:
4713   case X86::BI__builtin_ia32_getmantph128_mask:
4714   case X86::BI__builtin_ia32_getmantph256_mask:
4715   case X86::BI__builtin_ia32_getmantph512_mask:
4716   case X86::BI__builtin_ia32_vec_ext_v16qi:
4717   case X86::BI__builtin_ia32_vec_ext_v16hi:
4718     i = 1; l = 0; u = 15;
4719     break;
4720   case X86::BI__builtin_ia32_pblendd128:
4721   case X86::BI__builtin_ia32_blendps:
4722   case X86::BI__builtin_ia32_blendpd256:
4723   case X86::BI__builtin_ia32_shufpd256:
4724   case X86::BI__builtin_ia32_roundss:
4725   case X86::BI__builtin_ia32_roundsd:
4726   case X86::BI__builtin_ia32_rangepd128_mask:
4727   case X86::BI__builtin_ia32_rangepd256_mask:
4728   case X86::BI__builtin_ia32_rangepd512_mask:
4729   case X86::BI__builtin_ia32_rangeps128_mask:
4730   case X86::BI__builtin_ia32_rangeps256_mask:
4731   case X86::BI__builtin_ia32_rangeps512_mask:
4732   case X86::BI__builtin_ia32_getmantsd_round_mask:
4733   case X86::BI__builtin_ia32_getmantss_round_mask:
4734   case X86::BI__builtin_ia32_getmantsh_round_mask:
4735   case X86::BI__builtin_ia32_vec_set_v16qi:
4736   case X86::BI__builtin_ia32_vec_set_v16hi:
4737     i = 2; l = 0; u = 15;
4738     break;
4739   case X86::BI__builtin_ia32_vec_ext_v32qi:
4740     i = 1; l = 0; u = 31;
4741     break;
4742   case X86::BI__builtin_ia32_cmpps:
4743   case X86::BI__builtin_ia32_cmpss:
4744   case X86::BI__builtin_ia32_cmppd:
4745   case X86::BI__builtin_ia32_cmpsd:
4746   case X86::BI__builtin_ia32_cmpps256:
4747   case X86::BI__builtin_ia32_cmppd256:
4748   case X86::BI__builtin_ia32_cmpps128_mask:
4749   case X86::BI__builtin_ia32_cmppd128_mask:
4750   case X86::BI__builtin_ia32_cmpps256_mask:
4751   case X86::BI__builtin_ia32_cmppd256_mask:
4752   case X86::BI__builtin_ia32_cmpps512_mask:
4753   case X86::BI__builtin_ia32_cmppd512_mask:
4754   case X86::BI__builtin_ia32_cmpsd_mask:
4755   case X86::BI__builtin_ia32_cmpss_mask:
4756   case X86::BI__builtin_ia32_vec_set_v32qi:
4757     i = 2; l = 0; u = 31;
4758     break;
4759   case X86::BI__builtin_ia32_permdf256:
4760   case X86::BI__builtin_ia32_permdi256:
4761   case X86::BI__builtin_ia32_permdf512:
4762   case X86::BI__builtin_ia32_permdi512:
4763   case X86::BI__builtin_ia32_vpermilps:
4764   case X86::BI__builtin_ia32_vpermilps256:
4765   case X86::BI__builtin_ia32_vpermilpd512:
4766   case X86::BI__builtin_ia32_vpermilps512:
4767   case X86::BI__builtin_ia32_pshufd:
4768   case X86::BI__builtin_ia32_pshufd256:
4769   case X86::BI__builtin_ia32_pshufd512:
4770   case X86::BI__builtin_ia32_pshufhw:
4771   case X86::BI__builtin_ia32_pshufhw256:
4772   case X86::BI__builtin_ia32_pshufhw512:
4773   case X86::BI__builtin_ia32_pshuflw:
4774   case X86::BI__builtin_ia32_pshuflw256:
4775   case X86::BI__builtin_ia32_pshuflw512:
4776   case X86::BI__builtin_ia32_vcvtps2ph:
4777   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4778   case X86::BI__builtin_ia32_vcvtps2ph256:
4779   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4780   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4781   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4782   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4783   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4784   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4785   case X86::BI__builtin_ia32_rndscaleps_mask:
4786   case X86::BI__builtin_ia32_rndscalepd_mask:
4787   case X86::BI__builtin_ia32_rndscaleph_mask:
4788   case X86::BI__builtin_ia32_reducepd128_mask:
4789   case X86::BI__builtin_ia32_reducepd256_mask:
4790   case X86::BI__builtin_ia32_reducepd512_mask:
4791   case X86::BI__builtin_ia32_reduceps128_mask:
4792   case X86::BI__builtin_ia32_reduceps256_mask:
4793   case X86::BI__builtin_ia32_reduceps512_mask:
4794   case X86::BI__builtin_ia32_reduceph128_mask:
4795   case X86::BI__builtin_ia32_reduceph256_mask:
4796   case X86::BI__builtin_ia32_reduceph512_mask:
4797   case X86::BI__builtin_ia32_prold512:
4798   case X86::BI__builtin_ia32_prolq512:
4799   case X86::BI__builtin_ia32_prold128:
4800   case X86::BI__builtin_ia32_prold256:
4801   case X86::BI__builtin_ia32_prolq128:
4802   case X86::BI__builtin_ia32_prolq256:
4803   case X86::BI__builtin_ia32_prord512:
4804   case X86::BI__builtin_ia32_prorq512:
4805   case X86::BI__builtin_ia32_prord128:
4806   case X86::BI__builtin_ia32_prord256:
4807   case X86::BI__builtin_ia32_prorq128:
4808   case X86::BI__builtin_ia32_prorq256:
4809   case X86::BI__builtin_ia32_fpclasspd128_mask:
4810   case X86::BI__builtin_ia32_fpclasspd256_mask:
4811   case X86::BI__builtin_ia32_fpclassps128_mask:
4812   case X86::BI__builtin_ia32_fpclassps256_mask:
4813   case X86::BI__builtin_ia32_fpclassps512_mask:
4814   case X86::BI__builtin_ia32_fpclasspd512_mask:
4815   case X86::BI__builtin_ia32_fpclassph128_mask:
4816   case X86::BI__builtin_ia32_fpclassph256_mask:
4817   case X86::BI__builtin_ia32_fpclassph512_mask:
4818   case X86::BI__builtin_ia32_fpclasssd_mask:
4819   case X86::BI__builtin_ia32_fpclassss_mask:
4820   case X86::BI__builtin_ia32_fpclasssh_mask:
4821   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4822   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4823   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4824   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4825   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4826   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4827   case X86::BI__builtin_ia32_kshiftliqi:
4828   case X86::BI__builtin_ia32_kshiftlihi:
4829   case X86::BI__builtin_ia32_kshiftlisi:
4830   case X86::BI__builtin_ia32_kshiftlidi:
4831   case X86::BI__builtin_ia32_kshiftriqi:
4832   case X86::BI__builtin_ia32_kshiftrihi:
4833   case X86::BI__builtin_ia32_kshiftrisi:
4834   case X86::BI__builtin_ia32_kshiftridi:
4835     i = 1; l = 0; u = 255;
4836     break;
4837   case X86::BI__builtin_ia32_vperm2f128_pd256:
4838   case X86::BI__builtin_ia32_vperm2f128_ps256:
4839   case X86::BI__builtin_ia32_vperm2f128_si256:
4840   case X86::BI__builtin_ia32_permti256:
4841   case X86::BI__builtin_ia32_pblendw128:
4842   case X86::BI__builtin_ia32_pblendw256:
4843   case X86::BI__builtin_ia32_blendps256:
4844   case X86::BI__builtin_ia32_pblendd256:
4845   case X86::BI__builtin_ia32_palignr128:
4846   case X86::BI__builtin_ia32_palignr256:
4847   case X86::BI__builtin_ia32_palignr512:
4848   case X86::BI__builtin_ia32_alignq512:
4849   case X86::BI__builtin_ia32_alignd512:
4850   case X86::BI__builtin_ia32_alignd128:
4851   case X86::BI__builtin_ia32_alignd256:
4852   case X86::BI__builtin_ia32_alignq128:
4853   case X86::BI__builtin_ia32_alignq256:
4854   case X86::BI__builtin_ia32_vcomisd:
4855   case X86::BI__builtin_ia32_vcomiss:
4856   case X86::BI__builtin_ia32_shuf_f32x4:
4857   case X86::BI__builtin_ia32_shuf_f64x2:
4858   case X86::BI__builtin_ia32_shuf_i32x4:
4859   case X86::BI__builtin_ia32_shuf_i64x2:
4860   case X86::BI__builtin_ia32_shufpd512:
4861   case X86::BI__builtin_ia32_shufps:
4862   case X86::BI__builtin_ia32_shufps256:
4863   case X86::BI__builtin_ia32_shufps512:
4864   case X86::BI__builtin_ia32_dbpsadbw128:
4865   case X86::BI__builtin_ia32_dbpsadbw256:
4866   case X86::BI__builtin_ia32_dbpsadbw512:
4867   case X86::BI__builtin_ia32_vpshldd128:
4868   case X86::BI__builtin_ia32_vpshldd256:
4869   case X86::BI__builtin_ia32_vpshldd512:
4870   case X86::BI__builtin_ia32_vpshldq128:
4871   case X86::BI__builtin_ia32_vpshldq256:
4872   case X86::BI__builtin_ia32_vpshldq512:
4873   case X86::BI__builtin_ia32_vpshldw128:
4874   case X86::BI__builtin_ia32_vpshldw256:
4875   case X86::BI__builtin_ia32_vpshldw512:
4876   case X86::BI__builtin_ia32_vpshrdd128:
4877   case X86::BI__builtin_ia32_vpshrdd256:
4878   case X86::BI__builtin_ia32_vpshrdd512:
4879   case X86::BI__builtin_ia32_vpshrdq128:
4880   case X86::BI__builtin_ia32_vpshrdq256:
4881   case X86::BI__builtin_ia32_vpshrdq512:
4882   case X86::BI__builtin_ia32_vpshrdw128:
4883   case X86::BI__builtin_ia32_vpshrdw256:
4884   case X86::BI__builtin_ia32_vpshrdw512:
4885     i = 2; l = 0; u = 255;
4886     break;
4887   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4888   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4889   case X86::BI__builtin_ia32_fixupimmps512_mask:
4890   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4891   case X86::BI__builtin_ia32_fixupimmsd_mask:
4892   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4893   case X86::BI__builtin_ia32_fixupimmss_mask:
4894   case X86::BI__builtin_ia32_fixupimmss_maskz:
4895   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4896   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4897   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4898   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4899   case X86::BI__builtin_ia32_fixupimmps128_mask:
4900   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4901   case X86::BI__builtin_ia32_fixupimmps256_mask:
4902   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4903   case X86::BI__builtin_ia32_pternlogd512_mask:
4904   case X86::BI__builtin_ia32_pternlogd512_maskz:
4905   case X86::BI__builtin_ia32_pternlogq512_mask:
4906   case X86::BI__builtin_ia32_pternlogq512_maskz:
4907   case X86::BI__builtin_ia32_pternlogd128_mask:
4908   case X86::BI__builtin_ia32_pternlogd128_maskz:
4909   case X86::BI__builtin_ia32_pternlogd256_mask:
4910   case X86::BI__builtin_ia32_pternlogd256_maskz:
4911   case X86::BI__builtin_ia32_pternlogq128_mask:
4912   case X86::BI__builtin_ia32_pternlogq128_maskz:
4913   case X86::BI__builtin_ia32_pternlogq256_mask:
4914   case X86::BI__builtin_ia32_pternlogq256_maskz:
4915     i = 3; l = 0; u = 255;
4916     break;
4917   case X86::BI__builtin_ia32_gatherpfdpd:
4918   case X86::BI__builtin_ia32_gatherpfdps:
4919   case X86::BI__builtin_ia32_gatherpfqpd:
4920   case X86::BI__builtin_ia32_gatherpfqps:
4921   case X86::BI__builtin_ia32_scatterpfdpd:
4922   case X86::BI__builtin_ia32_scatterpfdps:
4923   case X86::BI__builtin_ia32_scatterpfqpd:
4924   case X86::BI__builtin_ia32_scatterpfqps:
4925     i = 4; l = 2; u = 3;
4926     break;
4927   case X86::BI__builtin_ia32_reducesd_mask:
4928   case X86::BI__builtin_ia32_reducess_mask:
4929   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4930   case X86::BI__builtin_ia32_rndscaless_round_mask:
4931   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4932   case X86::BI__builtin_ia32_reducesh_mask:
4933     i = 4; l = 0; u = 255;
4934     break;
4935   }
4936 
4937   // Note that we don't force a hard error on the range check here, allowing
4938   // template-generated or macro-generated dead code to potentially have out-of-
4939   // range values. These need to code generate, but don't need to necessarily
4940   // make any sense. We use a warning that defaults to an error.
4941   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4942 }
4943 
4944 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4945 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4946 /// Returns true when the format fits the function and the FormatStringInfo has
4947 /// been populated.
4948 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4949                                FormatStringInfo *FSI) {
4950   FSI->HasVAListArg = Format->getFirstArg() == 0;
4951   FSI->FormatIdx = Format->getFormatIdx() - 1;
4952   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4953 
4954   // The way the format attribute works in GCC, the implicit this argument
4955   // of member functions is counted. However, it doesn't appear in our own
4956   // lists, so decrement format_idx in that case.
4957   if (IsCXXMember) {
4958     if(FSI->FormatIdx == 0)
4959       return false;
4960     --FSI->FormatIdx;
4961     if (FSI->FirstDataArg != 0)
4962       --FSI->FirstDataArg;
4963   }
4964   return true;
4965 }
4966 
4967 /// Checks if a the given expression evaluates to null.
4968 ///
4969 /// Returns true if the value evaluates to null.
4970 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4971   // If the expression has non-null type, it doesn't evaluate to null.
4972   if (auto nullability
4973         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4974     if (*nullability == NullabilityKind::NonNull)
4975       return false;
4976   }
4977 
4978   // As a special case, transparent unions initialized with zero are
4979   // considered null for the purposes of the nonnull attribute.
4980   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4981     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4982       if (const CompoundLiteralExpr *CLE =
4983           dyn_cast<CompoundLiteralExpr>(Expr))
4984         if (const InitListExpr *ILE =
4985             dyn_cast<InitListExpr>(CLE->getInitializer()))
4986           Expr = ILE->getInit(0);
4987   }
4988 
4989   bool Result;
4990   return (!Expr->isValueDependent() &&
4991           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4992           !Result);
4993 }
4994 
4995 static void CheckNonNullArgument(Sema &S,
4996                                  const Expr *ArgExpr,
4997                                  SourceLocation CallSiteLoc) {
4998   if (CheckNonNullExpr(S, ArgExpr))
4999     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
5000                           S.PDiag(diag::warn_null_arg)
5001                               << ArgExpr->getSourceRange());
5002 }
5003 
5004 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
5005   FormatStringInfo FSI;
5006   if ((GetFormatStringType(Format) == FST_NSString) &&
5007       getFormatStringInfo(Format, false, &FSI)) {
5008     Idx = FSI.FormatIdx;
5009     return true;
5010   }
5011   return false;
5012 }
5013 
5014 /// Diagnose use of %s directive in an NSString which is being passed
5015 /// as formatting string to formatting method.
5016 static void
5017 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
5018                                         const NamedDecl *FDecl,
5019                                         Expr **Args,
5020                                         unsigned NumArgs) {
5021   unsigned Idx = 0;
5022   bool Format = false;
5023   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
5024   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
5025     Idx = 2;
5026     Format = true;
5027   }
5028   else
5029     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5030       if (S.GetFormatNSStringIdx(I, Idx)) {
5031         Format = true;
5032         break;
5033       }
5034     }
5035   if (!Format || NumArgs <= Idx)
5036     return;
5037   const Expr *FormatExpr = Args[Idx];
5038   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
5039     FormatExpr = CSCE->getSubExpr();
5040   const StringLiteral *FormatString;
5041   if (const ObjCStringLiteral *OSL =
5042       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
5043     FormatString = OSL->getString();
5044   else
5045     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
5046   if (!FormatString)
5047     return;
5048   if (S.FormatStringHasSArg(FormatString)) {
5049     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
5050       << "%s" << 1 << 1;
5051     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
5052       << FDecl->getDeclName();
5053   }
5054 }
5055 
5056 /// Determine whether the given type has a non-null nullability annotation.
5057 static bool isNonNullType(ASTContext &ctx, QualType type) {
5058   if (auto nullability = type->getNullability(ctx))
5059     return *nullability == NullabilityKind::NonNull;
5060 
5061   return false;
5062 }
5063 
5064 static void CheckNonNullArguments(Sema &S,
5065                                   const NamedDecl *FDecl,
5066                                   const FunctionProtoType *Proto,
5067                                   ArrayRef<const Expr *> Args,
5068                                   SourceLocation CallSiteLoc) {
5069   assert((FDecl || Proto) && "Need a function declaration or prototype");
5070 
5071   // Already checked by by constant evaluator.
5072   if (S.isConstantEvaluated())
5073     return;
5074   // Check the attributes attached to the method/function itself.
5075   llvm::SmallBitVector NonNullArgs;
5076   if (FDecl) {
5077     // Handle the nonnull attribute on the function/method declaration itself.
5078     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
5079       if (!NonNull->args_size()) {
5080         // Easy case: all pointer arguments are nonnull.
5081         for (const auto *Arg : Args)
5082           if (S.isValidPointerAttrType(Arg->getType()))
5083             CheckNonNullArgument(S, Arg, CallSiteLoc);
5084         return;
5085       }
5086 
5087       for (const ParamIdx &Idx : NonNull->args()) {
5088         unsigned IdxAST = Idx.getASTIndex();
5089         if (IdxAST >= Args.size())
5090           continue;
5091         if (NonNullArgs.empty())
5092           NonNullArgs.resize(Args.size());
5093         NonNullArgs.set(IdxAST);
5094       }
5095     }
5096   }
5097 
5098   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
5099     // Handle the nonnull attribute on the parameters of the
5100     // function/method.
5101     ArrayRef<ParmVarDecl*> parms;
5102     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
5103       parms = FD->parameters();
5104     else
5105       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
5106 
5107     unsigned ParamIndex = 0;
5108     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
5109          I != E; ++I, ++ParamIndex) {
5110       const ParmVarDecl *PVD = *I;
5111       if (PVD->hasAttr<NonNullAttr>() ||
5112           isNonNullType(S.Context, PVD->getType())) {
5113         if (NonNullArgs.empty())
5114           NonNullArgs.resize(Args.size());
5115 
5116         NonNullArgs.set(ParamIndex);
5117       }
5118     }
5119   } else {
5120     // If we have a non-function, non-method declaration but no
5121     // function prototype, try to dig out the function prototype.
5122     if (!Proto) {
5123       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
5124         QualType type = VD->getType().getNonReferenceType();
5125         if (auto pointerType = type->getAs<PointerType>())
5126           type = pointerType->getPointeeType();
5127         else if (auto blockType = type->getAs<BlockPointerType>())
5128           type = blockType->getPointeeType();
5129         // FIXME: data member pointers?
5130 
5131         // Dig out the function prototype, if there is one.
5132         Proto = type->getAs<FunctionProtoType>();
5133       }
5134     }
5135 
5136     // Fill in non-null argument information from the nullability
5137     // information on the parameter types (if we have them).
5138     if (Proto) {
5139       unsigned Index = 0;
5140       for (auto paramType : Proto->getParamTypes()) {
5141         if (isNonNullType(S.Context, paramType)) {
5142           if (NonNullArgs.empty())
5143             NonNullArgs.resize(Args.size());
5144 
5145           NonNullArgs.set(Index);
5146         }
5147 
5148         ++Index;
5149       }
5150     }
5151   }
5152 
5153   // Check for non-null arguments.
5154   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
5155        ArgIndex != ArgIndexEnd; ++ArgIndex) {
5156     if (NonNullArgs[ArgIndex])
5157       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
5158   }
5159 }
5160 
5161 /// Warn if a pointer or reference argument passed to a function points to an
5162 /// object that is less aligned than the parameter. This can happen when
5163 /// creating a typedef with a lower alignment than the original type and then
5164 /// calling functions defined in terms of the original type.
5165 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
5166                              StringRef ParamName, QualType ArgTy,
5167                              QualType ParamTy) {
5168 
5169   // If a function accepts a pointer or reference type
5170   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
5171     return;
5172 
5173   // If the parameter is a pointer type, get the pointee type for the
5174   // argument too. If the parameter is a reference type, don't try to get
5175   // the pointee type for the argument.
5176   if (ParamTy->isPointerType())
5177     ArgTy = ArgTy->getPointeeType();
5178 
5179   // Remove reference or pointer
5180   ParamTy = ParamTy->getPointeeType();
5181 
5182   // Find expected alignment, and the actual alignment of the passed object.
5183   // getTypeAlignInChars requires complete types
5184   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
5185       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
5186       ArgTy->isUndeducedType())
5187     return;
5188 
5189   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
5190   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
5191 
5192   // If the argument is less aligned than the parameter, there is a
5193   // potential alignment issue.
5194   if (ArgAlign < ParamAlign)
5195     Diag(Loc, diag::warn_param_mismatched_alignment)
5196         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
5197         << ParamName << (FDecl != nullptr) << FDecl;
5198 }
5199 
5200 /// Handles the checks for format strings, non-POD arguments to vararg
5201 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
5202 /// attributes.
5203 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
5204                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
5205                      bool IsMemberFunction, SourceLocation Loc,
5206                      SourceRange Range, VariadicCallType CallType) {
5207   // FIXME: We should check as much as we can in the template definition.
5208   if (CurContext->isDependentContext())
5209     return;
5210 
5211   // Printf and scanf checking.
5212   llvm::SmallBitVector CheckedVarArgs;
5213   if (FDecl) {
5214     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5215       // Only create vector if there are format attributes.
5216       CheckedVarArgs.resize(Args.size());
5217 
5218       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
5219                            CheckedVarArgs);
5220     }
5221   }
5222 
5223   // Refuse POD arguments that weren't caught by the format string
5224   // checks above.
5225   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
5226   if (CallType != VariadicDoesNotApply &&
5227       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
5228     unsigned NumParams = Proto ? Proto->getNumParams()
5229                        : FDecl && isa<FunctionDecl>(FDecl)
5230                            ? cast<FunctionDecl>(FDecl)->getNumParams()
5231                        : FDecl && isa<ObjCMethodDecl>(FDecl)
5232                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
5233                        : 0;
5234 
5235     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
5236       // Args[ArgIdx] can be null in malformed code.
5237       if (const Expr *Arg = Args[ArgIdx]) {
5238         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
5239           checkVariadicArgument(Arg, CallType);
5240       }
5241     }
5242   }
5243 
5244   if (FDecl || Proto) {
5245     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
5246 
5247     // Type safety checking.
5248     if (FDecl) {
5249       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
5250         CheckArgumentWithTypeTag(I, Args, Loc);
5251     }
5252   }
5253 
5254   // Check that passed arguments match the alignment of original arguments.
5255   // Try to get the missing prototype from the declaration.
5256   if (!Proto && FDecl) {
5257     const auto *FT = FDecl->getFunctionType();
5258     if (isa_and_nonnull<FunctionProtoType>(FT))
5259       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
5260   }
5261   if (Proto) {
5262     // For variadic functions, we may have more args than parameters.
5263     // For some K&R functions, we may have less args than parameters.
5264     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
5265     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
5266       // Args[ArgIdx] can be null in malformed code.
5267       if (const Expr *Arg = Args[ArgIdx]) {
5268         if (Arg->containsErrors())
5269           continue;
5270 
5271         QualType ParamTy = Proto->getParamType(ArgIdx);
5272         QualType ArgTy = Arg->getType();
5273         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
5274                           ArgTy, ParamTy);
5275       }
5276     }
5277   }
5278 
5279   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
5280     auto *AA = FDecl->getAttr<AllocAlignAttr>();
5281     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
5282     if (!Arg->isValueDependent()) {
5283       Expr::EvalResult Align;
5284       if (Arg->EvaluateAsInt(Align, Context)) {
5285         const llvm::APSInt &I = Align.Val.getInt();
5286         if (!I.isPowerOf2())
5287           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
5288               << Arg->getSourceRange();
5289 
5290         if (I > Sema::MaximumAlignment)
5291           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
5292               << Arg->getSourceRange() << Sema::MaximumAlignment;
5293       }
5294     }
5295   }
5296 
5297   if (FD)
5298     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
5299 }
5300 
5301 /// CheckConstructorCall - Check a constructor call for correctness and safety
5302 /// properties not enforced by the C type system.
5303 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5304                                 ArrayRef<const Expr *> Args,
5305                                 const FunctionProtoType *Proto,
5306                                 SourceLocation Loc) {
5307   VariadicCallType CallType =
5308       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5309 
5310   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5311   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5312                     Context.getPointerType(Ctor->getThisObjectType()));
5313 
5314   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5315             Loc, SourceRange(), CallType);
5316 }
5317 
5318 /// CheckFunctionCall - Check a direct function call for various correctness
5319 /// and safety properties not strictly enforced by the C type system.
5320 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5321                              const FunctionProtoType *Proto) {
5322   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5323                               isa<CXXMethodDecl>(FDecl);
5324   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5325                           IsMemberOperatorCall;
5326   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5327                                                   TheCall->getCallee());
5328   Expr** Args = TheCall->getArgs();
5329   unsigned NumArgs = TheCall->getNumArgs();
5330 
5331   Expr *ImplicitThis = nullptr;
5332   if (IsMemberOperatorCall) {
5333     // If this is a call to a member operator, hide the first argument
5334     // from checkCall.
5335     // FIXME: Our choice of AST representation here is less than ideal.
5336     ImplicitThis = Args[0];
5337     ++Args;
5338     --NumArgs;
5339   } else if (IsMemberFunction)
5340     ImplicitThis =
5341         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5342 
5343   if (ImplicitThis) {
5344     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5345     // used.
5346     QualType ThisType = ImplicitThis->getType();
5347     if (!ThisType->isPointerType()) {
5348       assert(!ThisType->isReferenceType());
5349       ThisType = Context.getPointerType(ThisType);
5350     }
5351 
5352     QualType ThisTypeFromDecl =
5353         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5354 
5355     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5356                       ThisTypeFromDecl);
5357   }
5358 
5359   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5360             IsMemberFunction, TheCall->getRParenLoc(),
5361             TheCall->getCallee()->getSourceRange(), CallType);
5362 
5363   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5364   // None of the checks below are needed for functions that don't have
5365   // simple names (e.g., C++ conversion functions).
5366   if (!FnInfo)
5367     return false;
5368 
5369   CheckTCBEnforcement(TheCall, FDecl);
5370 
5371   CheckAbsoluteValueFunction(TheCall, FDecl);
5372   CheckMaxUnsignedZero(TheCall, FDecl);
5373 
5374   if (getLangOpts().ObjC)
5375     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5376 
5377   unsigned CMId = FDecl->getMemoryFunctionKind();
5378 
5379   // Handle memory setting and copying functions.
5380   switch (CMId) {
5381   case 0:
5382     return false;
5383   case Builtin::BIstrlcpy: // fallthrough
5384   case Builtin::BIstrlcat:
5385     CheckStrlcpycatArguments(TheCall, FnInfo);
5386     break;
5387   case Builtin::BIstrncat:
5388     CheckStrncatArguments(TheCall, FnInfo);
5389     break;
5390   case Builtin::BIfree:
5391     CheckFreeArguments(TheCall);
5392     break;
5393   default:
5394     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5395   }
5396 
5397   return false;
5398 }
5399 
5400 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5401                                ArrayRef<const Expr *> Args) {
5402   VariadicCallType CallType =
5403       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5404 
5405   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5406             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5407             CallType);
5408 
5409   return false;
5410 }
5411 
5412 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5413                             const FunctionProtoType *Proto) {
5414   QualType Ty;
5415   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5416     Ty = V->getType().getNonReferenceType();
5417   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5418     Ty = F->getType().getNonReferenceType();
5419   else
5420     return false;
5421 
5422   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5423       !Ty->isFunctionProtoType())
5424     return false;
5425 
5426   VariadicCallType CallType;
5427   if (!Proto || !Proto->isVariadic()) {
5428     CallType = VariadicDoesNotApply;
5429   } else if (Ty->isBlockPointerType()) {
5430     CallType = VariadicBlock;
5431   } else { // Ty->isFunctionPointerType()
5432     CallType = VariadicFunction;
5433   }
5434 
5435   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5436             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5437             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5438             TheCall->getCallee()->getSourceRange(), CallType);
5439 
5440   return false;
5441 }
5442 
5443 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5444 /// such as function pointers returned from functions.
5445 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5446   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5447                                                   TheCall->getCallee());
5448   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5449             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5450             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5451             TheCall->getCallee()->getSourceRange(), CallType);
5452 
5453   return false;
5454 }
5455 
5456 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5457   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5458     return false;
5459 
5460   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5461   switch (Op) {
5462   case AtomicExpr::AO__c11_atomic_init:
5463   case AtomicExpr::AO__opencl_atomic_init:
5464     llvm_unreachable("There is no ordering argument for an init");
5465 
5466   case AtomicExpr::AO__c11_atomic_load:
5467   case AtomicExpr::AO__opencl_atomic_load:
5468   case AtomicExpr::AO__hip_atomic_load:
5469   case AtomicExpr::AO__atomic_load_n:
5470   case AtomicExpr::AO__atomic_load:
5471     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5472            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5473 
5474   case AtomicExpr::AO__c11_atomic_store:
5475   case AtomicExpr::AO__opencl_atomic_store:
5476   case AtomicExpr::AO__hip_atomic_store:
5477   case AtomicExpr::AO__atomic_store:
5478   case AtomicExpr::AO__atomic_store_n:
5479     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5480            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5481            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5482 
5483   default:
5484     return true;
5485   }
5486 }
5487 
5488 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5489                                          AtomicExpr::AtomicOp Op) {
5490   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5491   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5492   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5493   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5494                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5495                          Op);
5496 }
5497 
5498 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5499                                  SourceLocation RParenLoc, MultiExprArg Args,
5500                                  AtomicExpr::AtomicOp Op,
5501                                  AtomicArgumentOrder ArgOrder) {
5502   // All the non-OpenCL operations take one of the following forms.
5503   // The OpenCL operations take the __c11 forms with one extra argument for
5504   // synchronization scope.
5505   enum {
5506     // C    __c11_atomic_init(A *, C)
5507     Init,
5508 
5509     // C    __c11_atomic_load(A *, int)
5510     Load,
5511 
5512     // void __atomic_load(A *, CP, int)
5513     LoadCopy,
5514 
5515     // void __atomic_store(A *, CP, int)
5516     Copy,
5517 
5518     // C    __c11_atomic_add(A *, M, int)
5519     Arithmetic,
5520 
5521     // C    __atomic_exchange_n(A *, CP, int)
5522     Xchg,
5523 
5524     // void __atomic_exchange(A *, C *, CP, int)
5525     GNUXchg,
5526 
5527     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5528     C11CmpXchg,
5529 
5530     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5531     GNUCmpXchg
5532   } Form = Init;
5533 
5534   const unsigned NumForm = GNUCmpXchg + 1;
5535   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5536   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5537   // where:
5538   //   C is an appropriate type,
5539   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5540   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5541   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5542   //   the int parameters are for orderings.
5543 
5544   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5545       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5546       "need to update code for modified forms");
5547   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5548                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5549                         AtomicExpr::AO__atomic_load,
5550                 "need to update code for modified C11 atomics");
5551   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5552                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5553   bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load &&
5554                Op <= AtomicExpr::AO__hip_atomic_fetch_max;
5555   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5556                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5557                IsOpenCL;
5558   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5559              Op == AtomicExpr::AO__atomic_store_n ||
5560              Op == AtomicExpr::AO__atomic_exchange_n ||
5561              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5562   bool IsAddSub = false;
5563 
5564   switch (Op) {
5565   case AtomicExpr::AO__c11_atomic_init:
5566   case AtomicExpr::AO__opencl_atomic_init:
5567     Form = Init;
5568     break;
5569 
5570   case AtomicExpr::AO__c11_atomic_load:
5571   case AtomicExpr::AO__opencl_atomic_load:
5572   case AtomicExpr::AO__hip_atomic_load:
5573   case AtomicExpr::AO__atomic_load_n:
5574     Form = Load;
5575     break;
5576 
5577   case AtomicExpr::AO__atomic_load:
5578     Form = LoadCopy;
5579     break;
5580 
5581   case AtomicExpr::AO__c11_atomic_store:
5582   case AtomicExpr::AO__opencl_atomic_store:
5583   case AtomicExpr::AO__hip_atomic_store:
5584   case AtomicExpr::AO__atomic_store:
5585   case AtomicExpr::AO__atomic_store_n:
5586     Form = Copy;
5587     break;
5588   case AtomicExpr::AO__hip_atomic_fetch_add:
5589   case AtomicExpr::AO__hip_atomic_fetch_min:
5590   case AtomicExpr::AO__hip_atomic_fetch_max:
5591   case AtomicExpr::AO__c11_atomic_fetch_add:
5592   case AtomicExpr::AO__c11_atomic_fetch_sub:
5593   case AtomicExpr::AO__opencl_atomic_fetch_add:
5594   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5595   case AtomicExpr::AO__atomic_fetch_add:
5596   case AtomicExpr::AO__atomic_fetch_sub:
5597   case AtomicExpr::AO__atomic_add_fetch:
5598   case AtomicExpr::AO__atomic_sub_fetch:
5599     IsAddSub = true;
5600     Form = Arithmetic;
5601     break;
5602   case AtomicExpr::AO__c11_atomic_fetch_and:
5603   case AtomicExpr::AO__c11_atomic_fetch_or:
5604   case AtomicExpr::AO__c11_atomic_fetch_xor:
5605   case AtomicExpr::AO__hip_atomic_fetch_and:
5606   case AtomicExpr::AO__hip_atomic_fetch_or:
5607   case AtomicExpr::AO__hip_atomic_fetch_xor:
5608   case AtomicExpr::AO__c11_atomic_fetch_nand:
5609   case AtomicExpr::AO__opencl_atomic_fetch_and:
5610   case AtomicExpr::AO__opencl_atomic_fetch_or:
5611   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5612   case AtomicExpr::AO__atomic_fetch_and:
5613   case AtomicExpr::AO__atomic_fetch_or:
5614   case AtomicExpr::AO__atomic_fetch_xor:
5615   case AtomicExpr::AO__atomic_fetch_nand:
5616   case AtomicExpr::AO__atomic_and_fetch:
5617   case AtomicExpr::AO__atomic_or_fetch:
5618   case AtomicExpr::AO__atomic_xor_fetch:
5619   case AtomicExpr::AO__atomic_nand_fetch:
5620     Form = Arithmetic;
5621     break;
5622   case AtomicExpr::AO__c11_atomic_fetch_min:
5623   case AtomicExpr::AO__c11_atomic_fetch_max:
5624   case AtomicExpr::AO__opencl_atomic_fetch_min:
5625   case AtomicExpr::AO__opencl_atomic_fetch_max:
5626   case AtomicExpr::AO__atomic_min_fetch:
5627   case AtomicExpr::AO__atomic_max_fetch:
5628   case AtomicExpr::AO__atomic_fetch_min:
5629   case AtomicExpr::AO__atomic_fetch_max:
5630     Form = Arithmetic;
5631     break;
5632 
5633   case AtomicExpr::AO__c11_atomic_exchange:
5634   case AtomicExpr::AO__hip_atomic_exchange:
5635   case AtomicExpr::AO__opencl_atomic_exchange:
5636   case AtomicExpr::AO__atomic_exchange_n:
5637     Form = Xchg;
5638     break;
5639 
5640   case AtomicExpr::AO__atomic_exchange:
5641     Form = GNUXchg;
5642     break;
5643 
5644   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5645   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5646   case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5647   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5648   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5649   case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5650     Form = C11CmpXchg;
5651     break;
5652 
5653   case AtomicExpr::AO__atomic_compare_exchange:
5654   case AtomicExpr::AO__atomic_compare_exchange_n:
5655     Form = GNUCmpXchg;
5656     break;
5657   }
5658 
5659   unsigned AdjustedNumArgs = NumArgs[Form];
5660   if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init)
5661     ++AdjustedNumArgs;
5662   // Check we have the right number of arguments.
5663   if (Args.size() < AdjustedNumArgs) {
5664     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5665         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5666         << ExprRange;
5667     return ExprError();
5668   } else if (Args.size() > AdjustedNumArgs) {
5669     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5670          diag::err_typecheck_call_too_many_args)
5671         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5672         << ExprRange;
5673     return ExprError();
5674   }
5675 
5676   // Inspect the first argument of the atomic operation.
5677   Expr *Ptr = Args[0];
5678   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5679   if (ConvertedPtr.isInvalid())
5680     return ExprError();
5681 
5682   Ptr = ConvertedPtr.get();
5683   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5684   if (!pointerType) {
5685     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5686         << Ptr->getType() << Ptr->getSourceRange();
5687     return ExprError();
5688   }
5689 
5690   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5691   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5692   QualType ValType = AtomTy; // 'C'
5693   if (IsC11) {
5694     if (!AtomTy->isAtomicType()) {
5695       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5696           << Ptr->getType() << Ptr->getSourceRange();
5697       return ExprError();
5698     }
5699     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5700         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5701       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5702           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5703           << Ptr->getSourceRange();
5704       return ExprError();
5705     }
5706     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5707   } else if (Form != Load && Form != LoadCopy) {
5708     if (ValType.isConstQualified()) {
5709       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5710           << Ptr->getType() << Ptr->getSourceRange();
5711       return ExprError();
5712     }
5713   }
5714 
5715   // For an arithmetic operation, the implied arithmetic must be well-formed.
5716   if (Form == Arithmetic) {
5717     // GCC does not enforce these rules for GNU atomics, but we do to help catch
5718     // trivial type errors.
5719     auto IsAllowedValueType = [&](QualType ValType) {
5720       if (ValType->isIntegerType())
5721         return true;
5722       if (ValType->isPointerType())
5723         return true;
5724       if (!ValType->isFloatingType())
5725         return false;
5726       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5727       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5728           &Context.getTargetInfo().getLongDoubleFormat() ==
5729               &llvm::APFloat::x87DoubleExtended())
5730         return false;
5731       return true;
5732     };
5733     if (IsAddSub && !IsAllowedValueType(ValType)) {
5734       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5735           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5736       return ExprError();
5737     }
5738     if (!IsAddSub && !ValType->isIntegerType()) {
5739       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5740           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5741       return ExprError();
5742     }
5743     if (IsC11 && ValType->isPointerType() &&
5744         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5745                             diag::err_incomplete_type)) {
5746       return ExprError();
5747     }
5748   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5749     // For __atomic_*_n operations, the value type must be a scalar integral or
5750     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5751     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5752         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5753     return ExprError();
5754   }
5755 
5756   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5757       !AtomTy->isScalarType()) {
5758     // For GNU atomics, require a trivially-copyable type. This is not part of
5759     // the GNU atomics specification but we enforce it for consistency with
5760     // other atomics which generally all require a trivially-copyable type. This
5761     // is because atomics just copy bits.
5762     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5763         << Ptr->getType() << Ptr->getSourceRange();
5764     return ExprError();
5765   }
5766 
5767   switch (ValType.getObjCLifetime()) {
5768   case Qualifiers::OCL_None:
5769   case Qualifiers::OCL_ExplicitNone:
5770     // okay
5771     break;
5772 
5773   case Qualifiers::OCL_Weak:
5774   case Qualifiers::OCL_Strong:
5775   case Qualifiers::OCL_Autoreleasing:
5776     // FIXME: Can this happen? By this point, ValType should be known
5777     // to be trivially copyable.
5778     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5779         << ValType << Ptr->getSourceRange();
5780     return ExprError();
5781   }
5782 
5783   // All atomic operations have an overload which takes a pointer to a volatile
5784   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5785   // into the result or the other operands. Similarly atomic_load takes a
5786   // pointer to a const 'A'.
5787   ValType.removeLocalVolatile();
5788   ValType.removeLocalConst();
5789   QualType ResultType = ValType;
5790   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5791       Form == Init)
5792     ResultType = Context.VoidTy;
5793   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5794     ResultType = Context.BoolTy;
5795 
5796   // The type of a parameter passed 'by value'. In the GNU atomics, such
5797   // arguments are actually passed as pointers.
5798   QualType ByValType = ValType; // 'CP'
5799   bool IsPassedByAddress = false;
5800   if (!IsC11 && !IsHIP && !IsN) {
5801     ByValType = Ptr->getType();
5802     IsPassedByAddress = true;
5803   }
5804 
5805   SmallVector<Expr *, 5> APIOrderedArgs;
5806   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5807     APIOrderedArgs.push_back(Args[0]);
5808     switch (Form) {
5809     case Init:
5810     case Load:
5811       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5812       break;
5813     case LoadCopy:
5814     case Copy:
5815     case Arithmetic:
5816     case Xchg:
5817       APIOrderedArgs.push_back(Args[2]); // Val1
5818       APIOrderedArgs.push_back(Args[1]); // Order
5819       break;
5820     case GNUXchg:
5821       APIOrderedArgs.push_back(Args[2]); // Val1
5822       APIOrderedArgs.push_back(Args[3]); // Val2
5823       APIOrderedArgs.push_back(Args[1]); // Order
5824       break;
5825     case C11CmpXchg:
5826       APIOrderedArgs.push_back(Args[2]); // Val1
5827       APIOrderedArgs.push_back(Args[4]); // Val2
5828       APIOrderedArgs.push_back(Args[1]); // Order
5829       APIOrderedArgs.push_back(Args[3]); // OrderFail
5830       break;
5831     case GNUCmpXchg:
5832       APIOrderedArgs.push_back(Args[2]); // Val1
5833       APIOrderedArgs.push_back(Args[4]); // Val2
5834       APIOrderedArgs.push_back(Args[5]); // Weak
5835       APIOrderedArgs.push_back(Args[1]); // Order
5836       APIOrderedArgs.push_back(Args[3]); // OrderFail
5837       break;
5838     }
5839   } else
5840     APIOrderedArgs.append(Args.begin(), Args.end());
5841 
5842   // The first argument's non-CV pointer type is used to deduce the type of
5843   // subsequent arguments, except for:
5844   //  - weak flag (always converted to bool)
5845   //  - memory order (always converted to int)
5846   //  - scope  (always converted to int)
5847   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5848     QualType Ty;
5849     if (i < NumVals[Form] + 1) {
5850       switch (i) {
5851       case 0:
5852         // The first argument is always a pointer. It has a fixed type.
5853         // It is always dereferenced, a nullptr is undefined.
5854         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5855         // Nothing else to do: we already know all we want about this pointer.
5856         continue;
5857       case 1:
5858         // The second argument is the non-atomic operand. For arithmetic, this
5859         // is always passed by value, and for a compare_exchange it is always
5860         // passed by address. For the rest, GNU uses by-address and C11 uses
5861         // by-value.
5862         assert(Form != Load);
5863         if (Form == Arithmetic && ValType->isPointerType())
5864           Ty = Context.getPointerDiffType();
5865         else if (Form == Init || Form == Arithmetic)
5866           Ty = ValType;
5867         else if (Form == Copy || Form == Xchg) {
5868           if (IsPassedByAddress) {
5869             // The value pointer is always dereferenced, a nullptr is undefined.
5870             CheckNonNullArgument(*this, APIOrderedArgs[i],
5871                                  ExprRange.getBegin());
5872           }
5873           Ty = ByValType;
5874         } else {
5875           Expr *ValArg = APIOrderedArgs[i];
5876           // The value pointer is always dereferenced, a nullptr is undefined.
5877           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5878           LangAS AS = LangAS::Default;
5879           // Keep address space of non-atomic pointer type.
5880           if (const PointerType *PtrTy =
5881                   ValArg->getType()->getAs<PointerType>()) {
5882             AS = PtrTy->getPointeeType().getAddressSpace();
5883           }
5884           Ty = Context.getPointerType(
5885               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5886         }
5887         break;
5888       case 2:
5889         // The third argument to compare_exchange / GNU exchange is the desired
5890         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5891         if (IsPassedByAddress)
5892           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5893         Ty = ByValType;
5894         break;
5895       case 3:
5896         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5897         Ty = Context.BoolTy;
5898         break;
5899       }
5900     } else {
5901       // The order(s) and scope are always converted to int.
5902       Ty = Context.IntTy;
5903     }
5904 
5905     InitializedEntity Entity =
5906         InitializedEntity::InitializeParameter(Context, Ty, false);
5907     ExprResult Arg = APIOrderedArgs[i];
5908     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5909     if (Arg.isInvalid())
5910       return true;
5911     APIOrderedArgs[i] = Arg.get();
5912   }
5913 
5914   // Permute the arguments into a 'consistent' order.
5915   SmallVector<Expr*, 5> SubExprs;
5916   SubExprs.push_back(Ptr);
5917   switch (Form) {
5918   case Init:
5919     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5920     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5921     break;
5922   case Load:
5923     SubExprs.push_back(APIOrderedArgs[1]); // Order
5924     break;
5925   case LoadCopy:
5926   case Copy:
5927   case Arithmetic:
5928   case Xchg:
5929     SubExprs.push_back(APIOrderedArgs[2]); // Order
5930     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5931     break;
5932   case GNUXchg:
5933     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5934     SubExprs.push_back(APIOrderedArgs[3]); // Order
5935     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5936     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5937     break;
5938   case C11CmpXchg:
5939     SubExprs.push_back(APIOrderedArgs[3]); // Order
5940     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5941     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5942     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5943     break;
5944   case GNUCmpXchg:
5945     SubExprs.push_back(APIOrderedArgs[4]); // Order
5946     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5947     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5948     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5949     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5950     break;
5951   }
5952 
5953   if (SubExprs.size() >= 2 && Form != Init) {
5954     if (Optional<llvm::APSInt> Result =
5955             SubExprs[1]->getIntegerConstantExpr(Context))
5956       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5957         Diag(SubExprs[1]->getBeginLoc(),
5958              diag::warn_atomic_op_has_invalid_memory_order)
5959             << SubExprs[1]->getSourceRange();
5960   }
5961 
5962   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5963     auto *Scope = Args[Args.size() - 1];
5964     if (Optional<llvm::APSInt> Result =
5965             Scope->getIntegerConstantExpr(Context)) {
5966       if (!ScopeModel->isValid(Result->getZExtValue()))
5967         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5968             << Scope->getSourceRange();
5969     }
5970     SubExprs.push_back(Scope);
5971   }
5972 
5973   AtomicExpr *AE = new (Context)
5974       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5975 
5976   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5977        Op == AtomicExpr::AO__c11_atomic_store ||
5978        Op == AtomicExpr::AO__opencl_atomic_load ||
5979        Op == AtomicExpr::AO__hip_atomic_load ||
5980        Op == AtomicExpr::AO__opencl_atomic_store ||
5981        Op == AtomicExpr::AO__hip_atomic_store) &&
5982       Context.AtomicUsesUnsupportedLibcall(AE))
5983     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5984         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5985              Op == AtomicExpr::AO__opencl_atomic_load ||
5986              Op == AtomicExpr::AO__hip_atomic_load)
5987                 ? 0
5988                 : 1);
5989 
5990   if (ValType->isBitIntType()) {
5991     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
5992     return ExprError();
5993   }
5994 
5995   return AE;
5996 }
5997 
5998 /// checkBuiltinArgument - Given a call to a builtin function, perform
5999 /// normal type-checking on the given argument, updating the call in
6000 /// place.  This is useful when a builtin function requires custom
6001 /// type-checking for some of its arguments but not necessarily all of
6002 /// them.
6003 ///
6004 /// Returns true on error.
6005 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
6006   FunctionDecl *Fn = E->getDirectCallee();
6007   assert(Fn && "builtin call without direct callee!");
6008 
6009   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
6010   InitializedEntity Entity =
6011     InitializedEntity::InitializeParameter(S.Context, Param);
6012 
6013   ExprResult Arg = E->getArg(0);
6014   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
6015   if (Arg.isInvalid())
6016     return true;
6017 
6018   E->setArg(ArgIndex, Arg.get());
6019   return false;
6020 }
6021 
6022 /// We have a call to a function like __sync_fetch_and_add, which is an
6023 /// overloaded function based on the pointer type of its first argument.
6024 /// The main BuildCallExpr routines have already promoted the types of
6025 /// arguments because all of these calls are prototyped as void(...).
6026 ///
6027 /// This function goes through and does final semantic checking for these
6028 /// builtins, as well as generating any warnings.
6029 ExprResult
6030 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
6031   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
6032   Expr *Callee = TheCall->getCallee();
6033   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
6034   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6035 
6036   // Ensure that we have at least one argument to do type inference from.
6037   if (TheCall->getNumArgs() < 1) {
6038     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6039         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
6040     return ExprError();
6041   }
6042 
6043   // Inspect the first argument of the atomic builtin.  This should always be
6044   // a pointer type, whose element is an integral scalar or pointer type.
6045   // Because it is a pointer type, we don't have to worry about any implicit
6046   // casts here.
6047   // FIXME: We don't allow floating point scalars as input.
6048   Expr *FirstArg = TheCall->getArg(0);
6049   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
6050   if (FirstArgResult.isInvalid())
6051     return ExprError();
6052   FirstArg = FirstArgResult.get();
6053   TheCall->setArg(0, FirstArg);
6054 
6055   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
6056   if (!pointerType) {
6057     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
6058         << FirstArg->getType() << FirstArg->getSourceRange();
6059     return ExprError();
6060   }
6061 
6062   QualType ValType = pointerType->getPointeeType();
6063   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6064       !ValType->isBlockPointerType()) {
6065     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
6066         << FirstArg->getType() << FirstArg->getSourceRange();
6067     return ExprError();
6068   }
6069 
6070   if (ValType.isConstQualified()) {
6071     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
6072         << FirstArg->getType() << FirstArg->getSourceRange();
6073     return ExprError();
6074   }
6075 
6076   switch (ValType.getObjCLifetime()) {
6077   case Qualifiers::OCL_None:
6078   case Qualifiers::OCL_ExplicitNone:
6079     // okay
6080     break;
6081 
6082   case Qualifiers::OCL_Weak:
6083   case Qualifiers::OCL_Strong:
6084   case Qualifiers::OCL_Autoreleasing:
6085     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
6086         << ValType << FirstArg->getSourceRange();
6087     return ExprError();
6088   }
6089 
6090   // Strip any qualifiers off ValType.
6091   ValType = ValType.getUnqualifiedType();
6092 
6093   // The majority of builtins return a value, but a few have special return
6094   // types, so allow them to override appropriately below.
6095   QualType ResultType = ValType;
6096 
6097   // We need to figure out which concrete builtin this maps onto.  For example,
6098   // __sync_fetch_and_add with a 2 byte object turns into
6099   // __sync_fetch_and_add_2.
6100 #define BUILTIN_ROW(x) \
6101   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
6102     Builtin::BI##x##_8, Builtin::BI##x##_16 }
6103 
6104   static const unsigned BuiltinIndices[][5] = {
6105     BUILTIN_ROW(__sync_fetch_and_add),
6106     BUILTIN_ROW(__sync_fetch_and_sub),
6107     BUILTIN_ROW(__sync_fetch_and_or),
6108     BUILTIN_ROW(__sync_fetch_and_and),
6109     BUILTIN_ROW(__sync_fetch_and_xor),
6110     BUILTIN_ROW(__sync_fetch_and_nand),
6111 
6112     BUILTIN_ROW(__sync_add_and_fetch),
6113     BUILTIN_ROW(__sync_sub_and_fetch),
6114     BUILTIN_ROW(__sync_and_and_fetch),
6115     BUILTIN_ROW(__sync_or_and_fetch),
6116     BUILTIN_ROW(__sync_xor_and_fetch),
6117     BUILTIN_ROW(__sync_nand_and_fetch),
6118 
6119     BUILTIN_ROW(__sync_val_compare_and_swap),
6120     BUILTIN_ROW(__sync_bool_compare_and_swap),
6121     BUILTIN_ROW(__sync_lock_test_and_set),
6122     BUILTIN_ROW(__sync_lock_release),
6123     BUILTIN_ROW(__sync_swap)
6124   };
6125 #undef BUILTIN_ROW
6126 
6127   // Determine the index of the size.
6128   unsigned SizeIndex;
6129   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
6130   case 1: SizeIndex = 0; break;
6131   case 2: SizeIndex = 1; break;
6132   case 4: SizeIndex = 2; break;
6133   case 8: SizeIndex = 3; break;
6134   case 16: SizeIndex = 4; break;
6135   default:
6136     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
6137         << FirstArg->getType() << FirstArg->getSourceRange();
6138     return ExprError();
6139   }
6140 
6141   // Each of these builtins has one pointer argument, followed by some number of
6142   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
6143   // that we ignore.  Find out which row of BuiltinIndices to read from as well
6144   // as the number of fixed args.
6145   unsigned BuiltinID = FDecl->getBuiltinID();
6146   unsigned BuiltinIndex, NumFixed = 1;
6147   bool WarnAboutSemanticsChange = false;
6148   switch (BuiltinID) {
6149   default: llvm_unreachable("Unknown overloaded atomic builtin!");
6150   case Builtin::BI__sync_fetch_and_add:
6151   case Builtin::BI__sync_fetch_and_add_1:
6152   case Builtin::BI__sync_fetch_and_add_2:
6153   case Builtin::BI__sync_fetch_and_add_4:
6154   case Builtin::BI__sync_fetch_and_add_8:
6155   case Builtin::BI__sync_fetch_and_add_16:
6156     BuiltinIndex = 0;
6157     break;
6158 
6159   case Builtin::BI__sync_fetch_and_sub:
6160   case Builtin::BI__sync_fetch_and_sub_1:
6161   case Builtin::BI__sync_fetch_and_sub_2:
6162   case Builtin::BI__sync_fetch_and_sub_4:
6163   case Builtin::BI__sync_fetch_and_sub_8:
6164   case Builtin::BI__sync_fetch_and_sub_16:
6165     BuiltinIndex = 1;
6166     break;
6167 
6168   case Builtin::BI__sync_fetch_and_or:
6169   case Builtin::BI__sync_fetch_and_or_1:
6170   case Builtin::BI__sync_fetch_and_or_2:
6171   case Builtin::BI__sync_fetch_and_or_4:
6172   case Builtin::BI__sync_fetch_and_or_8:
6173   case Builtin::BI__sync_fetch_and_or_16:
6174     BuiltinIndex = 2;
6175     break;
6176 
6177   case Builtin::BI__sync_fetch_and_and:
6178   case Builtin::BI__sync_fetch_and_and_1:
6179   case Builtin::BI__sync_fetch_and_and_2:
6180   case Builtin::BI__sync_fetch_and_and_4:
6181   case Builtin::BI__sync_fetch_and_and_8:
6182   case Builtin::BI__sync_fetch_and_and_16:
6183     BuiltinIndex = 3;
6184     break;
6185 
6186   case Builtin::BI__sync_fetch_and_xor:
6187   case Builtin::BI__sync_fetch_and_xor_1:
6188   case Builtin::BI__sync_fetch_and_xor_2:
6189   case Builtin::BI__sync_fetch_and_xor_4:
6190   case Builtin::BI__sync_fetch_and_xor_8:
6191   case Builtin::BI__sync_fetch_and_xor_16:
6192     BuiltinIndex = 4;
6193     break;
6194 
6195   case Builtin::BI__sync_fetch_and_nand:
6196   case Builtin::BI__sync_fetch_and_nand_1:
6197   case Builtin::BI__sync_fetch_and_nand_2:
6198   case Builtin::BI__sync_fetch_and_nand_4:
6199   case Builtin::BI__sync_fetch_and_nand_8:
6200   case Builtin::BI__sync_fetch_and_nand_16:
6201     BuiltinIndex = 5;
6202     WarnAboutSemanticsChange = true;
6203     break;
6204 
6205   case Builtin::BI__sync_add_and_fetch:
6206   case Builtin::BI__sync_add_and_fetch_1:
6207   case Builtin::BI__sync_add_and_fetch_2:
6208   case Builtin::BI__sync_add_and_fetch_4:
6209   case Builtin::BI__sync_add_and_fetch_8:
6210   case Builtin::BI__sync_add_and_fetch_16:
6211     BuiltinIndex = 6;
6212     break;
6213 
6214   case Builtin::BI__sync_sub_and_fetch:
6215   case Builtin::BI__sync_sub_and_fetch_1:
6216   case Builtin::BI__sync_sub_and_fetch_2:
6217   case Builtin::BI__sync_sub_and_fetch_4:
6218   case Builtin::BI__sync_sub_and_fetch_8:
6219   case Builtin::BI__sync_sub_and_fetch_16:
6220     BuiltinIndex = 7;
6221     break;
6222 
6223   case Builtin::BI__sync_and_and_fetch:
6224   case Builtin::BI__sync_and_and_fetch_1:
6225   case Builtin::BI__sync_and_and_fetch_2:
6226   case Builtin::BI__sync_and_and_fetch_4:
6227   case Builtin::BI__sync_and_and_fetch_8:
6228   case Builtin::BI__sync_and_and_fetch_16:
6229     BuiltinIndex = 8;
6230     break;
6231 
6232   case Builtin::BI__sync_or_and_fetch:
6233   case Builtin::BI__sync_or_and_fetch_1:
6234   case Builtin::BI__sync_or_and_fetch_2:
6235   case Builtin::BI__sync_or_and_fetch_4:
6236   case Builtin::BI__sync_or_and_fetch_8:
6237   case Builtin::BI__sync_or_and_fetch_16:
6238     BuiltinIndex = 9;
6239     break;
6240 
6241   case Builtin::BI__sync_xor_and_fetch:
6242   case Builtin::BI__sync_xor_and_fetch_1:
6243   case Builtin::BI__sync_xor_and_fetch_2:
6244   case Builtin::BI__sync_xor_and_fetch_4:
6245   case Builtin::BI__sync_xor_and_fetch_8:
6246   case Builtin::BI__sync_xor_and_fetch_16:
6247     BuiltinIndex = 10;
6248     break;
6249 
6250   case Builtin::BI__sync_nand_and_fetch:
6251   case Builtin::BI__sync_nand_and_fetch_1:
6252   case Builtin::BI__sync_nand_and_fetch_2:
6253   case Builtin::BI__sync_nand_and_fetch_4:
6254   case Builtin::BI__sync_nand_and_fetch_8:
6255   case Builtin::BI__sync_nand_and_fetch_16:
6256     BuiltinIndex = 11;
6257     WarnAboutSemanticsChange = true;
6258     break;
6259 
6260   case Builtin::BI__sync_val_compare_and_swap:
6261   case Builtin::BI__sync_val_compare_and_swap_1:
6262   case Builtin::BI__sync_val_compare_and_swap_2:
6263   case Builtin::BI__sync_val_compare_and_swap_4:
6264   case Builtin::BI__sync_val_compare_and_swap_8:
6265   case Builtin::BI__sync_val_compare_and_swap_16:
6266     BuiltinIndex = 12;
6267     NumFixed = 2;
6268     break;
6269 
6270   case Builtin::BI__sync_bool_compare_and_swap:
6271   case Builtin::BI__sync_bool_compare_and_swap_1:
6272   case Builtin::BI__sync_bool_compare_and_swap_2:
6273   case Builtin::BI__sync_bool_compare_and_swap_4:
6274   case Builtin::BI__sync_bool_compare_and_swap_8:
6275   case Builtin::BI__sync_bool_compare_and_swap_16:
6276     BuiltinIndex = 13;
6277     NumFixed = 2;
6278     ResultType = Context.BoolTy;
6279     break;
6280 
6281   case Builtin::BI__sync_lock_test_and_set:
6282   case Builtin::BI__sync_lock_test_and_set_1:
6283   case Builtin::BI__sync_lock_test_and_set_2:
6284   case Builtin::BI__sync_lock_test_and_set_4:
6285   case Builtin::BI__sync_lock_test_and_set_8:
6286   case Builtin::BI__sync_lock_test_and_set_16:
6287     BuiltinIndex = 14;
6288     break;
6289 
6290   case Builtin::BI__sync_lock_release:
6291   case Builtin::BI__sync_lock_release_1:
6292   case Builtin::BI__sync_lock_release_2:
6293   case Builtin::BI__sync_lock_release_4:
6294   case Builtin::BI__sync_lock_release_8:
6295   case Builtin::BI__sync_lock_release_16:
6296     BuiltinIndex = 15;
6297     NumFixed = 0;
6298     ResultType = Context.VoidTy;
6299     break;
6300 
6301   case Builtin::BI__sync_swap:
6302   case Builtin::BI__sync_swap_1:
6303   case Builtin::BI__sync_swap_2:
6304   case Builtin::BI__sync_swap_4:
6305   case Builtin::BI__sync_swap_8:
6306   case Builtin::BI__sync_swap_16:
6307     BuiltinIndex = 16;
6308     break;
6309   }
6310 
6311   // Now that we know how many fixed arguments we expect, first check that we
6312   // have at least that many.
6313   if (TheCall->getNumArgs() < 1+NumFixed) {
6314     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6315         << 0 << 1 + NumFixed << TheCall->getNumArgs()
6316         << Callee->getSourceRange();
6317     return ExprError();
6318   }
6319 
6320   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6321       << Callee->getSourceRange();
6322 
6323   if (WarnAboutSemanticsChange) {
6324     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6325         << Callee->getSourceRange();
6326   }
6327 
6328   // Get the decl for the concrete builtin from this, we can tell what the
6329   // concrete integer type we should convert to is.
6330   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6331   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6332   FunctionDecl *NewBuiltinDecl;
6333   if (NewBuiltinID == BuiltinID)
6334     NewBuiltinDecl = FDecl;
6335   else {
6336     // Perform builtin lookup to avoid redeclaring it.
6337     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6338     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6339     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6340     assert(Res.getFoundDecl());
6341     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6342     if (!NewBuiltinDecl)
6343       return ExprError();
6344   }
6345 
6346   // The first argument --- the pointer --- has a fixed type; we
6347   // deduce the types of the rest of the arguments accordingly.  Walk
6348   // the remaining arguments, converting them to the deduced value type.
6349   for (unsigned i = 0; i != NumFixed; ++i) {
6350     ExprResult Arg = TheCall->getArg(i+1);
6351 
6352     // GCC does an implicit conversion to the pointer or integer ValType.  This
6353     // can fail in some cases (1i -> int**), check for this error case now.
6354     // Initialize the argument.
6355     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6356                                                    ValType, /*consume*/ false);
6357     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6358     if (Arg.isInvalid())
6359       return ExprError();
6360 
6361     // Okay, we have something that *can* be converted to the right type.  Check
6362     // to see if there is a potentially weird extension going on here.  This can
6363     // happen when you do an atomic operation on something like an char* and
6364     // pass in 42.  The 42 gets converted to char.  This is even more strange
6365     // for things like 45.123 -> char, etc.
6366     // FIXME: Do this check.
6367     TheCall->setArg(i+1, Arg.get());
6368   }
6369 
6370   // Create a new DeclRefExpr to refer to the new decl.
6371   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6372       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6373       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6374       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6375 
6376   // Set the callee in the CallExpr.
6377   // FIXME: This loses syntactic information.
6378   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6379   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6380                                               CK_BuiltinFnToFnPtr);
6381   TheCall->setCallee(PromotedCall.get());
6382 
6383   // Change the result type of the call to match the original value type. This
6384   // is arbitrary, but the codegen for these builtins ins design to handle it
6385   // gracefully.
6386   TheCall->setType(ResultType);
6387 
6388   // Prohibit problematic uses of bit-precise integer types with atomic
6389   // builtins. The arguments would have already been converted to the first
6390   // argument's type, so only need to check the first argument.
6391   const auto *BitIntValType = ValType->getAs<BitIntType>();
6392   if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
6393     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6394     return ExprError();
6395   }
6396 
6397   return TheCallResult;
6398 }
6399 
6400 /// SemaBuiltinNontemporalOverloaded - We have a call to
6401 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6402 /// overloaded function based on the pointer type of its last argument.
6403 ///
6404 /// This function goes through and does final semantic checking for these
6405 /// builtins.
6406 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6407   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6408   DeclRefExpr *DRE =
6409       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6410   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6411   unsigned BuiltinID = FDecl->getBuiltinID();
6412   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6413           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6414          "Unexpected nontemporal load/store builtin!");
6415   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6416   unsigned numArgs = isStore ? 2 : 1;
6417 
6418   // Ensure that we have the proper number of arguments.
6419   if (checkArgCount(*this, TheCall, numArgs))
6420     return ExprError();
6421 
6422   // Inspect the last argument of the nontemporal builtin.  This should always
6423   // be a pointer type, from which we imply the type of the memory access.
6424   // Because it is a pointer type, we don't have to worry about any implicit
6425   // casts here.
6426   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6427   ExprResult PointerArgResult =
6428       DefaultFunctionArrayLvalueConversion(PointerArg);
6429 
6430   if (PointerArgResult.isInvalid())
6431     return ExprError();
6432   PointerArg = PointerArgResult.get();
6433   TheCall->setArg(numArgs - 1, PointerArg);
6434 
6435   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6436   if (!pointerType) {
6437     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6438         << PointerArg->getType() << PointerArg->getSourceRange();
6439     return ExprError();
6440   }
6441 
6442   QualType ValType = pointerType->getPointeeType();
6443 
6444   // Strip any qualifiers off ValType.
6445   ValType = ValType.getUnqualifiedType();
6446   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6447       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6448       !ValType->isVectorType()) {
6449     Diag(DRE->getBeginLoc(),
6450          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6451         << PointerArg->getType() << PointerArg->getSourceRange();
6452     return ExprError();
6453   }
6454 
6455   if (!isStore) {
6456     TheCall->setType(ValType);
6457     return TheCallResult;
6458   }
6459 
6460   ExprResult ValArg = TheCall->getArg(0);
6461   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6462       Context, ValType, /*consume*/ false);
6463   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6464   if (ValArg.isInvalid())
6465     return ExprError();
6466 
6467   TheCall->setArg(0, ValArg.get());
6468   TheCall->setType(Context.VoidTy);
6469   return TheCallResult;
6470 }
6471 
6472 /// CheckObjCString - Checks that the argument to the builtin
6473 /// CFString constructor is correct
6474 /// Note: It might also make sense to do the UTF-16 conversion here (would
6475 /// simplify the backend).
6476 bool Sema::CheckObjCString(Expr *Arg) {
6477   Arg = Arg->IgnoreParenCasts();
6478   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6479 
6480   if (!Literal || !Literal->isAscii()) {
6481     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6482         << Arg->getSourceRange();
6483     return true;
6484   }
6485 
6486   if (Literal->containsNonAsciiOrNull()) {
6487     StringRef String = Literal->getString();
6488     unsigned NumBytes = String.size();
6489     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6490     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6491     llvm::UTF16 *ToPtr = &ToBuf[0];
6492 
6493     llvm::ConversionResult Result =
6494         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6495                                  ToPtr + NumBytes, llvm::strictConversion);
6496     // Check for conversion failure.
6497     if (Result != llvm::conversionOK)
6498       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6499           << Arg->getSourceRange();
6500   }
6501   return false;
6502 }
6503 
6504 /// CheckObjCString - Checks that the format string argument to the os_log()
6505 /// and os_trace() functions is correct, and converts it to const char *.
6506 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6507   Arg = Arg->IgnoreParenCasts();
6508   auto *Literal = dyn_cast<StringLiteral>(Arg);
6509   if (!Literal) {
6510     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6511       Literal = ObjcLiteral->getString();
6512     }
6513   }
6514 
6515   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6516     return ExprError(
6517         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6518         << Arg->getSourceRange());
6519   }
6520 
6521   ExprResult Result(Literal);
6522   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6523   InitializedEntity Entity =
6524       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6525   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6526   return Result;
6527 }
6528 
6529 /// Check that the user is calling the appropriate va_start builtin for the
6530 /// target and calling convention.
6531 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6532   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6533   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6534   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6535                     TT.getArch() == llvm::Triple::aarch64_32);
6536   bool IsWindows = TT.isOSWindows();
6537   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6538   if (IsX64 || IsAArch64) {
6539     CallingConv CC = CC_C;
6540     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6541       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6542     if (IsMSVAStart) {
6543       // Don't allow this in System V ABI functions.
6544       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6545         return S.Diag(Fn->getBeginLoc(),
6546                       diag::err_ms_va_start_used_in_sysv_function);
6547     } else {
6548       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6549       // On x64 Windows, don't allow this in System V ABI functions.
6550       // (Yes, that means there's no corresponding way to support variadic
6551       // System V ABI functions on Windows.)
6552       if ((IsWindows && CC == CC_X86_64SysV) ||
6553           (!IsWindows && CC == CC_Win64))
6554         return S.Diag(Fn->getBeginLoc(),
6555                       diag::err_va_start_used_in_wrong_abi_function)
6556                << !IsWindows;
6557     }
6558     return false;
6559   }
6560 
6561   if (IsMSVAStart)
6562     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6563   return false;
6564 }
6565 
6566 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6567                                              ParmVarDecl **LastParam = nullptr) {
6568   // Determine whether the current function, block, or obj-c method is variadic
6569   // and get its parameter list.
6570   bool IsVariadic = false;
6571   ArrayRef<ParmVarDecl *> Params;
6572   DeclContext *Caller = S.CurContext;
6573   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6574     IsVariadic = Block->isVariadic();
6575     Params = Block->parameters();
6576   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6577     IsVariadic = FD->isVariadic();
6578     Params = FD->parameters();
6579   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6580     IsVariadic = MD->isVariadic();
6581     // FIXME: This isn't correct for methods (results in bogus warning).
6582     Params = MD->parameters();
6583   } else if (isa<CapturedDecl>(Caller)) {
6584     // We don't support va_start in a CapturedDecl.
6585     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6586     return true;
6587   } else {
6588     // This must be some other declcontext that parses exprs.
6589     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6590     return true;
6591   }
6592 
6593   if (!IsVariadic) {
6594     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6595     return true;
6596   }
6597 
6598   if (LastParam)
6599     *LastParam = Params.empty() ? nullptr : Params.back();
6600 
6601   return false;
6602 }
6603 
6604 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6605 /// for validity.  Emit an error and return true on failure; return false
6606 /// on success.
6607 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6608   Expr *Fn = TheCall->getCallee();
6609 
6610   if (checkVAStartABI(*this, BuiltinID, Fn))
6611     return true;
6612 
6613   if (checkArgCount(*this, TheCall, 2))
6614     return true;
6615 
6616   // Type-check the first argument normally.
6617   if (checkBuiltinArgument(*this, TheCall, 0))
6618     return true;
6619 
6620   // Check that the current function is variadic, and get its last parameter.
6621   ParmVarDecl *LastParam;
6622   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6623     return true;
6624 
6625   // Verify that the second argument to the builtin is the last argument of the
6626   // current function or method.
6627   bool SecondArgIsLastNamedArgument = false;
6628   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6629 
6630   // These are valid if SecondArgIsLastNamedArgument is false after the next
6631   // block.
6632   QualType Type;
6633   SourceLocation ParamLoc;
6634   bool IsCRegister = false;
6635 
6636   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6637     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6638       SecondArgIsLastNamedArgument = PV == LastParam;
6639 
6640       Type = PV->getType();
6641       ParamLoc = PV->getLocation();
6642       IsCRegister =
6643           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6644     }
6645   }
6646 
6647   if (!SecondArgIsLastNamedArgument)
6648     Diag(TheCall->getArg(1)->getBeginLoc(),
6649          diag::warn_second_arg_of_va_start_not_last_named_param);
6650   else if (IsCRegister || Type->isReferenceType() ||
6651            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6652              // Promotable integers are UB, but enumerations need a bit of
6653              // extra checking to see what their promotable type actually is.
6654              if (!Type->isPromotableIntegerType())
6655                return false;
6656              if (!Type->isEnumeralType())
6657                return true;
6658              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6659              return !(ED &&
6660                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6661            }()) {
6662     unsigned Reason = 0;
6663     if (Type->isReferenceType())  Reason = 1;
6664     else if (IsCRegister)         Reason = 2;
6665     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6666     Diag(ParamLoc, diag::note_parameter_type) << Type;
6667   }
6668 
6669   TheCall->setType(Context.VoidTy);
6670   return false;
6671 }
6672 
6673 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6674   auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6675     const LangOptions &LO = getLangOpts();
6676 
6677     if (LO.CPlusPlus)
6678       return Arg->getType()
6679                  .getCanonicalType()
6680                  .getTypePtr()
6681                  ->getPointeeType()
6682                  .withoutLocalFastQualifiers() == Context.CharTy;
6683 
6684     // In C, allow aliasing through `char *`, this is required for AArch64 at
6685     // least.
6686     return true;
6687   };
6688 
6689   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6690   //                 const char *named_addr);
6691 
6692   Expr *Func = Call->getCallee();
6693 
6694   if (Call->getNumArgs() < 3)
6695     return Diag(Call->getEndLoc(),
6696                 diag::err_typecheck_call_too_few_args_at_least)
6697            << 0 /*function call*/ << 3 << Call->getNumArgs();
6698 
6699   // Type-check the first argument normally.
6700   if (checkBuiltinArgument(*this, Call, 0))
6701     return true;
6702 
6703   // Check that the current function is variadic.
6704   if (checkVAStartIsInVariadicFunction(*this, Func))
6705     return true;
6706 
6707   // __va_start on Windows does not validate the parameter qualifiers
6708 
6709   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6710   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6711 
6712   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6713   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6714 
6715   const QualType &ConstCharPtrTy =
6716       Context.getPointerType(Context.CharTy.withConst());
6717   if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6718     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6719         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6720         << 0                                      /* qualifier difference */
6721         << 3                                      /* parameter mismatch */
6722         << 2 << Arg1->getType() << ConstCharPtrTy;
6723 
6724   const QualType SizeTy = Context.getSizeType();
6725   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6726     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6727         << Arg2->getType() << SizeTy << 1 /* different class */
6728         << 0                              /* qualifier difference */
6729         << 3                              /* parameter mismatch */
6730         << 3 << Arg2->getType() << SizeTy;
6731 
6732   return false;
6733 }
6734 
6735 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6736 /// friends.  This is declared to take (...), so we have to check everything.
6737 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6738   if (checkArgCount(*this, TheCall, 2))
6739     return true;
6740 
6741   ExprResult OrigArg0 = TheCall->getArg(0);
6742   ExprResult OrigArg1 = TheCall->getArg(1);
6743 
6744   // Do standard promotions between the two arguments, returning their common
6745   // type.
6746   QualType Res = UsualArithmeticConversions(
6747       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6748   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6749     return true;
6750 
6751   // Make sure any conversions are pushed back into the call; this is
6752   // type safe since unordered compare builtins are declared as "_Bool
6753   // foo(...)".
6754   TheCall->setArg(0, OrigArg0.get());
6755   TheCall->setArg(1, OrigArg1.get());
6756 
6757   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6758     return false;
6759 
6760   // If the common type isn't a real floating type, then the arguments were
6761   // invalid for this operation.
6762   if (Res.isNull() || !Res->isRealFloatingType())
6763     return Diag(OrigArg0.get()->getBeginLoc(),
6764                 diag::err_typecheck_call_invalid_ordered_compare)
6765            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6766            << SourceRange(OrigArg0.get()->getBeginLoc(),
6767                           OrigArg1.get()->getEndLoc());
6768 
6769   return false;
6770 }
6771 
6772 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6773 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6774 /// to check everything. We expect the last argument to be a floating point
6775 /// value.
6776 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6777   if (checkArgCount(*this, TheCall, NumArgs))
6778     return true;
6779 
6780   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6781   // on all preceding parameters just being int.  Try all of those.
6782   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6783     Expr *Arg = TheCall->getArg(i);
6784 
6785     if (Arg->isTypeDependent())
6786       return false;
6787 
6788     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6789 
6790     if (Res.isInvalid())
6791       return true;
6792     TheCall->setArg(i, Res.get());
6793   }
6794 
6795   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6796 
6797   if (OrigArg->isTypeDependent())
6798     return false;
6799 
6800   // Usual Unary Conversions will convert half to float, which we want for
6801   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6802   // type how it is, but do normal L->Rvalue conversions.
6803   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6804     OrigArg = UsualUnaryConversions(OrigArg).get();
6805   else
6806     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6807   TheCall->setArg(NumArgs - 1, OrigArg);
6808 
6809   // This operation requires a non-_Complex floating-point number.
6810   if (!OrigArg->getType()->isRealFloatingType())
6811     return Diag(OrigArg->getBeginLoc(),
6812                 diag::err_typecheck_call_invalid_unary_fp)
6813            << OrigArg->getType() << OrigArg->getSourceRange();
6814 
6815   return false;
6816 }
6817 
6818 /// Perform semantic analysis for a call to __builtin_complex.
6819 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6820   if (checkArgCount(*this, TheCall, 2))
6821     return true;
6822 
6823   bool Dependent = false;
6824   for (unsigned I = 0; I != 2; ++I) {
6825     Expr *Arg = TheCall->getArg(I);
6826     QualType T = Arg->getType();
6827     if (T->isDependentType()) {
6828       Dependent = true;
6829       continue;
6830     }
6831 
6832     // Despite supporting _Complex int, GCC requires a real floating point type
6833     // for the operands of __builtin_complex.
6834     if (!T->isRealFloatingType()) {
6835       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6836              << Arg->getType() << Arg->getSourceRange();
6837     }
6838 
6839     ExprResult Converted = DefaultLvalueConversion(Arg);
6840     if (Converted.isInvalid())
6841       return true;
6842     TheCall->setArg(I, Converted.get());
6843   }
6844 
6845   if (Dependent) {
6846     TheCall->setType(Context.DependentTy);
6847     return false;
6848   }
6849 
6850   Expr *Real = TheCall->getArg(0);
6851   Expr *Imag = TheCall->getArg(1);
6852   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6853     return Diag(Real->getBeginLoc(),
6854                 diag::err_typecheck_call_different_arg_types)
6855            << Real->getType() << Imag->getType()
6856            << Real->getSourceRange() << Imag->getSourceRange();
6857   }
6858 
6859   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6860   // don't allow this builtin to form those types either.
6861   // FIXME: Should we allow these types?
6862   if (Real->getType()->isFloat16Type())
6863     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6864            << "_Float16";
6865   if (Real->getType()->isHalfType())
6866     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6867            << "half";
6868 
6869   TheCall->setType(Context.getComplexType(Real->getType()));
6870   return false;
6871 }
6872 
6873 // Customized Sema Checking for VSX builtins that have the following signature:
6874 // vector [...] builtinName(vector [...], vector [...], const int);
6875 // Which takes the same type of vectors (any legal vector type) for the first
6876 // two arguments and takes compile time constant for the third argument.
6877 // Example builtins are :
6878 // vector double vec_xxpermdi(vector double, vector double, int);
6879 // vector short vec_xxsldwi(vector short, vector short, int);
6880 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6881   unsigned ExpectedNumArgs = 3;
6882   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6883     return true;
6884 
6885   // Check the third argument is a compile time constant
6886   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6887     return Diag(TheCall->getBeginLoc(),
6888                 diag::err_vsx_builtin_nonconstant_argument)
6889            << 3 /* argument index */ << TheCall->getDirectCallee()
6890            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6891                           TheCall->getArg(2)->getEndLoc());
6892 
6893   QualType Arg1Ty = TheCall->getArg(0)->getType();
6894   QualType Arg2Ty = TheCall->getArg(1)->getType();
6895 
6896   // Check the type of argument 1 and argument 2 are vectors.
6897   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6898   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6899       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6900     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6901            << TheCall->getDirectCallee()
6902            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6903                           TheCall->getArg(1)->getEndLoc());
6904   }
6905 
6906   // Check the first two arguments are the same type.
6907   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6908     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6909            << TheCall->getDirectCallee()
6910            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6911                           TheCall->getArg(1)->getEndLoc());
6912   }
6913 
6914   // When default clang type checking is turned off and the customized type
6915   // checking is used, the returning type of the function must be explicitly
6916   // set. Otherwise it is _Bool by default.
6917   TheCall->setType(Arg1Ty);
6918 
6919   return false;
6920 }
6921 
6922 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6923 // This is declared to take (...), so we have to check everything.
6924 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6925   if (TheCall->getNumArgs() < 2)
6926     return ExprError(Diag(TheCall->getEndLoc(),
6927                           diag::err_typecheck_call_too_few_args_at_least)
6928                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6929                      << TheCall->getSourceRange());
6930 
6931   // Determine which of the following types of shufflevector we're checking:
6932   // 1) unary, vector mask: (lhs, mask)
6933   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6934   QualType resType = TheCall->getArg(0)->getType();
6935   unsigned numElements = 0;
6936 
6937   if (!TheCall->getArg(0)->isTypeDependent() &&
6938       !TheCall->getArg(1)->isTypeDependent()) {
6939     QualType LHSType = TheCall->getArg(0)->getType();
6940     QualType RHSType = TheCall->getArg(1)->getType();
6941 
6942     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6943       return ExprError(
6944           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6945           << TheCall->getDirectCallee()
6946           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6947                          TheCall->getArg(1)->getEndLoc()));
6948 
6949     numElements = LHSType->castAs<VectorType>()->getNumElements();
6950     unsigned numResElements = TheCall->getNumArgs() - 2;
6951 
6952     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6953     // with mask.  If so, verify that RHS is an integer vector type with the
6954     // same number of elts as lhs.
6955     if (TheCall->getNumArgs() == 2) {
6956       if (!RHSType->hasIntegerRepresentation() ||
6957           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6958         return ExprError(Diag(TheCall->getBeginLoc(),
6959                               diag::err_vec_builtin_incompatible_vector)
6960                          << TheCall->getDirectCallee()
6961                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6962                                         TheCall->getArg(1)->getEndLoc()));
6963     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6964       return ExprError(Diag(TheCall->getBeginLoc(),
6965                             diag::err_vec_builtin_incompatible_vector)
6966                        << TheCall->getDirectCallee()
6967                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6968                                       TheCall->getArg(1)->getEndLoc()));
6969     } else if (numElements != numResElements) {
6970       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6971       resType = Context.getVectorType(eltType, numResElements,
6972                                       VectorType::GenericVector);
6973     }
6974   }
6975 
6976   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6977     if (TheCall->getArg(i)->isTypeDependent() ||
6978         TheCall->getArg(i)->isValueDependent())
6979       continue;
6980 
6981     Optional<llvm::APSInt> Result;
6982     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6983       return ExprError(Diag(TheCall->getBeginLoc(),
6984                             diag::err_shufflevector_nonconstant_argument)
6985                        << TheCall->getArg(i)->getSourceRange());
6986 
6987     // Allow -1 which will be translated to undef in the IR.
6988     if (Result->isSigned() && Result->isAllOnes())
6989       continue;
6990 
6991     if (Result->getActiveBits() > 64 ||
6992         Result->getZExtValue() >= numElements * 2)
6993       return ExprError(Diag(TheCall->getBeginLoc(),
6994                             diag::err_shufflevector_argument_too_large)
6995                        << TheCall->getArg(i)->getSourceRange());
6996   }
6997 
6998   SmallVector<Expr*, 32> exprs;
6999 
7000   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
7001     exprs.push_back(TheCall->getArg(i));
7002     TheCall->setArg(i, nullptr);
7003   }
7004 
7005   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
7006                                          TheCall->getCallee()->getBeginLoc(),
7007                                          TheCall->getRParenLoc());
7008 }
7009 
7010 /// SemaConvertVectorExpr - Handle __builtin_convertvector
7011 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
7012                                        SourceLocation BuiltinLoc,
7013                                        SourceLocation RParenLoc) {
7014   ExprValueKind VK = VK_PRValue;
7015   ExprObjectKind OK = OK_Ordinary;
7016   QualType DstTy = TInfo->getType();
7017   QualType SrcTy = E->getType();
7018 
7019   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
7020     return ExprError(Diag(BuiltinLoc,
7021                           diag::err_convertvector_non_vector)
7022                      << E->getSourceRange());
7023   if (!DstTy->isVectorType() && !DstTy->isDependentType())
7024     return ExprError(Diag(BuiltinLoc,
7025                           diag::err_convertvector_non_vector_type));
7026 
7027   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
7028     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
7029     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
7030     if (SrcElts != DstElts)
7031       return ExprError(Diag(BuiltinLoc,
7032                             diag::err_convertvector_incompatible_vector)
7033                        << E->getSourceRange());
7034   }
7035 
7036   return new (Context)
7037       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
7038 }
7039 
7040 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
7041 // This is declared to take (const void*, ...) and can take two
7042 // optional constant int args.
7043 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
7044   unsigned NumArgs = TheCall->getNumArgs();
7045 
7046   if (NumArgs > 3)
7047     return Diag(TheCall->getEndLoc(),
7048                 diag::err_typecheck_call_too_many_args_at_most)
7049            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7050 
7051   // Argument 0 is checked for us and the remaining arguments must be
7052   // constant integers.
7053   for (unsigned i = 1; i != NumArgs; ++i)
7054     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
7055       return true;
7056 
7057   return false;
7058 }
7059 
7060 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
7061 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
7062   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
7063     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
7064            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7065   if (checkArgCount(*this, TheCall, 1))
7066     return true;
7067   Expr *Arg = TheCall->getArg(0);
7068   if (Arg->isInstantiationDependent())
7069     return false;
7070 
7071   QualType ArgTy = Arg->getType();
7072   if (!ArgTy->hasFloatingRepresentation())
7073     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
7074            << ArgTy;
7075   if (Arg->isLValue()) {
7076     ExprResult FirstArg = DefaultLvalueConversion(Arg);
7077     TheCall->setArg(0, FirstArg.get());
7078   }
7079   TheCall->setType(TheCall->getArg(0)->getType());
7080   return false;
7081 }
7082 
7083 /// SemaBuiltinAssume - Handle __assume (MS Extension).
7084 // __assume does not evaluate its arguments, and should warn if its argument
7085 // has side effects.
7086 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
7087   Expr *Arg = TheCall->getArg(0);
7088   if (Arg->isInstantiationDependent()) return false;
7089 
7090   if (Arg->HasSideEffects(Context))
7091     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
7092         << Arg->getSourceRange()
7093         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
7094 
7095   return false;
7096 }
7097 
7098 /// Handle __builtin_alloca_with_align. This is declared
7099 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
7100 /// than 8.
7101 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
7102   // The alignment must be a constant integer.
7103   Expr *Arg = TheCall->getArg(1);
7104 
7105   // We can't check the value of a dependent argument.
7106   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7107     if (const auto *UE =
7108             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
7109       if (UE->getKind() == UETT_AlignOf ||
7110           UE->getKind() == UETT_PreferredAlignOf)
7111         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
7112             << Arg->getSourceRange();
7113 
7114     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
7115 
7116     if (!Result.isPowerOf2())
7117       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7118              << Arg->getSourceRange();
7119 
7120     if (Result < Context.getCharWidth())
7121       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
7122              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
7123 
7124     if (Result > std::numeric_limits<int32_t>::max())
7125       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
7126              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
7127   }
7128 
7129   return false;
7130 }
7131 
7132 /// Handle __builtin_assume_aligned. This is declared
7133 /// as (const void*, size_t, ...) and can take one optional constant int arg.
7134 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
7135   unsigned NumArgs = TheCall->getNumArgs();
7136 
7137   if (NumArgs > 3)
7138     return Diag(TheCall->getEndLoc(),
7139                 diag::err_typecheck_call_too_many_args_at_most)
7140            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7141 
7142   // The alignment must be a constant integer.
7143   Expr *Arg = TheCall->getArg(1);
7144 
7145   // We can't check the value of a dependent argument.
7146   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7147     llvm::APSInt Result;
7148     if (SemaBuiltinConstantArg(TheCall, 1, Result))
7149       return true;
7150 
7151     if (!Result.isPowerOf2())
7152       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7153              << Arg->getSourceRange();
7154 
7155     if (Result > Sema::MaximumAlignment)
7156       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
7157           << Arg->getSourceRange() << Sema::MaximumAlignment;
7158   }
7159 
7160   if (NumArgs > 2) {
7161     ExprResult Arg(TheCall->getArg(2));
7162     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
7163       Context.getSizeType(), false);
7164     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7165     if (Arg.isInvalid()) return true;
7166     TheCall->setArg(2, Arg.get());
7167   }
7168 
7169   return false;
7170 }
7171 
7172 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
7173   unsigned BuiltinID =
7174       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
7175   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
7176 
7177   unsigned NumArgs = TheCall->getNumArgs();
7178   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
7179   if (NumArgs < NumRequiredArgs) {
7180     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
7181            << 0 /* function call */ << NumRequiredArgs << NumArgs
7182            << TheCall->getSourceRange();
7183   }
7184   if (NumArgs >= NumRequiredArgs + 0x100) {
7185     return Diag(TheCall->getEndLoc(),
7186                 diag::err_typecheck_call_too_many_args_at_most)
7187            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
7188            << TheCall->getSourceRange();
7189   }
7190   unsigned i = 0;
7191 
7192   // For formatting call, check buffer arg.
7193   if (!IsSizeCall) {
7194     ExprResult Arg(TheCall->getArg(i));
7195     InitializedEntity Entity = InitializedEntity::InitializeParameter(
7196         Context, Context.VoidPtrTy, false);
7197     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7198     if (Arg.isInvalid())
7199       return true;
7200     TheCall->setArg(i, Arg.get());
7201     i++;
7202   }
7203 
7204   // Check string literal arg.
7205   unsigned FormatIdx = i;
7206   {
7207     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
7208     if (Arg.isInvalid())
7209       return true;
7210     TheCall->setArg(i, Arg.get());
7211     i++;
7212   }
7213 
7214   // Make sure variadic args are scalar.
7215   unsigned FirstDataArg = i;
7216   while (i < NumArgs) {
7217     ExprResult Arg = DefaultVariadicArgumentPromotion(
7218         TheCall->getArg(i), VariadicFunction, nullptr);
7219     if (Arg.isInvalid())
7220       return true;
7221     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
7222     if (ArgSize.getQuantity() >= 0x100) {
7223       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
7224              << i << (int)ArgSize.getQuantity() << 0xff
7225              << TheCall->getSourceRange();
7226     }
7227     TheCall->setArg(i, Arg.get());
7228     i++;
7229   }
7230 
7231   // Check formatting specifiers. NOTE: We're only doing this for the non-size
7232   // call to avoid duplicate diagnostics.
7233   if (!IsSizeCall) {
7234     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
7235     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
7236     bool Success = CheckFormatArguments(
7237         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
7238         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
7239         CheckedVarArgs);
7240     if (!Success)
7241       return true;
7242   }
7243 
7244   if (IsSizeCall) {
7245     TheCall->setType(Context.getSizeType());
7246   } else {
7247     TheCall->setType(Context.VoidPtrTy);
7248   }
7249   return false;
7250 }
7251 
7252 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
7253 /// TheCall is a constant expression.
7254 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7255                                   llvm::APSInt &Result) {
7256   Expr *Arg = TheCall->getArg(ArgNum);
7257   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
7258   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
7259 
7260   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
7261 
7262   Optional<llvm::APSInt> R;
7263   if (!(R = Arg->getIntegerConstantExpr(Context)))
7264     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
7265            << FDecl->getDeclName() << Arg->getSourceRange();
7266   Result = *R;
7267   return false;
7268 }
7269 
7270 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
7271 /// TheCall is a constant expression in the range [Low, High].
7272 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
7273                                        int Low, int High, bool RangeIsError) {
7274   if (isConstantEvaluated())
7275     return false;
7276   llvm::APSInt Result;
7277 
7278   // We can't check the value of a dependent argument.
7279   Expr *Arg = TheCall->getArg(ArgNum);
7280   if (Arg->isTypeDependent() || Arg->isValueDependent())
7281     return false;
7282 
7283   // Check constant-ness first.
7284   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7285     return true;
7286 
7287   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7288     if (RangeIsError)
7289       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
7290              << toString(Result, 10) << Low << High << Arg->getSourceRange();
7291     else
7292       // Defer the warning until we know if the code will be emitted so that
7293       // dead code can ignore this.
7294       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
7295                           PDiag(diag::warn_argument_invalid_range)
7296                               << toString(Result, 10) << Low << High
7297                               << Arg->getSourceRange());
7298   }
7299 
7300   return false;
7301 }
7302 
7303 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
7304 /// TheCall is a constant expression is a multiple of Num..
7305 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
7306                                           unsigned Num) {
7307   llvm::APSInt Result;
7308 
7309   // We can't check the value of a dependent argument.
7310   Expr *Arg = TheCall->getArg(ArgNum);
7311   if (Arg->isTypeDependent() || Arg->isValueDependent())
7312     return false;
7313 
7314   // Check constant-ness first.
7315   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7316     return true;
7317 
7318   if (Result.getSExtValue() % Num != 0)
7319     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7320            << Num << Arg->getSourceRange();
7321 
7322   return false;
7323 }
7324 
7325 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7326 /// constant expression representing a power of 2.
7327 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7328   llvm::APSInt Result;
7329 
7330   // We can't check the value of a dependent argument.
7331   Expr *Arg = TheCall->getArg(ArgNum);
7332   if (Arg->isTypeDependent() || Arg->isValueDependent())
7333     return false;
7334 
7335   // Check constant-ness first.
7336   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7337     return true;
7338 
7339   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7340   // and only if x is a power of 2.
7341   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7342     return false;
7343 
7344   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7345          << Arg->getSourceRange();
7346 }
7347 
7348 static bool IsShiftedByte(llvm::APSInt Value) {
7349   if (Value.isNegative())
7350     return false;
7351 
7352   // Check if it's a shifted byte, by shifting it down
7353   while (true) {
7354     // If the value fits in the bottom byte, the check passes.
7355     if (Value < 0x100)
7356       return true;
7357 
7358     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7359     // fails.
7360     if ((Value & 0xFF) != 0)
7361       return false;
7362 
7363     // If the bottom 8 bits are all 0, but something above that is nonzero,
7364     // then shifting the value right by 8 bits won't affect whether it's a
7365     // shifted byte or not. So do that, and go round again.
7366     Value >>= 8;
7367   }
7368 }
7369 
7370 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7371 /// a constant expression representing an arbitrary byte value shifted left by
7372 /// a multiple of 8 bits.
7373 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7374                                              unsigned ArgBits) {
7375   llvm::APSInt Result;
7376 
7377   // We can't check the value of a dependent argument.
7378   Expr *Arg = TheCall->getArg(ArgNum);
7379   if (Arg->isTypeDependent() || Arg->isValueDependent())
7380     return false;
7381 
7382   // Check constant-ness first.
7383   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7384     return true;
7385 
7386   // Truncate to the given size.
7387   Result = Result.getLoBits(ArgBits);
7388   Result.setIsUnsigned(true);
7389 
7390   if (IsShiftedByte(Result))
7391     return false;
7392 
7393   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7394          << Arg->getSourceRange();
7395 }
7396 
7397 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7398 /// TheCall is a constant expression representing either a shifted byte value,
7399 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7400 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7401 /// Arm MVE intrinsics.
7402 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7403                                                    int ArgNum,
7404                                                    unsigned ArgBits) {
7405   llvm::APSInt Result;
7406 
7407   // We can't check the value of a dependent argument.
7408   Expr *Arg = TheCall->getArg(ArgNum);
7409   if (Arg->isTypeDependent() || Arg->isValueDependent())
7410     return false;
7411 
7412   // Check constant-ness first.
7413   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7414     return true;
7415 
7416   // Truncate to the given size.
7417   Result = Result.getLoBits(ArgBits);
7418   Result.setIsUnsigned(true);
7419 
7420   // Check to see if it's in either of the required forms.
7421   if (IsShiftedByte(Result) ||
7422       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7423     return false;
7424 
7425   return Diag(TheCall->getBeginLoc(),
7426               diag::err_argument_not_shifted_byte_or_xxff)
7427          << Arg->getSourceRange();
7428 }
7429 
7430 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7431 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7432   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7433     if (checkArgCount(*this, TheCall, 2))
7434       return true;
7435     Expr *Arg0 = TheCall->getArg(0);
7436     Expr *Arg1 = TheCall->getArg(1);
7437 
7438     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7439     if (FirstArg.isInvalid())
7440       return true;
7441     QualType FirstArgType = FirstArg.get()->getType();
7442     if (!FirstArgType->isAnyPointerType())
7443       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7444                << "first" << FirstArgType << Arg0->getSourceRange();
7445     TheCall->setArg(0, FirstArg.get());
7446 
7447     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7448     if (SecArg.isInvalid())
7449       return true;
7450     QualType SecArgType = SecArg.get()->getType();
7451     if (!SecArgType->isIntegerType())
7452       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7453                << "second" << SecArgType << Arg1->getSourceRange();
7454 
7455     // Derive the return type from the pointer argument.
7456     TheCall->setType(FirstArgType);
7457     return false;
7458   }
7459 
7460   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7461     if (checkArgCount(*this, TheCall, 2))
7462       return true;
7463 
7464     Expr *Arg0 = TheCall->getArg(0);
7465     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7466     if (FirstArg.isInvalid())
7467       return true;
7468     QualType FirstArgType = FirstArg.get()->getType();
7469     if (!FirstArgType->isAnyPointerType())
7470       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7471                << "first" << FirstArgType << Arg0->getSourceRange();
7472     TheCall->setArg(0, FirstArg.get());
7473 
7474     // Derive the return type from the pointer argument.
7475     TheCall->setType(FirstArgType);
7476 
7477     // Second arg must be an constant in range [0,15]
7478     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7479   }
7480 
7481   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7482     if (checkArgCount(*this, TheCall, 2))
7483       return true;
7484     Expr *Arg0 = TheCall->getArg(0);
7485     Expr *Arg1 = TheCall->getArg(1);
7486 
7487     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7488     if (FirstArg.isInvalid())
7489       return true;
7490     QualType FirstArgType = FirstArg.get()->getType();
7491     if (!FirstArgType->isAnyPointerType())
7492       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7493                << "first" << FirstArgType << Arg0->getSourceRange();
7494 
7495     QualType SecArgType = Arg1->getType();
7496     if (!SecArgType->isIntegerType())
7497       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7498                << "second" << SecArgType << Arg1->getSourceRange();
7499     TheCall->setType(Context.IntTy);
7500     return false;
7501   }
7502 
7503   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7504       BuiltinID == AArch64::BI__builtin_arm_stg) {
7505     if (checkArgCount(*this, TheCall, 1))
7506       return true;
7507     Expr *Arg0 = TheCall->getArg(0);
7508     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7509     if (FirstArg.isInvalid())
7510       return true;
7511 
7512     QualType FirstArgType = FirstArg.get()->getType();
7513     if (!FirstArgType->isAnyPointerType())
7514       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7515                << "first" << FirstArgType << Arg0->getSourceRange();
7516     TheCall->setArg(0, FirstArg.get());
7517 
7518     // Derive the return type from the pointer argument.
7519     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7520       TheCall->setType(FirstArgType);
7521     return false;
7522   }
7523 
7524   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7525     Expr *ArgA = TheCall->getArg(0);
7526     Expr *ArgB = TheCall->getArg(1);
7527 
7528     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7529     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7530 
7531     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7532       return true;
7533 
7534     QualType ArgTypeA = ArgExprA.get()->getType();
7535     QualType ArgTypeB = ArgExprB.get()->getType();
7536 
7537     auto isNull = [&] (Expr *E) -> bool {
7538       return E->isNullPointerConstant(
7539                         Context, Expr::NPC_ValueDependentIsNotNull); };
7540 
7541     // argument should be either a pointer or null
7542     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7543       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7544         << "first" << ArgTypeA << ArgA->getSourceRange();
7545 
7546     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7547       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7548         << "second" << ArgTypeB << ArgB->getSourceRange();
7549 
7550     // Ensure Pointee types are compatible
7551     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7552         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7553       QualType pointeeA = ArgTypeA->getPointeeType();
7554       QualType pointeeB = ArgTypeB->getPointeeType();
7555       if (!Context.typesAreCompatible(
7556              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7557              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7558         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7559           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7560           << ArgB->getSourceRange();
7561       }
7562     }
7563 
7564     // at least one argument should be pointer type
7565     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7566       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7567         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7568 
7569     if (isNull(ArgA)) // adopt type of the other pointer
7570       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7571 
7572     if (isNull(ArgB))
7573       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7574 
7575     TheCall->setArg(0, ArgExprA.get());
7576     TheCall->setArg(1, ArgExprB.get());
7577     TheCall->setType(Context.LongLongTy);
7578     return false;
7579   }
7580   assert(false && "Unhandled ARM MTE intrinsic");
7581   return true;
7582 }
7583 
7584 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7585 /// TheCall is an ARM/AArch64 special register string literal.
7586 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7587                                     int ArgNum, unsigned ExpectedFieldNum,
7588                                     bool AllowName) {
7589   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7590                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7591                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7592                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7593                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7594                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7595   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7596                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7597                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7598                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7599                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7600                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7601   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7602 
7603   // We can't check the value of a dependent argument.
7604   Expr *Arg = TheCall->getArg(ArgNum);
7605   if (Arg->isTypeDependent() || Arg->isValueDependent())
7606     return false;
7607 
7608   // Check if the argument is a string literal.
7609   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7610     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7611            << Arg->getSourceRange();
7612 
7613   // Check the type of special register given.
7614   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7615   SmallVector<StringRef, 6> Fields;
7616   Reg.split(Fields, ":");
7617 
7618   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7619     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7620            << Arg->getSourceRange();
7621 
7622   // If the string is the name of a register then we cannot check that it is
7623   // valid here but if the string is of one the forms described in ACLE then we
7624   // can check that the supplied fields are integers and within the valid
7625   // ranges.
7626   if (Fields.size() > 1) {
7627     bool FiveFields = Fields.size() == 5;
7628 
7629     bool ValidString = true;
7630     if (IsARMBuiltin) {
7631       ValidString &= Fields[0].startswith_insensitive("cp") ||
7632                      Fields[0].startswith_insensitive("p");
7633       if (ValidString)
7634         Fields[0] = Fields[0].drop_front(
7635             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7636 
7637       ValidString &= Fields[2].startswith_insensitive("c");
7638       if (ValidString)
7639         Fields[2] = Fields[2].drop_front(1);
7640 
7641       if (FiveFields) {
7642         ValidString &= Fields[3].startswith_insensitive("c");
7643         if (ValidString)
7644           Fields[3] = Fields[3].drop_front(1);
7645       }
7646     }
7647 
7648     SmallVector<int, 5> Ranges;
7649     if (FiveFields)
7650       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7651     else
7652       Ranges.append({15, 7, 15});
7653 
7654     for (unsigned i=0; i<Fields.size(); ++i) {
7655       int IntField;
7656       ValidString &= !Fields[i].getAsInteger(10, IntField);
7657       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7658     }
7659 
7660     if (!ValidString)
7661       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7662              << Arg->getSourceRange();
7663   } else if (IsAArch64Builtin && Fields.size() == 1) {
7664     // If the register name is one of those that appear in the condition below
7665     // and the special register builtin being used is one of the write builtins,
7666     // then we require that the argument provided for writing to the register
7667     // is an integer constant expression. This is because it will be lowered to
7668     // an MSR (immediate) instruction, so we need to know the immediate at
7669     // compile time.
7670     if (TheCall->getNumArgs() != 2)
7671       return false;
7672 
7673     std::string RegLower = Reg.lower();
7674     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7675         RegLower != "pan" && RegLower != "uao")
7676       return false;
7677 
7678     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7679   }
7680 
7681   return false;
7682 }
7683 
7684 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7685 /// Emit an error and return true on failure; return false on success.
7686 /// TypeStr is a string containing the type descriptor of the value returned by
7687 /// the builtin and the descriptors of the expected type of the arguments.
7688 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
7689                                  const char *TypeStr) {
7690 
7691   assert((TypeStr[0] != '\0') &&
7692          "Invalid types in PPC MMA builtin declaration");
7693 
7694   switch (BuiltinID) {
7695   default:
7696     // This function is called in CheckPPCBuiltinFunctionCall where the
7697     // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here
7698     // we are isolating the pair vector memop builtins that can be used with mma
7699     // off so the default case is every builtin that requires mma and paired
7700     // vector memops.
7701     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7702                          diag::err_ppc_builtin_only_on_arch, "10") ||
7703         SemaFeatureCheck(*this, TheCall, "mma",
7704                          diag::err_ppc_builtin_only_on_arch, "10"))
7705       return true;
7706     break;
7707   case PPC::BI__builtin_vsx_lxvp:
7708   case PPC::BI__builtin_vsx_stxvp:
7709   case PPC::BI__builtin_vsx_assemble_pair:
7710   case PPC::BI__builtin_vsx_disassemble_pair:
7711     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7712                          diag::err_ppc_builtin_only_on_arch, "10"))
7713       return true;
7714     break;
7715   }
7716 
7717   unsigned Mask = 0;
7718   unsigned ArgNum = 0;
7719 
7720   // The first type in TypeStr is the type of the value returned by the
7721   // builtin. So we first read that type and change the type of TheCall.
7722   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7723   TheCall->setType(type);
7724 
7725   while (*TypeStr != '\0') {
7726     Mask = 0;
7727     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7728     if (ArgNum >= TheCall->getNumArgs()) {
7729       ArgNum++;
7730       break;
7731     }
7732 
7733     Expr *Arg = TheCall->getArg(ArgNum);
7734     QualType PassedType = Arg->getType();
7735     QualType StrippedRVType = PassedType.getCanonicalType();
7736 
7737     // Strip Restrict/Volatile qualifiers.
7738     if (StrippedRVType.isRestrictQualified() ||
7739         StrippedRVType.isVolatileQualified())
7740       StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
7741 
7742     // The only case where the argument type and expected type are allowed to
7743     // mismatch is if the argument type is a non-void pointer (or array) and
7744     // expected type is a void pointer.
7745     if (StrippedRVType != ExpectedType)
7746       if (!(ExpectedType->isVoidPointerType() &&
7747             (StrippedRVType->isPointerType() || StrippedRVType->isArrayType())))
7748         return Diag(Arg->getBeginLoc(),
7749                     diag::err_typecheck_convert_incompatible)
7750                << PassedType << ExpectedType << 1 << 0 << 0;
7751 
7752     // If the value of the Mask is not 0, we have a constraint in the size of
7753     // the integer argument so here we ensure the argument is a constant that
7754     // is in the valid range.
7755     if (Mask != 0 &&
7756         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7757       return true;
7758 
7759     ArgNum++;
7760   }
7761 
7762   // In case we exited early from the previous loop, there are other types to
7763   // read from TypeStr. So we need to read them all to ensure we have the right
7764   // number of arguments in TheCall and if it is not the case, to display a
7765   // better error message.
7766   while (*TypeStr != '\0') {
7767     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7768     ArgNum++;
7769   }
7770   if (checkArgCount(*this, TheCall, ArgNum))
7771     return true;
7772 
7773   return false;
7774 }
7775 
7776 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7777 /// This checks that the target supports __builtin_longjmp and
7778 /// that val is a constant 1.
7779 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7780   if (!Context.getTargetInfo().hasSjLjLowering())
7781     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7782            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7783 
7784   Expr *Arg = TheCall->getArg(1);
7785   llvm::APSInt Result;
7786 
7787   // TODO: This is less than ideal. Overload this to take a value.
7788   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7789     return true;
7790 
7791   if (Result != 1)
7792     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7793            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7794 
7795   return false;
7796 }
7797 
7798 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7799 /// This checks that the target supports __builtin_setjmp.
7800 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7801   if (!Context.getTargetInfo().hasSjLjLowering())
7802     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7803            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7804   return false;
7805 }
7806 
7807 namespace {
7808 
7809 class UncoveredArgHandler {
7810   enum { Unknown = -1, AllCovered = -2 };
7811 
7812   signed FirstUncoveredArg = Unknown;
7813   SmallVector<const Expr *, 4> DiagnosticExprs;
7814 
7815 public:
7816   UncoveredArgHandler() = default;
7817 
7818   bool hasUncoveredArg() const {
7819     return (FirstUncoveredArg >= 0);
7820   }
7821 
7822   unsigned getUncoveredArg() const {
7823     assert(hasUncoveredArg() && "no uncovered argument");
7824     return FirstUncoveredArg;
7825   }
7826 
7827   void setAllCovered() {
7828     // A string has been found with all arguments covered, so clear out
7829     // the diagnostics.
7830     DiagnosticExprs.clear();
7831     FirstUncoveredArg = AllCovered;
7832   }
7833 
7834   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7835     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7836 
7837     // Don't update if a previous string covers all arguments.
7838     if (FirstUncoveredArg == AllCovered)
7839       return;
7840 
7841     // UncoveredArgHandler tracks the highest uncovered argument index
7842     // and with it all the strings that match this index.
7843     if (NewFirstUncoveredArg == FirstUncoveredArg)
7844       DiagnosticExprs.push_back(StrExpr);
7845     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7846       DiagnosticExprs.clear();
7847       DiagnosticExprs.push_back(StrExpr);
7848       FirstUncoveredArg = NewFirstUncoveredArg;
7849     }
7850   }
7851 
7852   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7853 };
7854 
7855 enum StringLiteralCheckType {
7856   SLCT_NotALiteral,
7857   SLCT_UncheckedLiteral,
7858   SLCT_CheckedLiteral
7859 };
7860 
7861 } // namespace
7862 
7863 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7864                                      BinaryOperatorKind BinOpKind,
7865                                      bool AddendIsRight) {
7866   unsigned BitWidth = Offset.getBitWidth();
7867   unsigned AddendBitWidth = Addend.getBitWidth();
7868   // There might be negative interim results.
7869   if (Addend.isUnsigned()) {
7870     Addend = Addend.zext(++AddendBitWidth);
7871     Addend.setIsSigned(true);
7872   }
7873   // Adjust the bit width of the APSInts.
7874   if (AddendBitWidth > BitWidth) {
7875     Offset = Offset.sext(AddendBitWidth);
7876     BitWidth = AddendBitWidth;
7877   } else if (BitWidth > AddendBitWidth) {
7878     Addend = Addend.sext(BitWidth);
7879   }
7880 
7881   bool Ov = false;
7882   llvm::APSInt ResOffset = Offset;
7883   if (BinOpKind == BO_Add)
7884     ResOffset = Offset.sadd_ov(Addend, Ov);
7885   else {
7886     assert(AddendIsRight && BinOpKind == BO_Sub &&
7887            "operator must be add or sub with addend on the right");
7888     ResOffset = Offset.ssub_ov(Addend, Ov);
7889   }
7890 
7891   // We add an offset to a pointer here so we should support an offset as big as
7892   // possible.
7893   if (Ov) {
7894     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7895            "index (intermediate) result too big");
7896     Offset = Offset.sext(2 * BitWidth);
7897     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7898     return;
7899   }
7900 
7901   Offset = ResOffset;
7902 }
7903 
7904 namespace {
7905 
7906 // This is a wrapper class around StringLiteral to support offsetted string
7907 // literals as format strings. It takes the offset into account when returning
7908 // the string and its length or the source locations to display notes correctly.
7909 class FormatStringLiteral {
7910   const StringLiteral *FExpr;
7911   int64_t Offset;
7912 
7913  public:
7914   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7915       : FExpr(fexpr), Offset(Offset) {}
7916 
7917   StringRef getString() const {
7918     return FExpr->getString().drop_front(Offset);
7919   }
7920 
7921   unsigned getByteLength() const {
7922     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7923   }
7924 
7925   unsigned getLength() const { return FExpr->getLength() - Offset; }
7926   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7927 
7928   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7929 
7930   QualType getType() const { return FExpr->getType(); }
7931 
7932   bool isAscii() const { return FExpr->isAscii(); }
7933   bool isWide() const { return FExpr->isWide(); }
7934   bool isUTF8() const { return FExpr->isUTF8(); }
7935   bool isUTF16() const { return FExpr->isUTF16(); }
7936   bool isUTF32() const { return FExpr->isUTF32(); }
7937   bool isPascal() const { return FExpr->isPascal(); }
7938 
7939   SourceLocation getLocationOfByte(
7940       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7941       const TargetInfo &Target, unsigned *StartToken = nullptr,
7942       unsigned *StartTokenByteOffset = nullptr) const {
7943     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7944                                     StartToken, StartTokenByteOffset);
7945   }
7946 
7947   SourceLocation getBeginLoc() const LLVM_READONLY {
7948     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7949   }
7950 
7951   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7952 };
7953 
7954 }  // namespace
7955 
7956 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7957                               const Expr *OrigFormatExpr,
7958                               ArrayRef<const Expr *> Args,
7959                               bool HasVAListArg, unsigned format_idx,
7960                               unsigned firstDataArg,
7961                               Sema::FormatStringType Type,
7962                               bool inFunctionCall,
7963                               Sema::VariadicCallType CallType,
7964                               llvm::SmallBitVector &CheckedVarArgs,
7965                               UncoveredArgHandler &UncoveredArg,
7966                               bool IgnoreStringsWithoutSpecifiers);
7967 
7968 // Determine if an expression is a string literal or constant string.
7969 // If this function returns false on the arguments to a function expecting a
7970 // format string, we will usually need to emit a warning.
7971 // True string literals are then checked by CheckFormatString.
7972 static StringLiteralCheckType
7973 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7974                       bool HasVAListArg, unsigned format_idx,
7975                       unsigned firstDataArg, Sema::FormatStringType Type,
7976                       Sema::VariadicCallType CallType, bool InFunctionCall,
7977                       llvm::SmallBitVector &CheckedVarArgs,
7978                       UncoveredArgHandler &UncoveredArg,
7979                       llvm::APSInt Offset,
7980                       bool IgnoreStringsWithoutSpecifiers = false) {
7981   if (S.isConstantEvaluated())
7982     return SLCT_NotALiteral;
7983  tryAgain:
7984   assert(Offset.isSigned() && "invalid offset");
7985 
7986   if (E->isTypeDependent() || E->isValueDependent())
7987     return SLCT_NotALiteral;
7988 
7989   E = E->IgnoreParenCasts();
7990 
7991   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7992     // Technically -Wformat-nonliteral does not warn about this case.
7993     // The behavior of printf and friends in this case is implementation
7994     // dependent.  Ideally if the format string cannot be null then
7995     // it should have a 'nonnull' attribute in the function prototype.
7996     return SLCT_UncheckedLiteral;
7997 
7998   switch (E->getStmtClass()) {
7999   case Stmt::BinaryConditionalOperatorClass:
8000   case Stmt::ConditionalOperatorClass: {
8001     // The expression is a literal if both sub-expressions were, and it was
8002     // completely checked only if both sub-expressions were checked.
8003     const AbstractConditionalOperator *C =
8004         cast<AbstractConditionalOperator>(E);
8005 
8006     // Determine whether it is necessary to check both sub-expressions, for
8007     // example, because the condition expression is a constant that can be
8008     // evaluated at compile time.
8009     bool CheckLeft = true, CheckRight = true;
8010 
8011     bool Cond;
8012     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
8013                                                  S.isConstantEvaluated())) {
8014       if (Cond)
8015         CheckRight = false;
8016       else
8017         CheckLeft = false;
8018     }
8019 
8020     // We need to maintain the offsets for the right and the left hand side
8021     // separately to check if every possible indexed expression is a valid
8022     // string literal. They might have different offsets for different string
8023     // literals in the end.
8024     StringLiteralCheckType Left;
8025     if (!CheckLeft)
8026       Left = SLCT_UncheckedLiteral;
8027     else {
8028       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
8029                                    HasVAListArg, format_idx, firstDataArg,
8030                                    Type, CallType, InFunctionCall,
8031                                    CheckedVarArgs, UncoveredArg, Offset,
8032                                    IgnoreStringsWithoutSpecifiers);
8033       if (Left == SLCT_NotALiteral || !CheckRight) {
8034         return Left;
8035       }
8036     }
8037 
8038     StringLiteralCheckType Right = checkFormatStringExpr(
8039         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
8040         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8041         IgnoreStringsWithoutSpecifiers);
8042 
8043     return (CheckLeft && Left < Right) ? Left : Right;
8044   }
8045 
8046   case Stmt::ImplicitCastExprClass:
8047     E = cast<ImplicitCastExpr>(E)->getSubExpr();
8048     goto tryAgain;
8049 
8050   case Stmt::OpaqueValueExprClass:
8051     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
8052       E = src;
8053       goto tryAgain;
8054     }
8055     return SLCT_NotALiteral;
8056 
8057   case Stmt::PredefinedExprClass:
8058     // While __func__, etc., are technically not string literals, they
8059     // cannot contain format specifiers and thus are not a security
8060     // liability.
8061     return SLCT_UncheckedLiteral;
8062 
8063   case Stmt::DeclRefExprClass: {
8064     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8065 
8066     // As an exception, do not flag errors for variables binding to
8067     // const string literals.
8068     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
8069       bool isConstant = false;
8070       QualType T = DR->getType();
8071 
8072       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
8073         isConstant = AT->getElementType().isConstant(S.Context);
8074       } else if (const PointerType *PT = T->getAs<PointerType>()) {
8075         isConstant = T.isConstant(S.Context) &&
8076                      PT->getPointeeType().isConstant(S.Context);
8077       } else if (T->isObjCObjectPointerType()) {
8078         // In ObjC, there is usually no "const ObjectPointer" type,
8079         // so don't check if the pointee type is constant.
8080         isConstant = T.isConstant(S.Context);
8081       }
8082 
8083       if (isConstant) {
8084         if (const Expr *Init = VD->getAnyInitializer()) {
8085           // Look through initializers like const char c[] = { "foo" }
8086           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
8087             if (InitList->isStringLiteralInit())
8088               Init = InitList->getInit(0)->IgnoreParenImpCasts();
8089           }
8090           return checkFormatStringExpr(S, Init, Args,
8091                                        HasVAListArg, format_idx,
8092                                        firstDataArg, Type, CallType,
8093                                        /*InFunctionCall*/ false, CheckedVarArgs,
8094                                        UncoveredArg, Offset);
8095         }
8096       }
8097 
8098       // For vprintf* functions (i.e., HasVAListArg==true), we add a
8099       // special check to see if the format string is a function parameter
8100       // of the function calling the printf function.  If the function
8101       // has an attribute indicating it is a printf-like function, then we
8102       // should suppress warnings concerning non-literals being used in a call
8103       // to a vprintf function.  For example:
8104       //
8105       // void
8106       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
8107       //      va_list ap;
8108       //      va_start(ap, fmt);
8109       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
8110       //      ...
8111       // }
8112       if (HasVAListArg) {
8113         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
8114           if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) {
8115             int PVIndex = PV->getFunctionScopeIndex() + 1;
8116             for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
8117               // adjust for implicit parameter
8118               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
8119                 if (MD->isInstance())
8120                   ++PVIndex;
8121               // We also check if the formats are compatible.
8122               // We can't pass a 'scanf' string to a 'printf' function.
8123               if (PVIndex == PVFormat->getFormatIdx() &&
8124                   Type == S.GetFormatStringType(PVFormat))
8125                 return SLCT_UncheckedLiteral;
8126             }
8127           }
8128         }
8129       }
8130     }
8131 
8132     return SLCT_NotALiteral;
8133   }
8134 
8135   case Stmt::CallExprClass:
8136   case Stmt::CXXMemberCallExprClass: {
8137     const CallExpr *CE = cast<CallExpr>(E);
8138     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
8139       bool IsFirst = true;
8140       StringLiteralCheckType CommonResult;
8141       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
8142         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
8143         StringLiteralCheckType Result = checkFormatStringExpr(
8144             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8145             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8146             IgnoreStringsWithoutSpecifiers);
8147         if (IsFirst) {
8148           CommonResult = Result;
8149           IsFirst = false;
8150         }
8151       }
8152       if (!IsFirst)
8153         return CommonResult;
8154 
8155       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
8156         unsigned BuiltinID = FD->getBuiltinID();
8157         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
8158             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
8159           const Expr *Arg = CE->getArg(0);
8160           return checkFormatStringExpr(S, Arg, Args,
8161                                        HasVAListArg, format_idx,
8162                                        firstDataArg, Type, CallType,
8163                                        InFunctionCall, CheckedVarArgs,
8164                                        UncoveredArg, Offset,
8165                                        IgnoreStringsWithoutSpecifiers);
8166         }
8167       }
8168     }
8169 
8170     return SLCT_NotALiteral;
8171   }
8172   case Stmt::ObjCMessageExprClass: {
8173     const auto *ME = cast<ObjCMessageExpr>(E);
8174     if (const auto *MD = ME->getMethodDecl()) {
8175       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
8176         // As a special case heuristic, if we're using the method -[NSBundle
8177         // localizedStringForKey:value:table:], ignore any key strings that lack
8178         // format specifiers. The idea is that if the key doesn't have any
8179         // format specifiers then its probably just a key to map to the
8180         // localized strings. If it does have format specifiers though, then its
8181         // likely that the text of the key is the format string in the
8182         // programmer's language, and should be checked.
8183         const ObjCInterfaceDecl *IFace;
8184         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
8185             IFace->getIdentifier()->isStr("NSBundle") &&
8186             MD->getSelector().isKeywordSelector(
8187                 {"localizedStringForKey", "value", "table"})) {
8188           IgnoreStringsWithoutSpecifiers = true;
8189         }
8190 
8191         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
8192         return checkFormatStringExpr(
8193             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8194             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8195             IgnoreStringsWithoutSpecifiers);
8196       }
8197     }
8198 
8199     return SLCT_NotALiteral;
8200   }
8201   case Stmt::ObjCStringLiteralClass:
8202   case Stmt::StringLiteralClass: {
8203     const StringLiteral *StrE = nullptr;
8204 
8205     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
8206       StrE = ObjCFExpr->getString();
8207     else
8208       StrE = cast<StringLiteral>(E);
8209 
8210     if (StrE) {
8211       if (Offset.isNegative() || Offset > StrE->getLength()) {
8212         // TODO: It would be better to have an explicit warning for out of
8213         // bounds literals.
8214         return SLCT_NotALiteral;
8215       }
8216       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
8217       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
8218                         firstDataArg, Type, InFunctionCall, CallType,
8219                         CheckedVarArgs, UncoveredArg,
8220                         IgnoreStringsWithoutSpecifiers);
8221       return SLCT_CheckedLiteral;
8222     }
8223 
8224     return SLCT_NotALiteral;
8225   }
8226   case Stmt::BinaryOperatorClass: {
8227     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
8228 
8229     // A string literal + an int offset is still a string literal.
8230     if (BinOp->isAdditiveOp()) {
8231       Expr::EvalResult LResult, RResult;
8232 
8233       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
8234           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8235       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
8236           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8237 
8238       if (LIsInt != RIsInt) {
8239         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
8240 
8241         if (LIsInt) {
8242           if (BinOpKind == BO_Add) {
8243             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
8244             E = BinOp->getRHS();
8245             goto tryAgain;
8246           }
8247         } else {
8248           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
8249           E = BinOp->getLHS();
8250           goto tryAgain;
8251         }
8252       }
8253     }
8254 
8255     return SLCT_NotALiteral;
8256   }
8257   case Stmt::UnaryOperatorClass: {
8258     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
8259     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
8260     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
8261       Expr::EvalResult IndexResult;
8262       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
8263                                        Expr::SE_NoSideEffects,
8264                                        S.isConstantEvaluated())) {
8265         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
8266                    /*RHS is int*/ true);
8267         E = ASE->getBase();
8268         goto tryAgain;
8269       }
8270     }
8271 
8272     return SLCT_NotALiteral;
8273   }
8274 
8275   default:
8276     return SLCT_NotALiteral;
8277   }
8278 }
8279 
8280 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
8281   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
8282       .Case("scanf", FST_Scanf)
8283       .Cases("printf", "printf0", FST_Printf)
8284       .Cases("NSString", "CFString", FST_NSString)
8285       .Case("strftime", FST_Strftime)
8286       .Case("strfmon", FST_Strfmon)
8287       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
8288       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
8289       .Case("os_trace", FST_OSLog)
8290       .Case("os_log", FST_OSLog)
8291       .Default(FST_Unknown);
8292 }
8293 
8294 /// CheckFormatArguments - Check calls to printf and scanf (and similar
8295 /// functions) for correct use of format strings.
8296 /// Returns true if a format string has been fully checked.
8297 bool Sema::CheckFormatArguments(const FormatAttr *Format,
8298                                 ArrayRef<const Expr *> Args,
8299                                 bool IsCXXMember,
8300                                 VariadicCallType CallType,
8301                                 SourceLocation Loc, SourceRange Range,
8302                                 llvm::SmallBitVector &CheckedVarArgs) {
8303   FormatStringInfo FSI;
8304   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
8305     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
8306                                 FSI.FirstDataArg, GetFormatStringType(Format),
8307                                 CallType, Loc, Range, CheckedVarArgs);
8308   return false;
8309 }
8310 
8311 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8312                                 bool HasVAListArg, unsigned format_idx,
8313                                 unsigned firstDataArg, FormatStringType Type,
8314                                 VariadicCallType CallType,
8315                                 SourceLocation Loc, SourceRange Range,
8316                                 llvm::SmallBitVector &CheckedVarArgs) {
8317   // CHECK: printf/scanf-like function is called with no format string.
8318   if (format_idx >= Args.size()) {
8319     Diag(Loc, diag::warn_missing_format_string) << Range;
8320     return false;
8321   }
8322 
8323   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8324 
8325   // CHECK: format string is not a string literal.
8326   //
8327   // Dynamically generated format strings are difficult to
8328   // automatically vet at compile time.  Requiring that format strings
8329   // are string literals: (1) permits the checking of format strings by
8330   // the compiler and thereby (2) can practically remove the source of
8331   // many format string exploits.
8332 
8333   // Format string can be either ObjC string (e.g. @"%d") or
8334   // C string (e.g. "%d")
8335   // ObjC string uses the same format specifiers as C string, so we can use
8336   // the same format string checking logic for both ObjC and C strings.
8337   UncoveredArgHandler UncoveredArg;
8338   StringLiteralCheckType CT =
8339       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8340                             format_idx, firstDataArg, Type, CallType,
8341                             /*IsFunctionCall*/ true, CheckedVarArgs,
8342                             UncoveredArg,
8343                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8344 
8345   // Generate a diagnostic where an uncovered argument is detected.
8346   if (UncoveredArg.hasUncoveredArg()) {
8347     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8348     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8349     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8350   }
8351 
8352   if (CT != SLCT_NotALiteral)
8353     // Literal format string found, check done!
8354     return CT == SLCT_CheckedLiteral;
8355 
8356   // Strftime is particular as it always uses a single 'time' argument,
8357   // so it is safe to pass a non-literal string.
8358   if (Type == FST_Strftime)
8359     return false;
8360 
8361   // Do not emit diag when the string param is a macro expansion and the
8362   // format is either NSString or CFString. This is a hack to prevent
8363   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8364   // which are usually used in place of NS and CF string literals.
8365   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8366   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8367     return false;
8368 
8369   // If there are no arguments specified, warn with -Wformat-security, otherwise
8370   // warn only with -Wformat-nonliteral.
8371   if (Args.size() == firstDataArg) {
8372     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8373       << OrigFormatExpr->getSourceRange();
8374     switch (Type) {
8375     default:
8376       break;
8377     case FST_Kprintf:
8378     case FST_FreeBSDKPrintf:
8379     case FST_Printf:
8380       Diag(FormatLoc, diag::note_format_security_fixit)
8381         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8382       break;
8383     case FST_NSString:
8384       Diag(FormatLoc, diag::note_format_security_fixit)
8385         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8386       break;
8387     }
8388   } else {
8389     Diag(FormatLoc, diag::warn_format_nonliteral)
8390       << OrigFormatExpr->getSourceRange();
8391   }
8392   return false;
8393 }
8394 
8395 namespace {
8396 
8397 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8398 protected:
8399   Sema &S;
8400   const FormatStringLiteral *FExpr;
8401   const Expr *OrigFormatExpr;
8402   const Sema::FormatStringType FSType;
8403   const unsigned FirstDataArg;
8404   const unsigned NumDataArgs;
8405   const char *Beg; // Start of format string.
8406   const bool HasVAListArg;
8407   ArrayRef<const Expr *> Args;
8408   unsigned FormatIdx;
8409   llvm::SmallBitVector CoveredArgs;
8410   bool usesPositionalArgs = false;
8411   bool atFirstArg = true;
8412   bool inFunctionCall;
8413   Sema::VariadicCallType CallType;
8414   llvm::SmallBitVector &CheckedVarArgs;
8415   UncoveredArgHandler &UncoveredArg;
8416 
8417 public:
8418   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8419                      const Expr *origFormatExpr,
8420                      const Sema::FormatStringType type, unsigned firstDataArg,
8421                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8422                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8423                      bool inFunctionCall, Sema::VariadicCallType callType,
8424                      llvm::SmallBitVector &CheckedVarArgs,
8425                      UncoveredArgHandler &UncoveredArg)
8426       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8427         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8428         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8429         inFunctionCall(inFunctionCall), CallType(callType),
8430         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8431     CoveredArgs.resize(numDataArgs);
8432     CoveredArgs.reset();
8433   }
8434 
8435   void DoneProcessing();
8436 
8437   void HandleIncompleteSpecifier(const char *startSpecifier,
8438                                  unsigned specifierLen) override;
8439 
8440   void HandleInvalidLengthModifier(
8441                            const analyze_format_string::FormatSpecifier &FS,
8442                            const analyze_format_string::ConversionSpecifier &CS,
8443                            const char *startSpecifier, unsigned specifierLen,
8444                            unsigned DiagID);
8445 
8446   void HandleNonStandardLengthModifier(
8447                     const analyze_format_string::FormatSpecifier &FS,
8448                     const char *startSpecifier, unsigned specifierLen);
8449 
8450   void HandleNonStandardConversionSpecifier(
8451                     const analyze_format_string::ConversionSpecifier &CS,
8452                     const char *startSpecifier, unsigned specifierLen);
8453 
8454   void HandlePosition(const char *startPos, unsigned posLen) override;
8455 
8456   void HandleInvalidPosition(const char *startSpecifier,
8457                              unsigned specifierLen,
8458                              analyze_format_string::PositionContext p) override;
8459 
8460   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8461 
8462   void HandleNullChar(const char *nullCharacter) override;
8463 
8464   template <typename Range>
8465   static void
8466   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8467                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8468                        bool IsStringLocation, Range StringRange,
8469                        ArrayRef<FixItHint> Fixit = None);
8470 
8471 protected:
8472   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8473                                         const char *startSpec,
8474                                         unsigned specifierLen,
8475                                         const char *csStart, unsigned csLen);
8476 
8477   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8478                                          const char *startSpec,
8479                                          unsigned specifierLen);
8480 
8481   SourceRange getFormatStringRange();
8482   CharSourceRange getSpecifierRange(const char *startSpecifier,
8483                                     unsigned specifierLen);
8484   SourceLocation getLocationOfByte(const char *x);
8485 
8486   const Expr *getDataArg(unsigned i) const;
8487 
8488   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8489                     const analyze_format_string::ConversionSpecifier &CS,
8490                     const char *startSpecifier, unsigned specifierLen,
8491                     unsigned argIndex);
8492 
8493   template <typename Range>
8494   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8495                             bool IsStringLocation, Range StringRange,
8496                             ArrayRef<FixItHint> Fixit = None);
8497 };
8498 
8499 } // namespace
8500 
8501 SourceRange CheckFormatHandler::getFormatStringRange() {
8502   return OrigFormatExpr->getSourceRange();
8503 }
8504 
8505 CharSourceRange CheckFormatHandler::
8506 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8507   SourceLocation Start = getLocationOfByte(startSpecifier);
8508   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8509 
8510   // Advance the end SourceLocation by one due to half-open ranges.
8511   End = End.getLocWithOffset(1);
8512 
8513   return CharSourceRange::getCharRange(Start, End);
8514 }
8515 
8516 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8517   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8518                                   S.getLangOpts(), S.Context.getTargetInfo());
8519 }
8520 
8521 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8522                                                    unsigned specifierLen){
8523   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8524                        getLocationOfByte(startSpecifier),
8525                        /*IsStringLocation*/true,
8526                        getSpecifierRange(startSpecifier, specifierLen));
8527 }
8528 
8529 void CheckFormatHandler::HandleInvalidLengthModifier(
8530     const analyze_format_string::FormatSpecifier &FS,
8531     const analyze_format_string::ConversionSpecifier &CS,
8532     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8533   using namespace analyze_format_string;
8534 
8535   const LengthModifier &LM = FS.getLengthModifier();
8536   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8537 
8538   // See if we know how to fix this length modifier.
8539   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8540   if (FixedLM) {
8541     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8542                          getLocationOfByte(LM.getStart()),
8543                          /*IsStringLocation*/true,
8544                          getSpecifierRange(startSpecifier, specifierLen));
8545 
8546     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8547       << FixedLM->toString()
8548       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8549 
8550   } else {
8551     FixItHint Hint;
8552     if (DiagID == diag::warn_format_nonsensical_length)
8553       Hint = FixItHint::CreateRemoval(LMRange);
8554 
8555     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8556                          getLocationOfByte(LM.getStart()),
8557                          /*IsStringLocation*/true,
8558                          getSpecifierRange(startSpecifier, specifierLen),
8559                          Hint);
8560   }
8561 }
8562 
8563 void CheckFormatHandler::HandleNonStandardLengthModifier(
8564     const analyze_format_string::FormatSpecifier &FS,
8565     const char *startSpecifier, unsigned specifierLen) {
8566   using namespace analyze_format_string;
8567 
8568   const LengthModifier &LM = FS.getLengthModifier();
8569   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8570 
8571   // See if we know how to fix this length modifier.
8572   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8573   if (FixedLM) {
8574     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8575                            << LM.toString() << 0,
8576                          getLocationOfByte(LM.getStart()),
8577                          /*IsStringLocation*/true,
8578                          getSpecifierRange(startSpecifier, specifierLen));
8579 
8580     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8581       << FixedLM->toString()
8582       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8583 
8584   } else {
8585     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8586                            << LM.toString() << 0,
8587                          getLocationOfByte(LM.getStart()),
8588                          /*IsStringLocation*/true,
8589                          getSpecifierRange(startSpecifier, specifierLen));
8590   }
8591 }
8592 
8593 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8594     const analyze_format_string::ConversionSpecifier &CS,
8595     const char *startSpecifier, unsigned specifierLen) {
8596   using namespace analyze_format_string;
8597 
8598   // See if we know how to fix this conversion specifier.
8599   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8600   if (FixedCS) {
8601     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8602                           << CS.toString() << /*conversion specifier*/1,
8603                          getLocationOfByte(CS.getStart()),
8604                          /*IsStringLocation*/true,
8605                          getSpecifierRange(startSpecifier, specifierLen));
8606 
8607     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8608     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8609       << FixedCS->toString()
8610       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8611   } else {
8612     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8613                           << CS.toString() << /*conversion specifier*/1,
8614                          getLocationOfByte(CS.getStart()),
8615                          /*IsStringLocation*/true,
8616                          getSpecifierRange(startSpecifier, specifierLen));
8617   }
8618 }
8619 
8620 void CheckFormatHandler::HandlePosition(const char *startPos,
8621                                         unsigned posLen) {
8622   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8623                                getLocationOfByte(startPos),
8624                                /*IsStringLocation*/true,
8625                                getSpecifierRange(startPos, posLen));
8626 }
8627 
8628 void
8629 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8630                                      analyze_format_string::PositionContext p) {
8631   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8632                          << (unsigned) p,
8633                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8634                        getSpecifierRange(startPos, posLen));
8635 }
8636 
8637 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8638                                             unsigned posLen) {
8639   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8640                                getLocationOfByte(startPos),
8641                                /*IsStringLocation*/true,
8642                                getSpecifierRange(startPos, posLen));
8643 }
8644 
8645 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8646   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8647     // The presence of a null character is likely an error.
8648     EmitFormatDiagnostic(
8649       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8650       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8651       getFormatStringRange());
8652   }
8653 }
8654 
8655 // Note that this may return NULL if there was an error parsing or building
8656 // one of the argument expressions.
8657 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8658   return Args[FirstDataArg + i];
8659 }
8660 
8661 void CheckFormatHandler::DoneProcessing() {
8662   // Does the number of data arguments exceed the number of
8663   // format conversions in the format string?
8664   if (!HasVAListArg) {
8665       // Find any arguments that weren't covered.
8666     CoveredArgs.flip();
8667     signed notCoveredArg = CoveredArgs.find_first();
8668     if (notCoveredArg >= 0) {
8669       assert((unsigned)notCoveredArg < NumDataArgs);
8670       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8671     } else {
8672       UncoveredArg.setAllCovered();
8673     }
8674   }
8675 }
8676 
8677 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8678                                    const Expr *ArgExpr) {
8679   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8680          "Invalid state");
8681 
8682   if (!ArgExpr)
8683     return;
8684 
8685   SourceLocation Loc = ArgExpr->getBeginLoc();
8686 
8687   if (S.getSourceManager().isInSystemMacro(Loc))
8688     return;
8689 
8690   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8691   for (auto E : DiagnosticExprs)
8692     PDiag << E->getSourceRange();
8693 
8694   CheckFormatHandler::EmitFormatDiagnostic(
8695                                   S, IsFunctionCall, DiagnosticExprs[0],
8696                                   PDiag, Loc, /*IsStringLocation*/false,
8697                                   DiagnosticExprs[0]->getSourceRange());
8698 }
8699 
8700 bool
8701 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8702                                                      SourceLocation Loc,
8703                                                      const char *startSpec,
8704                                                      unsigned specifierLen,
8705                                                      const char *csStart,
8706                                                      unsigned csLen) {
8707   bool keepGoing = true;
8708   if (argIndex < NumDataArgs) {
8709     // Consider the argument coverered, even though the specifier doesn't
8710     // make sense.
8711     CoveredArgs.set(argIndex);
8712   }
8713   else {
8714     // If argIndex exceeds the number of data arguments we
8715     // don't issue a warning because that is just a cascade of warnings (and
8716     // they may have intended '%%' anyway). We don't want to continue processing
8717     // the format string after this point, however, as we will like just get
8718     // gibberish when trying to match arguments.
8719     keepGoing = false;
8720   }
8721 
8722   StringRef Specifier(csStart, csLen);
8723 
8724   // If the specifier in non-printable, it could be the first byte of a UTF-8
8725   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8726   // hex value.
8727   std::string CodePointStr;
8728   if (!llvm::sys::locale::isPrint(*csStart)) {
8729     llvm::UTF32 CodePoint;
8730     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8731     const llvm::UTF8 *E =
8732         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8733     llvm::ConversionResult Result =
8734         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8735 
8736     if (Result != llvm::conversionOK) {
8737       unsigned char FirstChar = *csStart;
8738       CodePoint = (llvm::UTF32)FirstChar;
8739     }
8740 
8741     llvm::raw_string_ostream OS(CodePointStr);
8742     if (CodePoint < 256)
8743       OS << "\\x" << llvm::format("%02x", CodePoint);
8744     else if (CodePoint <= 0xFFFF)
8745       OS << "\\u" << llvm::format("%04x", CodePoint);
8746     else
8747       OS << "\\U" << llvm::format("%08x", CodePoint);
8748     OS.flush();
8749     Specifier = CodePointStr;
8750   }
8751 
8752   EmitFormatDiagnostic(
8753       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8754       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8755 
8756   return keepGoing;
8757 }
8758 
8759 void
8760 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8761                                                       const char *startSpec,
8762                                                       unsigned specifierLen) {
8763   EmitFormatDiagnostic(
8764     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8765     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8766 }
8767 
8768 bool
8769 CheckFormatHandler::CheckNumArgs(
8770   const analyze_format_string::FormatSpecifier &FS,
8771   const analyze_format_string::ConversionSpecifier &CS,
8772   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8773 
8774   if (argIndex >= NumDataArgs) {
8775     PartialDiagnostic PDiag = FS.usesPositionalArg()
8776       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8777            << (argIndex+1) << NumDataArgs)
8778       : S.PDiag(diag::warn_printf_insufficient_data_args);
8779     EmitFormatDiagnostic(
8780       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8781       getSpecifierRange(startSpecifier, specifierLen));
8782 
8783     // Since more arguments than conversion tokens are given, by extension
8784     // all arguments are covered, so mark this as so.
8785     UncoveredArg.setAllCovered();
8786     return false;
8787   }
8788   return true;
8789 }
8790 
8791 template<typename Range>
8792 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8793                                               SourceLocation Loc,
8794                                               bool IsStringLocation,
8795                                               Range StringRange,
8796                                               ArrayRef<FixItHint> FixIt) {
8797   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8798                        Loc, IsStringLocation, StringRange, FixIt);
8799 }
8800 
8801 /// If the format string is not within the function call, emit a note
8802 /// so that the function call and string are in diagnostic messages.
8803 ///
8804 /// \param InFunctionCall if true, the format string is within the function
8805 /// call and only one diagnostic message will be produced.  Otherwise, an
8806 /// extra note will be emitted pointing to location of the format string.
8807 ///
8808 /// \param ArgumentExpr the expression that is passed as the format string
8809 /// argument in the function call.  Used for getting locations when two
8810 /// diagnostics are emitted.
8811 ///
8812 /// \param PDiag the callee should already have provided any strings for the
8813 /// diagnostic message.  This function only adds locations and fixits
8814 /// to diagnostics.
8815 ///
8816 /// \param Loc primary location for diagnostic.  If two diagnostics are
8817 /// required, one will be at Loc and a new SourceLocation will be created for
8818 /// the other one.
8819 ///
8820 /// \param IsStringLocation if true, Loc points to the format string should be
8821 /// used for the note.  Otherwise, Loc points to the argument list and will
8822 /// be used with PDiag.
8823 ///
8824 /// \param StringRange some or all of the string to highlight.  This is
8825 /// templated so it can accept either a CharSourceRange or a SourceRange.
8826 ///
8827 /// \param FixIt optional fix it hint for the format string.
8828 template <typename Range>
8829 void CheckFormatHandler::EmitFormatDiagnostic(
8830     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8831     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8832     Range StringRange, ArrayRef<FixItHint> FixIt) {
8833   if (InFunctionCall) {
8834     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8835     D << StringRange;
8836     D << FixIt;
8837   } else {
8838     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8839       << ArgumentExpr->getSourceRange();
8840 
8841     const Sema::SemaDiagnosticBuilder &Note =
8842       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8843              diag::note_format_string_defined);
8844 
8845     Note << StringRange;
8846     Note << FixIt;
8847   }
8848 }
8849 
8850 //===--- CHECK: Printf format string checking ------------------------------===//
8851 
8852 namespace {
8853 
8854 class CheckPrintfHandler : public CheckFormatHandler {
8855 public:
8856   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8857                      const Expr *origFormatExpr,
8858                      const Sema::FormatStringType type, unsigned firstDataArg,
8859                      unsigned numDataArgs, bool isObjC, const char *beg,
8860                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8861                      unsigned formatIdx, bool inFunctionCall,
8862                      Sema::VariadicCallType CallType,
8863                      llvm::SmallBitVector &CheckedVarArgs,
8864                      UncoveredArgHandler &UncoveredArg)
8865       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8866                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8867                            inFunctionCall, CallType, CheckedVarArgs,
8868                            UncoveredArg) {}
8869 
8870   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8871 
8872   /// Returns true if '%@' specifiers are allowed in the format string.
8873   bool allowsObjCArg() const {
8874     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8875            FSType == Sema::FST_OSTrace;
8876   }
8877 
8878   bool HandleInvalidPrintfConversionSpecifier(
8879                                       const analyze_printf::PrintfSpecifier &FS,
8880                                       const char *startSpecifier,
8881                                       unsigned specifierLen) override;
8882 
8883   void handleInvalidMaskType(StringRef MaskType) override;
8884 
8885   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8886                              const char *startSpecifier,
8887                              unsigned specifierLen) override;
8888   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8889                        const char *StartSpecifier,
8890                        unsigned SpecifierLen,
8891                        const Expr *E);
8892 
8893   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8894                     const char *startSpecifier, unsigned specifierLen);
8895   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8896                            const analyze_printf::OptionalAmount &Amt,
8897                            unsigned type,
8898                            const char *startSpecifier, unsigned specifierLen);
8899   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8900                   const analyze_printf::OptionalFlag &flag,
8901                   const char *startSpecifier, unsigned specifierLen);
8902   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8903                          const analyze_printf::OptionalFlag &ignoredFlag,
8904                          const analyze_printf::OptionalFlag &flag,
8905                          const char *startSpecifier, unsigned specifierLen);
8906   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8907                            const Expr *E);
8908 
8909   void HandleEmptyObjCModifierFlag(const char *startFlag,
8910                                    unsigned flagLen) override;
8911 
8912   void HandleInvalidObjCModifierFlag(const char *startFlag,
8913                                             unsigned flagLen) override;
8914 
8915   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8916                                            const char *flagsEnd,
8917                                            const char *conversionPosition)
8918                                              override;
8919 };
8920 
8921 } // namespace
8922 
8923 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8924                                       const analyze_printf::PrintfSpecifier &FS,
8925                                       const char *startSpecifier,
8926                                       unsigned specifierLen) {
8927   const analyze_printf::PrintfConversionSpecifier &CS =
8928     FS.getConversionSpecifier();
8929 
8930   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8931                                           getLocationOfByte(CS.getStart()),
8932                                           startSpecifier, specifierLen,
8933                                           CS.getStart(), CS.getLength());
8934 }
8935 
8936 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8937   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8938 }
8939 
8940 bool CheckPrintfHandler::HandleAmount(
8941                                const analyze_format_string::OptionalAmount &Amt,
8942                                unsigned k, const char *startSpecifier,
8943                                unsigned specifierLen) {
8944   if (Amt.hasDataArgument()) {
8945     if (!HasVAListArg) {
8946       unsigned argIndex = Amt.getArgIndex();
8947       if (argIndex >= NumDataArgs) {
8948         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8949                                << k,
8950                              getLocationOfByte(Amt.getStart()),
8951                              /*IsStringLocation*/true,
8952                              getSpecifierRange(startSpecifier, specifierLen));
8953         // Don't do any more checking.  We will just emit
8954         // spurious errors.
8955         return false;
8956       }
8957 
8958       // Type check the data argument.  It should be an 'int'.
8959       // Although not in conformance with C99, we also allow the argument to be
8960       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8961       // doesn't emit a warning for that case.
8962       CoveredArgs.set(argIndex);
8963       const Expr *Arg = getDataArg(argIndex);
8964       if (!Arg)
8965         return false;
8966 
8967       QualType T = Arg->getType();
8968 
8969       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8970       assert(AT.isValid());
8971 
8972       if (!AT.matchesType(S.Context, T)) {
8973         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8974                                << k << AT.getRepresentativeTypeName(S.Context)
8975                                << T << Arg->getSourceRange(),
8976                              getLocationOfByte(Amt.getStart()),
8977                              /*IsStringLocation*/true,
8978                              getSpecifierRange(startSpecifier, specifierLen));
8979         // Don't do any more checking.  We will just emit
8980         // spurious errors.
8981         return false;
8982       }
8983     }
8984   }
8985   return true;
8986 }
8987 
8988 void CheckPrintfHandler::HandleInvalidAmount(
8989                                       const analyze_printf::PrintfSpecifier &FS,
8990                                       const analyze_printf::OptionalAmount &Amt,
8991                                       unsigned type,
8992                                       const char *startSpecifier,
8993                                       unsigned specifierLen) {
8994   const analyze_printf::PrintfConversionSpecifier &CS =
8995     FS.getConversionSpecifier();
8996 
8997   FixItHint fixit =
8998     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8999       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
9000                                  Amt.getConstantLength()))
9001       : FixItHint();
9002 
9003   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
9004                          << type << CS.toString(),
9005                        getLocationOfByte(Amt.getStart()),
9006                        /*IsStringLocation*/true,
9007                        getSpecifierRange(startSpecifier, specifierLen),
9008                        fixit);
9009 }
9010 
9011 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
9012                                     const analyze_printf::OptionalFlag &flag,
9013                                     const char *startSpecifier,
9014                                     unsigned specifierLen) {
9015   // Warn about pointless flag with a fixit removal.
9016   const analyze_printf::PrintfConversionSpecifier &CS =
9017     FS.getConversionSpecifier();
9018   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
9019                          << flag.toString() << CS.toString(),
9020                        getLocationOfByte(flag.getPosition()),
9021                        /*IsStringLocation*/true,
9022                        getSpecifierRange(startSpecifier, specifierLen),
9023                        FixItHint::CreateRemoval(
9024                          getSpecifierRange(flag.getPosition(), 1)));
9025 }
9026 
9027 void CheckPrintfHandler::HandleIgnoredFlag(
9028                                 const analyze_printf::PrintfSpecifier &FS,
9029                                 const analyze_printf::OptionalFlag &ignoredFlag,
9030                                 const analyze_printf::OptionalFlag &flag,
9031                                 const char *startSpecifier,
9032                                 unsigned specifierLen) {
9033   // Warn about ignored flag with a fixit removal.
9034   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
9035                          << ignoredFlag.toString() << flag.toString(),
9036                        getLocationOfByte(ignoredFlag.getPosition()),
9037                        /*IsStringLocation*/true,
9038                        getSpecifierRange(startSpecifier, specifierLen),
9039                        FixItHint::CreateRemoval(
9040                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
9041 }
9042 
9043 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
9044                                                      unsigned flagLen) {
9045   // Warn about an empty flag.
9046   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
9047                        getLocationOfByte(startFlag),
9048                        /*IsStringLocation*/true,
9049                        getSpecifierRange(startFlag, flagLen));
9050 }
9051 
9052 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
9053                                                        unsigned flagLen) {
9054   // Warn about an invalid flag.
9055   auto Range = getSpecifierRange(startFlag, flagLen);
9056   StringRef flag(startFlag, flagLen);
9057   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
9058                       getLocationOfByte(startFlag),
9059                       /*IsStringLocation*/true,
9060                       Range, FixItHint::CreateRemoval(Range));
9061 }
9062 
9063 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
9064     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
9065     // Warn about using '[...]' without a '@' conversion.
9066     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
9067     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
9068     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
9069                          getLocationOfByte(conversionPosition),
9070                          /*IsStringLocation*/true,
9071                          Range, FixItHint::CreateRemoval(Range));
9072 }
9073 
9074 // Determines if the specified is a C++ class or struct containing
9075 // a member with the specified name and kind (e.g. a CXXMethodDecl named
9076 // "c_str()").
9077 template<typename MemberKind>
9078 static llvm::SmallPtrSet<MemberKind*, 1>
9079 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9080   const RecordType *RT = Ty->getAs<RecordType>();
9081   llvm::SmallPtrSet<MemberKind*, 1> Results;
9082 
9083   if (!RT)
9084     return Results;
9085   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
9086   if (!RD || !RD->getDefinition())
9087     return Results;
9088 
9089   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9090                  Sema::LookupMemberName);
9091   R.suppressDiagnostics();
9092 
9093   // We just need to include all members of the right kind turned up by the
9094   // filter, at this point.
9095   if (S.LookupQualifiedName(R, RT->getDecl()))
9096     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9097       NamedDecl *decl = (*I)->getUnderlyingDecl();
9098       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9099         Results.insert(FK);
9100     }
9101   return Results;
9102 }
9103 
9104 /// Check if we could call '.c_str()' on an object.
9105 ///
9106 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9107 /// allow the call, or if it would be ambiguous).
9108 bool Sema::hasCStrMethod(const Expr *E) {
9109   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9110 
9111   MethodSet Results =
9112       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
9113   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9114        MI != ME; ++MI)
9115     if ((*MI)->getMinRequiredArguments() == 0)
9116       return true;
9117   return false;
9118 }
9119 
9120 // Check if a (w)string was passed when a (w)char* was needed, and offer a
9121 // better diagnostic if so. AT is assumed to be valid.
9122 // Returns true when a c_str() conversion method is found.
9123 bool CheckPrintfHandler::checkForCStrMembers(
9124     const analyze_printf::ArgType &AT, const Expr *E) {
9125   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9126 
9127   MethodSet Results =
9128       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
9129 
9130   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9131        MI != ME; ++MI) {
9132     const CXXMethodDecl *Method = *MI;
9133     if (Method->getMinRequiredArguments() == 0 &&
9134         AT.matchesType(S.Context, Method->getReturnType())) {
9135       // FIXME: Suggest parens if the expression needs them.
9136       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
9137       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
9138           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
9139       return true;
9140     }
9141   }
9142 
9143   return false;
9144 }
9145 
9146 bool
9147 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
9148                                             &FS,
9149                                           const char *startSpecifier,
9150                                           unsigned specifierLen) {
9151   using namespace analyze_format_string;
9152   using namespace analyze_printf;
9153 
9154   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9155 
9156   if (FS.consumesDataArgument()) {
9157     if (atFirstArg) {
9158         atFirstArg = false;
9159         usesPositionalArgs = FS.usesPositionalArg();
9160     }
9161     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9162       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9163                                         startSpecifier, specifierLen);
9164       return false;
9165     }
9166   }
9167 
9168   // First check if the field width, precision, and conversion specifier
9169   // have matching data arguments.
9170   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
9171                     startSpecifier, specifierLen)) {
9172     return false;
9173   }
9174 
9175   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
9176                     startSpecifier, specifierLen)) {
9177     return false;
9178   }
9179 
9180   if (!CS.consumesDataArgument()) {
9181     // FIXME: Technically specifying a precision or field width here
9182     // makes no sense.  Worth issuing a warning at some point.
9183     return true;
9184   }
9185 
9186   // Consume the argument.
9187   unsigned argIndex = FS.getArgIndex();
9188   if (argIndex < NumDataArgs) {
9189     // The check to see if the argIndex is valid will come later.
9190     // We set the bit here because we may exit early from this
9191     // function if we encounter some other error.
9192     CoveredArgs.set(argIndex);
9193   }
9194 
9195   // FreeBSD kernel extensions.
9196   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9197       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9198     // We need at least two arguments.
9199     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9200       return false;
9201 
9202     // Claim the second argument.
9203     CoveredArgs.set(argIndex + 1);
9204 
9205     // Type check the first argument (int for %b, pointer for %D)
9206     const Expr *Ex = getDataArg(argIndex);
9207     const analyze_printf::ArgType &AT =
9208       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
9209         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
9210     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9211       EmitFormatDiagnostic(
9212           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9213               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9214               << false << Ex->getSourceRange(),
9215           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9216           getSpecifierRange(startSpecifier, specifierLen));
9217 
9218     // Type check the second argument (char * for both %b and %D)
9219     Ex = getDataArg(argIndex + 1);
9220     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
9221     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9222       EmitFormatDiagnostic(
9223           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9224               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9225               << false << Ex->getSourceRange(),
9226           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9227           getSpecifierRange(startSpecifier, specifierLen));
9228 
9229      return true;
9230   }
9231 
9232   // Check for using an Objective-C specific conversion specifier
9233   // in a non-ObjC literal.
9234   if (!allowsObjCArg() && CS.isObjCArg()) {
9235     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9236                                                   specifierLen);
9237   }
9238 
9239   // %P can only be used with os_log.
9240   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
9241     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9242                                                   specifierLen);
9243   }
9244 
9245   // %n is not allowed with os_log.
9246   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
9247     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9248                          getLocationOfByte(CS.getStart()),
9249                          /*IsStringLocation*/ false,
9250                          getSpecifierRange(startSpecifier, specifierLen));
9251 
9252     return true;
9253   }
9254 
9255   // Only scalars are allowed for os_trace.
9256   if (FSType == Sema::FST_OSTrace &&
9257       (CS.getKind() == ConversionSpecifier::PArg ||
9258        CS.getKind() == ConversionSpecifier::sArg ||
9259        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9260     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9261                                                   specifierLen);
9262   }
9263 
9264   // Check for use of public/private annotation outside of os_log().
9265   if (FSType != Sema::FST_OSLog) {
9266     if (FS.isPublic().isSet()) {
9267       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9268                                << "public",
9269                            getLocationOfByte(FS.isPublic().getPosition()),
9270                            /*IsStringLocation*/ false,
9271                            getSpecifierRange(startSpecifier, specifierLen));
9272     }
9273     if (FS.isPrivate().isSet()) {
9274       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9275                                << "private",
9276                            getLocationOfByte(FS.isPrivate().getPosition()),
9277                            /*IsStringLocation*/ false,
9278                            getSpecifierRange(startSpecifier, specifierLen));
9279     }
9280   }
9281 
9282   // Check for invalid use of field width
9283   if (!FS.hasValidFieldWidth()) {
9284     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9285         startSpecifier, specifierLen);
9286   }
9287 
9288   // Check for invalid use of precision
9289   if (!FS.hasValidPrecision()) {
9290     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9291         startSpecifier, specifierLen);
9292   }
9293 
9294   // Precision is mandatory for %P specifier.
9295   if (CS.getKind() == ConversionSpecifier::PArg &&
9296       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9297     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9298                          getLocationOfByte(startSpecifier),
9299                          /*IsStringLocation*/ false,
9300                          getSpecifierRange(startSpecifier, specifierLen));
9301   }
9302 
9303   // Check each flag does not conflict with any other component.
9304   if (!FS.hasValidThousandsGroupingPrefix())
9305     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9306   if (!FS.hasValidLeadingZeros())
9307     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9308   if (!FS.hasValidPlusPrefix())
9309     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9310   if (!FS.hasValidSpacePrefix())
9311     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9312   if (!FS.hasValidAlternativeForm())
9313     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9314   if (!FS.hasValidLeftJustified())
9315     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9316 
9317   // Check that flags are not ignored by another flag
9318   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9319     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9320         startSpecifier, specifierLen);
9321   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9322     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9323             startSpecifier, specifierLen);
9324 
9325   // Check the length modifier is valid with the given conversion specifier.
9326   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9327                                  S.getLangOpts()))
9328     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9329                                 diag::warn_format_nonsensical_length);
9330   else if (!FS.hasStandardLengthModifier())
9331     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9332   else if (!FS.hasStandardLengthConversionCombination())
9333     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9334                                 diag::warn_format_non_standard_conversion_spec);
9335 
9336   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9337     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9338 
9339   // The remaining checks depend on the data arguments.
9340   if (HasVAListArg)
9341     return true;
9342 
9343   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9344     return false;
9345 
9346   const Expr *Arg = getDataArg(argIndex);
9347   if (!Arg)
9348     return true;
9349 
9350   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9351 }
9352 
9353 static bool requiresParensToAddCast(const Expr *E) {
9354   // FIXME: We should have a general way to reason about operator
9355   // precedence and whether parens are actually needed here.
9356   // Take care of a few common cases where they aren't.
9357   const Expr *Inside = E->IgnoreImpCasts();
9358   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9359     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9360 
9361   switch (Inside->getStmtClass()) {
9362   case Stmt::ArraySubscriptExprClass:
9363   case Stmt::CallExprClass:
9364   case Stmt::CharacterLiteralClass:
9365   case Stmt::CXXBoolLiteralExprClass:
9366   case Stmt::DeclRefExprClass:
9367   case Stmt::FloatingLiteralClass:
9368   case Stmt::IntegerLiteralClass:
9369   case Stmt::MemberExprClass:
9370   case Stmt::ObjCArrayLiteralClass:
9371   case Stmt::ObjCBoolLiteralExprClass:
9372   case Stmt::ObjCBoxedExprClass:
9373   case Stmt::ObjCDictionaryLiteralClass:
9374   case Stmt::ObjCEncodeExprClass:
9375   case Stmt::ObjCIvarRefExprClass:
9376   case Stmt::ObjCMessageExprClass:
9377   case Stmt::ObjCPropertyRefExprClass:
9378   case Stmt::ObjCStringLiteralClass:
9379   case Stmt::ObjCSubscriptRefExprClass:
9380   case Stmt::ParenExprClass:
9381   case Stmt::StringLiteralClass:
9382   case Stmt::UnaryOperatorClass:
9383     return false;
9384   default:
9385     return true;
9386   }
9387 }
9388 
9389 static std::pair<QualType, StringRef>
9390 shouldNotPrintDirectly(const ASTContext &Context,
9391                        QualType IntendedTy,
9392                        const Expr *E) {
9393   // Use a 'while' to peel off layers of typedefs.
9394   QualType TyTy = IntendedTy;
9395   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9396     StringRef Name = UserTy->getDecl()->getName();
9397     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9398       .Case("CFIndex", Context.getNSIntegerType())
9399       .Case("NSInteger", Context.getNSIntegerType())
9400       .Case("NSUInteger", Context.getNSUIntegerType())
9401       .Case("SInt32", Context.IntTy)
9402       .Case("UInt32", Context.UnsignedIntTy)
9403       .Default(QualType());
9404 
9405     if (!CastTy.isNull())
9406       return std::make_pair(CastTy, Name);
9407 
9408     TyTy = UserTy->desugar();
9409   }
9410 
9411   // Strip parens if necessary.
9412   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9413     return shouldNotPrintDirectly(Context,
9414                                   PE->getSubExpr()->getType(),
9415                                   PE->getSubExpr());
9416 
9417   // If this is a conditional expression, then its result type is constructed
9418   // via usual arithmetic conversions and thus there might be no necessary
9419   // typedef sugar there.  Recurse to operands to check for NSInteger &
9420   // Co. usage condition.
9421   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9422     QualType TrueTy, FalseTy;
9423     StringRef TrueName, FalseName;
9424 
9425     std::tie(TrueTy, TrueName) =
9426       shouldNotPrintDirectly(Context,
9427                              CO->getTrueExpr()->getType(),
9428                              CO->getTrueExpr());
9429     std::tie(FalseTy, FalseName) =
9430       shouldNotPrintDirectly(Context,
9431                              CO->getFalseExpr()->getType(),
9432                              CO->getFalseExpr());
9433 
9434     if (TrueTy == FalseTy)
9435       return std::make_pair(TrueTy, TrueName);
9436     else if (TrueTy.isNull())
9437       return std::make_pair(FalseTy, FalseName);
9438     else if (FalseTy.isNull())
9439       return std::make_pair(TrueTy, TrueName);
9440   }
9441 
9442   return std::make_pair(QualType(), StringRef());
9443 }
9444 
9445 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9446 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9447 /// type do not count.
9448 static bool
9449 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9450   QualType From = ICE->getSubExpr()->getType();
9451   QualType To = ICE->getType();
9452   // It's an integer promotion if the destination type is the promoted
9453   // source type.
9454   if (ICE->getCastKind() == CK_IntegralCast &&
9455       From->isPromotableIntegerType() &&
9456       S.Context.getPromotedIntegerType(From) == To)
9457     return true;
9458   // Look through vector types, since we do default argument promotion for
9459   // those in OpenCL.
9460   if (const auto *VecTy = From->getAs<ExtVectorType>())
9461     From = VecTy->getElementType();
9462   if (const auto *VecTy = To->getAs<ExtVectorType>())
9463     To = VecTy->getElementType();
9464   // It's a floating promotion if the source type is a lower rank.
9465   return ICE->getCastKind() == CK_FloatingCast &&
9466          S.Context.getFloatingTypeOrder(From, To) < 0;
9467 }
9468 
9469 bool
9470 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9471                                     const char *StartSpecifier,
9472                                     unsigned SpecifierLen,
9473                                     const Expr *E) {
9474   using namespace analyze_format_string;
9475   using namespace analyze_printf;
9476 
9477   // Now type check the data expression that matches the
9478   // format specifier.
9479   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9480   if (!AT.isValid())
9481     return true;
9482 
9483   QualType ExprTy = E->getType();
9484   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9485     ExprTy = TET->getUnderlyingExpr()->getType();
9486   }
9487 
9488   // Diagnose attempts to print a boolean value as a character. Unlike other
9489   // -Wformat diagnostics, this is fine from a type perspective, but it still
9490   // doesn't make sense.
9491   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9492       E->isKnownToHaveBooleanValue()) {
9493     const CharSourceRange &CSR =
9494         getSpecifierRange(StartSpecifier, SpecifierLen);
9495     SmallString<4> FSString;
9496     llvm::raw_svector_ostream os(FSString);
9497     FS.toString(os);
9498     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9499                              << FSString,
9500                          E->getExprLoc(), false, CSR);
9501     return true;
9502   }
9503 
9504   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9505   if (Match == analyze_printf::ArgType::Match)
9506     return true;
9507 
9508   // Look through argument promotions for our error message's reported type.
9509   // This includes the integral and floating promotions, but excludes array
9510   // and function pointer decay (seeing that an argument intended to be a
9511   // string has type 'char [6]' is probably more confusing than 'char *') and
9512   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9513   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9514     if (isArithmeticArgumentPromotion(S, ICE)) {
9515       E = ICE->getSubExpr();
9516       ExprTy = E->getType();
9517 
9518       // Check if we didn't match because of an implicit cast from a 'char'
9519       // or 'short' to an 'int'.  This is done because printf is a varargs
9520       // function.
9521       if (ICE->getType() == S.Context.IntTy ||
9522           ICE->getType() == S.Context.UnsignedIntTy) {
9523         // All further checking is done on the subexpression
9524         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9525             AT.matchesType(S.Context, ExprTy);
9526         if (ImplicitMatch == analyze_printf::ArgType::Match)
9527           return true;
9528         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9529             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9530           Match = ImplicitMatch;
9531       }
9532     }
9533   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9534     // Special case for 'a', which has type 'int' in C.
9535     // Note, however, that we do /not/ want to treat multibyte constants like
9536     // 'MooV' as characters! This form is deprecated but still exists. In
9537     // addition, don't treat expressions as of type 'char' if one byte length
9538     // modifier is provided.
9539     if (ExprTy == S.Context.IntTy &&
9540         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9541       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9542         ExprTy = S.Context.CharTy;
9543   }
9544 
9545   // Look through enums to their underlying type.
9546   bool IsEnum = false;
9547   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9548     ExprTy = EnumTy->getDecl()->getIntegerType();
9549     IsEnum = true;
9550   }
9551 
9552   // %C in an Objective-C context prints a unichar, not a wchar_t.
9553   // If the argument is an integer of some kind, believe the %C and suggest
9554   // a cast instead of changing the conversion specifier.
9555   QualType IntendedTy = ExprTy;
9556   if (isObjCContext() &&
9557       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9558     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9559         !ExprTy->isCharType()) {
9560       // 'unichar' is defined as a typedef of unsigned short, but we should
9561       // prefer using the typedef if it is visible.
9562       IntendedTy = S.Context.UnsignedShortTy;
9563 
9564       // While we are here, check if the value is an IntegerLiteral that happens
9565       // to be within the valid range.
9566       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9567         const llvm::APInt &V = IL->getValue();
9568         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9569           return true;
9570       }
9571 
9572       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9573                           Sema::LookupOrdinaryName);
9574       if (S.LookupName(Result, S.getCurScope())) {
9575         NamedDecl *ND = Result.getFoundDecl();
9576         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9577           if (TD->getUnderlyingType() == IntendedTy)
9578             IntendedTy = S.Context.getTypedefType(TD);
9579       }
9580     }
9581   }
9582 
9583   // Special-case some of Darwin's platform-independence types by suggesting
9584   // casts to primitive types that are known to be large enough.
9585   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9586   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9587     QualType CastTy;
9588     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9589     if (!CastTy.isNull()) {
9590       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9591       // (long in ASTContext). Only complain to pedants.
9592       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9593           (AT.isSizeT() || AT.isPtrdiffT()) &&
9594           AT.matchesType(S.Context, CastTy))
9595         Match = ArgType::NoMatchPedantic;
9596       IntendedTy = CastTy;
9597       ShouldNotPrintDirectly = true;
9598     }
9599   }
9600 
9601   // We may be able to offer a FixItHint if it is a supported type.
9602   PrintfSpecifier fixedFS = FS;
9603   bool Success =
9604       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9605 
9606   if (Success) {
9607     // Get the fix string from the fixed format specifier
9608     SmallString<16> buf;
9609     llvm::raw_svector_ostream os(buf);
9610     fixedFS.toString(os);
9611 
9612     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9613 
9614     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9615       unsigned Diag;
9616       switch (Match) {
9617       case ArgType::Match: llvm_unreachable("expected non-matching");
9618       case ArgType::NoMatchPedantic:
9619         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9620         break;
9621       case ArgType::NoMatchTypeConfusion:
9622         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9623         break;
9624       case ArgType::NoMatch:
9625         Diag = diag::warn_format_conversion_argument_type_mismatch;
9626         break;
9627       }
9628 
9629       // In this case, the specifier is wrong and should be changed to match
9630       // the argument.
9631       EmitFormatDiagnostic(S.PDiag(Diag)
9632                                << AT.getRepresentativeTypeName(S.Context)
9633                                << IntendedTy << IsEnum << E->getSourceRange(),
9634                            E->getBeginLoc(),
9635                            /*IsStringLocation*/ false, SpecRange,
9636                            FixItHint::CreateReplacement(SpecRange, os.str()));
9637     } else {
9638       // The canonical type for formatting this value is different from the
9639       // actual type of the expression. (This occurs, for example, with Darwin's
9640       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9641       // should be printed as 'long' for 64-bit compatibility.)
9642       // Rather than emitting a normal format/argument mismatch, we want to
9643       // add a cast to the recommended type (and correct the format string
9644       // if necessary).
9645       SmallString<16> CastBuf;
9646       llvm::raw_svector_ostream CastFix(CastBuf);
9647       CastFix << "(";
9648       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9649       CastFix << ")";
9650 
9651       SmallVector<FixItHint,4> Hints;
9652       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9653         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9654 
9655       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9656         // If there's already a cast present, just replace it.
9657         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9658         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9659 
9660       } else if (!requiresParensToAddCast(E)) {
9661         // If the expression has high enough precedence,
9662         // just write the C-style cast.
9663         Hints.push_back(
9664             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9665       } else {
9666         // Otherwise, add parens around the expression as well as the cast.
9667         CastFix << "(";
9668         Hints.push_back(
9669             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9670 
9671         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9672         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9673       }
9674 
9675       if (ShouldNotPrintDirectly) {
9676         // The expression has a type that should not be printed directly.
9677         // We extract the name from the typedef because we don't want to show
9678         // the underlying type in the diagnostic.
9679         StringRef Name;
9680         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9681           Name = TypedefTy->getDecl()->getName();
9682         else
9683           Name = CastTyName;
9684         unsigned Diag = Match == ArgType::NoMatchPedantic
9685                             ? diag::warn_format_argument_needs_cast_pedantic
9686                             : diag::warn_format_argument_needs_cast;
9687         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9688                                            << E->getSourceRange(),
9689                              E->getBeginLoc(), /*IsStringLocation=*/false,
9690                              SpecRange, Hints);
9691       } else {
9692         // In this case, the expression could be printed using a different
9693         // specifier, but we've decided that the specifier is probably correct
9694         // and we should cast instead. Just use the normal warning message.
9695         EmitFormatDiagnostic(
9696             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9697                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9698                 << E->getSourceRange(),
9699             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9700       }
9701     }
9702   } else {
9703     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9704                                                    SpecifierLen);
9705     // Since the warning for passing non-POD types to variadic functions
9706     // was deferred until now, we emit a warning for non-POD
9707     // arguments here.
9708     switch (S.isValidVarArgType(ExprTy)) {
9709     case Sema::VAK_Valid:
9710     case Sema::VAK_ValidInCXX11: {
9711       unsigned Diag;
9712       switch (Match) {
9713       case ArgType::Match: llvm_unreachable("expected non-matching");
9714       case ArgType::NoMatchPedantic:
9715         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9716         break;
9717       case ArgType::NoMatchTypeConfusion:
9718         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9719         break;
9720       case ArgType::NoMatch:
9721         Diag = diag::warn_format_conversion_argument_type_mismatch;
9722         break;
9723       }
9724 
9725       EmitFormatDiagnostic(
9726           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9727                         << IsEnum << CSR << E->getSourceRange(),
9728           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9729       break;
9730     }
9731     case Sema::VAK_Undefined:
9732     case Sema::VAK_MSVCUndefined:
9733       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9734                                << S.getLangOpts().CPlusPlus11 << ExprTy
9735                                << CallType
9736                                << AT.getRepresentativeTypeName(S.Context) << CSR
9737                                << E->getSourceRange(),
9738                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9739       checkForCStrMembers(AT, E);
9740       break;
9741 
9742     case Sema::VAK_Invalid:
9743       if (ExprTy->isObjCObjectType())
9744         EmitFormatDiagnostic(
9745             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9746                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9747                 << AT.getRepresentativeTypeName(S.Context) << CSR
9748                 << E->getSourceRange(),
9749             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9750       else
9751         // FIXME: If this is an initializer list, suggest removing the braces
9752         // or inserting a cast to the target type.
9753         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9754             << isa<InitListExpr>(E) << ExprTy << CallType
9755             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9756       break;
9757     }
9758 
9759     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9760            "format string specifier index out of range");
9761     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9762   }
9763 
9764   return true;
9765 }
9766 
9767 //===--- CHECK: Scanf format string checking ------------------------------===//
9768 
9769 namespace {
9770 
9771 class CheckScanfHandler : public CheckFormatHandler {
9772 public:
9773   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9774                     const Expr *origFormatExpr, Sema::FormatStringType type,
9775                     unsigned firstDataArg, unsigned numDataArgs,
9776                     const char *beg, bool hasVAListArg,
9777                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9778                     bool inFunctionCall, Sema::VariadicCallType CallType,
9779                     llvm::SmallBitVector &CheckedVarArgs,
9780                     UncoveredArgHandler &UncoveredArg)
9781       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9782                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9783                            inFunctionCall, CallType, CheckedVarArgs,
9784                            UncoveredArg) {}
9785 
9786   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9787                             const char *startSpecifier,
9788                             unsigned specifierLen) override;
9789 
9790   bool HandleInvalidScanfConversionSpecifier(
9791           const analyze_scanf::ScanfSpecifier &FS,
9792           const char *startSpecifier,
9793           unsigned specifierLen) override;
9794 
9795   void HandleIncompleteScanList(const char *start, const char *end) override;
9796 };
9797 
9798 } // namespace
9799 
9800 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9801                                                  const char *end) {
9802   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9803                        getLocationOfByte(end), /*IsStringLocation*/true,
9804                        getSpecifierRange(start, end - start));
9805 }
9806 
9807 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9808                                         const analyze_scanf::ScanfSpecifier &FS,
9809                                         const char *startSpecifier,
9810                                         unsigned specifierLen) {
9811   const analyze_scanf::ScanfConversionSpecifier &CS =
9812     FS.getConversionSpecifier();
9813 
9814   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9815                                           getLocationOfByte(CS.getStart()),
9816                                           startSpecifier, specifierLen,
9817                                           CS.getStart(), CS.getLength());
9818 }
9819 
9820 bool CheckScanfHandler::HandleScanfSpecifier(
9821                                        const analyze_scanf::ScanfSpecifier &FS,
9822                                        const char *startSpecifier,
9823                                        unsigned specifierLen) {
9824   using namespace analyze_scanf;
9825   using namespace analyze_format_string;
9826 
9827   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9828 
9829   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9830   // be used to decide if we are using positional arguments consistently.
9831   if (FS.consumesDataArgument()) {
9832     if (atFirstArg) {
9833       atFirstArg = false;
9834       usesPositionalArgs = FS.usesPositionalArg();
9835     }
9836     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9837       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9838                                         startSpecifier, specifierLen);
9839       return false;
9840     }
9841   }
9842 
9843   // Check if the field with is non-zero.
9844   const OptionalAmount &Amt = FS.getFieldWidth();
9845   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9846     if (Amt.getConstantAmount() == 0) {
9847       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9848                                                    Amt.getConstantLength());
9849       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9850                            getLocationOfByte(Amt.getStart()),
9851                            /*IsStringLocation*/true, R,
9852                            FixItHint::CreateRemoval(R));
9853     }
9854   }
9855 
9856   if (!FS.consumesDataArgument()) {
9857     // FIXME: Technically specifying a precision or field width here
9858     // makes no sense.  Worth issuing a warning at some point.
9859     return true;
9860   }
9861 
9862   // Consume the argument.
9863   unsigned argIndex = FS.getArgIndex();
9864   if (argIndex < NumDataArgs) {
9865       // The check to see if the argIndex is valid will come later.
9866       // We set the bit here because we may exit early from this
9867       // function if we encounter some other error.
9868     CoveredArgs.set(argIndex);
9869   }
9870 
9871   // Check the length modifier is valid with the given conversion specifier.
9872   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9873                                  S.getLangOpts()))
9874     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9875                                 diag::warn_format_nonsensical_length);
9876   else if (!FS.hasStandardLengthModifier())
9877     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9878   else if (!FS.hasStandardLengthConversionCombination())
9879     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9880                                 diag::warn_format_non_standard_conversion_spec);
9881 
9882   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9883     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9884 
9885   // The remaining checks depend on the data arguments.
9886   if (HasVAListArg)
9887     return true;
9888 
9889   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9890     return false;
9891 
9892   // Check that the argument type matches the format specifier.
9893   const Expr *Ex = getDataArg(argIndex);
9894   if (!Ex)
9895     return true;
9896 
9897   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9898 
9899   if (!AT.isValid()) {
9900     return true;
9901   }
9902 
9903   analyze_format_string::ArgType::MatchKind Match =
9904       AT.matchesType(S.Context, Ex->getType());
9905   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9906   if (Match == analyze_format_string::ArgType::Match)
9907     return true;
9908 
9909   ScanfSpecifier fixedFS = FS;
9910   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9911                                  S.getLangOpts(), S.Context);
9912 
9913   unsigned Diag =
9914       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9915                : diag::warn_format_conversion_argument_type_mismatch;
9916 
9917   if (Success) {
9918     // Get the fix string from the fixed format specifier.
9919     SmallString<128> buf;
9920     llvm::raw_svector_ostream os(buf);
9921     fixedFS.toString(os);
9922 
9923     EmitFormatDiagnostic(
9924         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9925                       << Ex->getType() << false << Ex->getSourceRange(),
9926         Ex->getBeginLoc(),
9927         /*IsStringLocation*/ false,
9928         getSpecifierRange(startSpecifier, specifierLen),
9929         FixItHint::CreateReplacement(
9930             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9931   } else {
9932     EmitFormatDiagnostic(S.PDiag(Diag)
9933                              << AT.getRepresentativeTypeName(S.Context)
9934                              << Ex->getType() << false << Ex->getSourceRange(),
9935                          Ex->getBeginLoc(),
9936                          /*IsStringLocation*/ false,
9937                          getSpecifierRange(startSpecifier, specifierLen));
9938   }
9939 
9940   return true;
9941 }
9942 
9943 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9944                               const Expr *OrigFormatExpr,
9945                               ArrayRef<const Expr *> Args,
9946                               bool HasVAListArg, unsigned format_idx,
9947                               unsigned firstDataArg,
9948                               Sema::FormatStringType Type,
9949                               bool inFunctionCall,
9950                               Sema::VariadicCallType CallType,
9951                               llvm::SmallBitVector &CheckedVarArgs,
9952                               UncoveredArgHandler &UncoveredArg,
9953                               bool IgnoreStringsWithoutSpecifiers) {
9954   // CHECK: is the format string a wide literal?
9955   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9956     CheckFormatHandler::EmitFormatDiagnostic(
9957         S, inFunctionCall, Args[format_idx],
9958         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9959         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9960     return;
9961   }
9962 
9963   // Str - The format string.  NOTE: this is NOT null-terminated!
9964   StringRef StrRef = FExpr->getString();
9965   const char *Str = StrRef.data();
9966   // Account for cases where the string literal is truncated in a declaration.
9967   const ConstantArrayType *T =
9968     S.Context.getAsConstantArrayType(FExpr->getType());
9969   assert(T && "String literal not of constant array type!");
9970   size_t TypeSize = T->getSize().getZExtValue();
9971   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9972   const unsigned numDataArgs = Args.size() - firstDataArg;
9973 
9974   if (IgnoreStringsWithoutSpecifiers &&
9975       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9976           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9977     return;
9978 
9979   // Emit a warning if the string literal is truncated and does not contain an
9980   // embedded null character.
9981   if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9982     CheckFormatHandler::EmitFormatDiagnostic(
9983         S, inFunctionCall, Args[format_idx],
9984         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9985         FExpr->getBeginLoc(),
9986         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9987     return;
9988   }
9989 
9990   // CHECK: empty format string?
9991   if (StrLen == 0 && numDataArgs > 0) {
9992     CheckFormatHandler::EmitFormatDiagnostic(
9993         S, inFunctionCall, Args[format_idx],
9994         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9995         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9996     return;
9997   }
9998 
9999   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
10000       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
10001       Type == Sema::FST_OSTrace) {
10002     CheckPrintfHandler H(
10003         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
10004         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
10005         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
10006         CheckedVarArgs, UncoveredArg);
10007 
10008     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
10009                                                   S.getLangOpts(),
10010                                                   S.Context.getTargetInfo(),
10011                                             Type == Sema::FST_FreeBSDKPrintf))
10012       H.DoneProcessing();
10013   } else if (Type == Sema::FST_Scanf) {
10014     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10015                         numDataArgs, Str, HasVAListArg, Args, format_idx,
10016                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
10017 
10018     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
10019                                                  S.getLangOpts(),
10020                                                  S.Context.getTargetInfo()))
10021       H.DoneProcessing();
10022   } // TODO: handle other formats
10023 }
10024 
10025 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
10026   // Str - The format string.  NOTE: this is NOT null-terminated!
10027   StringRef StrRef = FExpr->getString();
10028   const char *Str = StrRef.data();
10029   // Account for cases where the string literal is truncated in a declaration.
10030   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
10031   assert(T && "String literal not of constant array type!");
10032   size_t TypeSize = T->getSize().getZExtValue();
10033   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10034   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
10035                                                          getLangOpts(),
10036                                                          Context.getTargetInfo());
10037 }
10038 
10039 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10040 
10041 // Returns the related absolute value function that is larger, of 0 if one
10042 // does not exist.
10043 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10044   switch (AbsFunction) {
10045   default:
10046     return 0;
10047 
10048   case Builtin::BI__builtin_abs:
10049     return Builtin::BI__builtin_labs;
10050   case Builtin::BI__builtin_labs:
10051     return Builtin::BI__builtin_llabs;
10052   case Builtin::BI__builtin_llabs:
10053     return 0;
10054 
10055   case Builtin::BI__builtin_fabsf:
10056     return Builtin::BI__builtin_fabs;
10057   case Builtin::BI__builtin_fabs:
10058     return Builtin::BI__builtin_fabsl;
10059   case Builtin::BI__builtin_fabsl:
10060     return 0;
10061 
10062   case Builtin::BI__builtin_cabsf:
10063     return Builtin::BI__builtin_cabs;
10064   case Builtin::BI__builtin_cabs:
10065     return Builtin::BI__builtin_cabsl;
10066   case Builtin::BI__builtin_cabsl:
10067     return 0;
10068 
10069   case Builtin::BIabs:
10070     return Builtin::BIlabs;
10071   case Builtin::BIlabs:
10072     return Builtin::BIllabs;
10073   case Builtin::BIllabs:
10074     return 0;
10075 
10076   case Builtin::BIfabsf:
10077     return Builtin::BIfabs;
10078   case Builtin::BIfabs:
10079     return Builtin::BIfabsl;
10080   case Builtin::BIfabsl:
10081     return 0;
10082 
10083   case Builtin::BIcabsf:
10084    return Builtin::BIcabs;
10085   case Builtin::BIcabs:
10086     return Builtin::BIcabsl;
10087   case Builtin::BIcabsl:
10088     return 0;
10089   }
10090 }
10091 
10092 // Returns the argument type of the absolute value function.
10093 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
10094                                              unsigned AbsType) {
10095   if (AbsType == 0)
10096     return QualType();
10097 
10098   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
10099   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10100   if (Error != ASTContext::GE_None)
10101     return QualType();
10102 
10103   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
10104   if (!FT)
10105     return QualType();
10106 
10107   if (FT->getNumParams() != 1)
10108     return QualType();
10109 
10110   return FT->getParamType(0);
10111 }
10112 
10113 // Returns the best absolute value function, or zero, based on type and
10114 // current absolute value function.
10115 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10116                                    unsigned AbsFunctionKind) {
10117   unsigned BestKind = 0;
10118   uint64_t ArgSize = Context.getTypeSize(ArgType);
10119   for (unsigned Kind = AbsFunctionKind; Kind != 0;
10120        Kind = getLargerAbsoluteValueFunction(Kind)) {
10121     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10122     if (Context.getTypeSize(ParamType) >= ArgSize) {
10123       if (BestKind == 0)
10124         BestKind = Kind;
10125       else if (Context.hasSameType(ParamType, ArgType)) {
10126         BestKind = Kind;
10127         break;
10128       }
10129     }
10130   }
10131   return BestKind;
10132 }
10133 
10134 enum AbsoluteValueKind {
10135   AVK_Integer,
10136   AVK_Floating,
10137   AVK_Complex
10138 };
10139 
10140 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
10141   if (T->isIntegralOrEnumerationType())
10142     return AVK_Integer;
10143   if (T->isRealFloatingType())
10144     return AVK_Floating;
10145   if (T->isAnyComplexType())
10146     return AVK_Complex;
10147 
10148   llvm_unreachable("Type not integer, floating, or complex");
10149 }
10150 
10151 // Changes the absolute value function to a different type.  Preserves whether
10152 // the function is a builtin.
10153 static unsigned changeAbsFunction(unsigned AbsKind,
10154                                   AbsoluteValueKind ValueKind) {
10155   switch (ValueKind) {
10156   case AVK_Integer:
10157     switch (AbsKind) {
10158     default:
10159       return 0;
10160     case Builtin::BI__builtin_fabsf:
10161     case Builtin::BI__builtin_fabs:
10162     case Builtin::BI__builtin_fabsl:
10163     case Builtin::BI__builtin_cabsf:
10164     case Builtin::BI__builtin_cabs:
10165     case Builtin::BI__builtin_cabsl:
10166       return Builtin::BI__builtin_abs;
10167     case Builtin::BIfabsf:
10168     case Builtin::BIfabs:
10169     case Builtin::BIfabsl:
10170     case Builtin::BIcabsf:
10171     case Builtin::BIcabs:
10172     case Builtin::BIcabsl:
10173       return Builtin::BIabs;
10174     }
10175   case AVK_Floating:
10176     switch (AbsKind) {
10177     default:
10178       return 0;
10179     case Builtin::BI__builtin_abs:
10180     case Builtin::BI__builtin_labs:
10181     case Builtin::BI__builtin_llabs:
10182     case Builtin::BI__builtin_cabsf:
10183     case Builtin::BI__builtin_cabs:
10184     case Builtin::BI__builtin_cabsl:
10185       return Builtin::BI__builtin_fabsf;
10186     case Builtin::BIabs:
10187     case Builtin::BIlabs:
10188     case Builtin::BIllabs:
10189     case Builtin::BIcabsf:
10190     case Builtin::BIcabs:
10191     case Builtin::BIcabsl:
10192       return Builtin::BIfabsf;
10193     }
10194   case AVK_Complex:
10195     switch (AbsKind) {
10196     default:
10197       return 0;
10198     case Builtin::BI__builtin_abs:
10199     case Builtin::BI__builtin_labs:
10200     case Builtin::BI__builtin_llabs:
10201     case Builtin::BI__builtin_fabsf:
10202     case Builtin::BI__builtin_fabs:
10203     case Builtin::BI__builtin_fabsl:
10204       return Builtin::BI__builtin_cabsf;
10205     case Builtin::BIabs:
10206     case Builtin::BIlabs:
10207     case Builtin::BIllabs:
10208     case Builtin::BIfabsf:
10209     case Builtin::BIfabs:
10210     case Builtin::BIfabsl:
10211       return Builtin::BIcabsf;
10212     }
10213   }
10214   llvm_unreachable("Unable to convert function");
10215 }
10216 
10217 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10218   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10219   if (!FnInfo)
10220     return 0;
10221 
10222   switch (FDecl->getBuiltinID()) {
10223   default:
10224     return 0;
10225   case Builtin::BI__builtin_abs:
10226   case Builtin::BI__builtin_fabs:
10227   case Builtin::BI__builtin_fabsf:
10228   case Builtin::BI__builtin_fabsl:
10229   case Builtin::BI__builtin_labs:
10230   case Builtin::BI__builtin_llabs:
10231   case Builtin::BI__builtin_cabs:
10232   case Builtin::BI__builtin_cabsf:
10233   case Builtin::BI__builtin_cabsl:
10234   case Builtin::BIabs:
10235   case Builtin::BIlabs:
10236   case Builtin::BIllabs:
10237   case Builtin::BIfabs:
10238   case Builtin::BIfabsf:
10239   case Builtin::BIfabsl:
10240   case Builtin::BIcabs:
10241   case Builtin::BIcabsf:
10242   case Builtin::BIcabsl:
10243     return FDecl->getBuiltinID();
10244   }
10245   llvm_unreachable("Unknown Builtin type");
10246 }
10247 
10248 // If the replacement is valid, emit a note with replacement function.
10249 // Additionally, suggest including the proper header if not already included.
10250 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10251                             unsigned AbsKind, QualType ArgType) {
10252   bool EmitHeaderHint = true;
10253   const char *HeaderName = nullptr;
10254   const char *FunctionName = nullptr;
10255   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10256     FunctionName = "std::abs";
10257     if (ArgType->isIntegralOrEnumerationType()) {
10258       HeaderName = "cstdlib";
10259     } else if (ArgType->isRealFloatingType()) {
10260       HeaderName = "cmath";
10261     } else {
10262       llvm_unreachable("Invalid Type");
10263     }
10264 
10265     // Lookup all std::abs
10266     if (NamespaceDecl *Std = S.getStdNamespace()) {
10267       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10268       R.suppressDiagnostics();
10269       S.LookupQualifiedName(R, Std);
10270 
10271       for (const auto *I : R) {
10272         const FunctionDecl *FDecl = nullptr;
10273         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10274           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10275         } else {
10276           FDecl = dyn_cast<FunctionDecl>(I);
10277         }
10278         if (!FDecl)
10279           continue;
10280 
10281         // Found std::abs(), check that they are the right ones.
10282         if (FDecl->getNumParams() != 1)
10283           continue;
10284 
10285         // Check that the parameter type can handle the argument.
10286         QualType ParamType = FDecl->getParamDecl(0)->getType();
10287         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10288             S.Context.getTypeSize(ArgType) <=
10289                 S.Context.getTypeSize(ParamType)) {
10290           // Found a function, don't need the header hint.
10291           EmitHeaderHint = false;
10292           break;
10293         }
10294       }
10295     }
10296   } else {
10297     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10298     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10299 
10300     if (HeaderName) {
10301       DeclarationName DN(&S.Context.Idents.get(FunctionName));
10302       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10303       R.suppressDiagnostics();
10304       S.LookupName(R, S.getCurScope());
10305 
10306       if (R.isSingleResult()) {
10307         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10308         if (FD && FD->getBuiltinID() == AbsKind) {
10309           EmitHeaderHint = false;
10310         } else {
10311           return;
10312         }
10313       } else if (!R.empty()) {
10314         return;
10315       }
10316     }
10317   }
10318 
10319   S.Diag(Loc, diag::note_replace_abs_function)
10320       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10321 
10322   if (!HeaderName)
10323     return;
10324 
10325   if (!EmitHeaderHint)
10326     return;
10327 
10328   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10329                                                     << FunctionName;
10330 }
10331 
10332 template <std::size_t StrLen>
10333 static bool IsStdFunction(const FunctionDecl *FDecl,
10334                           const char (&Str)[StrLen]) {
10335   if (!FDecl)
10336     return false;
10337   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10338     return false;
10339   if (!FDecl->isInStdNamespace())
10340     return false;
10341 
10342   return true;
10343 }
10344 
10345 // Warn when using the wrong abs() function.
10346 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10347                                       const FunctionDecl *FDecl) {
10348   if (Call->getNumArgs() != 1)
10349     return;
10350 
10351   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10352   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10353   if (AbsKind == 0 && !IsStdAbs)
10354     return;
10355 
10356   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10357   QualType ParamType = Call->getArg(0)->getType();
10358 
10359   // Unsigned types cannot be negative.  Suggest removing the absolute value
10360   // function call.
10361   if (ArgType->isUnsignedIntegerType()) {
10362     const char *FunctionName =
10363         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10364     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10365     Diag(Call->getExprLoc(), diag::note_remove_abs)
10366         << FunctionName
10367         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10368     return;
10369   }
10370 
10371   // Taking the absolute value of a pointer is very suspicious, they probably
10372   // wanted to index into an array, dereference a pointer, call a function, etc.
10373   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10374     unsigned DiagType = 0;
10375     if (ArgType->isFunctionType())
10376       DiagType = 1;
10377     else if (ArgType->isArrayType())
10378       DiagType = 2;
10379 
10380     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10381     return;
10382   }
10383 
10384   // std::abs has overloads which prevent most of the absolute value problems
10385   // from occurring.
10386   if (IsStdAbs)
10387     return;
10388 
10389   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10390   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10391 
10392   // The argument and parameter are the same kind.  Check if they are the right
10393   // size.
10394   if (ArgValueKind == ParamValueKind) {
10395     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10396       return;
10397 
10398     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10399     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10400         << FDecl << ArgType << ParamType;
10401 
10402     if (NewAbsKind == 0)
10403       return;
10404 
10405     emitReplacement(*this, Call->getExprLoc(),
10406                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10407     return;
10408   }
10409 
10410   // ArgValueKind != ParamValueKind
10411   // The wrong type of absolute value function was used.  Attempt to find the
10412   // proper one.
10413   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10414   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10415   if (NewAbsKind == 0)
10416     return;
10417 
10418   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10419       << FDecl << ParamValueKind << ArgValueKind;
10420 
10421   emitReplacement(*this, Call->getExprLoc(),
10422                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10423 }
10424 
10425 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10426 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10427                                 const FunctionDecl *FDecl) {
10428   if (!Call || !FDecl) return;
10429 
10430   // Ignore template specializations and macros.
10431   if (inTemplateInstantiation()) return;
10432   if (Call->getExprLoc().isMacroID()) return;
10433 
10434   // Only care about the one template argument, two function parameter std::max
10435   if (Call->getNumArgs() != 2) return;
10436   if (!IsStdFunction(FDecl, "max")) return;
10437   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10438   if (!ArgList) return;
10439   if (ArgList->size() != 1) return;
10440 
10441   // Check that template type argument is unsigned integer.
10442   const auto& TA = ArgList->get(0);
10443   if (TA.getKind() != TemplateArgument::Type) return;
10444   QualType ArgType = TA.getAsType();
10445   if (!ArgType->isUnsignedIntegerType()) return;
10446 
10447   // See if either argument is a literal zero.
10448   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10449     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10450     if (!MTE) return false;
10451     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10452     if (!Num) return false;
10453     if (Num->getValue() != 0) return false;
10454     return true;
10455   };
10456 
10457   const Expr *FirstArg = Call->getArg(0);
10458   const Expr *SecondArg = Call->getArg(1);
10459   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10460   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10461 
10462   // Only warn when exactly one argument is zero.
10463   if (IsFirstArgZero == IsSecondArgZero) return;
10464 
10465   SourceRange FirstRange = FirstArg->getSourceRange();
10466   SourceRange SecondRange = SecondArg->getSourceRange();
10467 
10468   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10469 
10470   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10471       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10472 
10473   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10474   SourceRange RemovalRange;
10475   if (IsFirstArgZero) {
10476     RemovalRange = SourceRange(FirstRange.getBegin(),
10477                                SecondRange.getBegin().getLocWithOffset(-1));
10478   } else {
10479     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10480                                SecondRange.getEnd());
10481   }
10482 
10483   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10484         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10485         << FixItHint::CreateRemoval(RemovalRange);
10486 }
10487 
10488 //===--- CHECK: Standard memory functions ---------------------------------===//
10489 
10490 /// Takes the expression passed to the size_t parameter of functions
10491 /// such as memcmp, strncat, etc and warns if it's a comparison.
10492 ///
10493 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10494 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10495                                            IdentifierInfo *FnName,
10496                                            SourceLocation FnLoc,
10497                                            SourceLocation RParenLoc) {
10498   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10499   if (!Size)
10500     return false;
10501 
10502   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10503   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10504     return false;
10505 
10506   SourceRange SizeRange = Size->getSourceRange();
10507   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10508       << SizeRange << FnName;
10509   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10510       << FnName
10511       << FixItHint::CreateInsertion(
10512              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10513       << FixItHint::CreateRemoval(RParenLoc);
10514   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10515       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10516       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10517                                     ")");
10518 
10519   return true;
10520 }
10521 
10522 /// Determine whether the given type is or contains a dynamic class type
10523 /// (e.g., whether it has a vtable).
10524 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10525                                                      bool &IsContained) {
10526   // Look through array types while ignoring qualifiers.
10527   const Type *Ty = T->getBaseElementTypeUnsafe();
10528   IsContained = false;
10529 
10530   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10531   RD = RD ? RD->getDefinition() : nullptr;
10532   if (!RD || RD->isInvalidDecl())
10533     return nullptr;
10534 
10535   if (RD->isDynamicClass())
10536     return RD;
10537 
10538   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10539   // It's impossible for a class to transitively contain itself by value, so
10540   // infinite recursion is impossible.
10541   for (auto *FD : RD->fields()) {
10542     bool SubContained;
10543     if (const CXXRecordDecl *ContainedRD =
10544             getContainedDynamicClass(FD->getType(), SubContained)) {
10545       IsContained = true;
10546       return ContainedRD;
10547     }
10548   }
10549 
10550   return nullptr;
10551 }
10552 
10553 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10554   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10555     if (Unary->getKind() == UETT_SizeOf)
10556       return Unary;
10557   return nullptr;
10558 }
10559 
10560 /// If E is a sizeof expression, returns its argument expression,
10561 /// otherwise returns NULL.
10562 static const Expr *getSizeOfExprArg(const Expr *E) {
10563   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10564     if (!SizeOf->isArgumentType())
10565       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10566   return nullptr;
10567 }
10568 
10569 /// If E is a sizeof expression, returns its argument type.
10570 static QualType getSizeOfArgType(const Expr *E) {
10571   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10572     return SizeOf->getTypeOfArgument();
10573   return QualType();
10574 }
10575 
10576 namespace {
10577 
10578 struct SearchNonTrivialToInitializeField
10579     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10580   using Super =
10581       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10582 
10583   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10584 
10585   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10586                      SourceLocation SL) {
10587     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10588       asDerived().visitArray(PDIK, AT, SL);
10589       return;
10590     }
10591 
10592     Super::visitWithKind(PDIK, FT, SL);
10593   }
10594 
10595   void visitARCStrong(QualType FT, SourceLocation SL) {
10596     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10597   }
10598   void visitARCWeak(QualType FT, SourceLocation SL) {
10599     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10600   }
10601   void visitStruct(QualType FT, SourceLocation SL) {
10602     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10603       visit(FD->getType(), FD->getLocation());
10604   }
10605   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10606                   const ArrayType *AT, SourceLocation SL) {
10607     visit(getContext().getBaseElementType(AT), SL);
10608   }
10609   void visitTrivial(QualType FT, SourceLocation SL) {}
10610 
10611   static void diag(QualType RT, const Expr *E, Sema &S) {
10612     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10613   }
10614 
10615   ASTContext &getContext() { return S.getASTContext(); }
10616 
10617   const Expr *E;
10618   Sema &S;
10619 };
10620 
10621 struct SearchNonTrivialToCopyField
10622     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10623   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10624 
10625   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10626 
10627   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10628                      SourceLocation SL) {
10629     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10630       asDerived().visitArray(PCK, AT, SL);
10631       return;
10632     }
10633 
10634     Super::visitWithKind(PCK, FT, SL);
10635   }
10636 
10637   void visitARCStrong(QualType FT, SourceLocation SL) {
10638     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10639   }
10640   void visitARCWeak(QualType FT, SourceLocation SL) {
10641     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10642   }
10643   void visitStruct(QualType FT, SourceLocation SL) {
10644     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10645       visit(FD->getType(), FD->getLocation());
10646   }
10647   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10648                   SourceLocation SL) {
10649     visit(getContext().getBaseElementType(AT), SL);
10650   }
10651   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10652                 SourceLocation SL) {}
10653   void visitTrivial(QualType FT, SourceLocation SL) {}
10654   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10655 
10656   static void diag(QualType RT, const Expr *E, Sema &S) {
10657     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10658   }
10659 
10660   ASTContext &getContext() { return S.getASTContext(); }
10661 
10662   const Expr *E;
10663   Sema &S;
10664 };
10665 
10666 }
10667 
10668 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10669 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10670   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10671 
10672   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10673     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10674       return false;
10675 
10676     return doesExprLikelyComputeSize(BO->getLHS()) ||
10677            doesExprLikelyComputeSize(BO->getRHS());
10678   }
10679 
10680   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10681 }
10682 
10683 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10684 ///
10685 /// \code
10686 ///   #define MACRO 0
10687 ///   foo(MACRO);
10688 ///   foo(0);
10689 /// \endcode
10690 ///
10691 /// This should return true for the first call to foo, but not for the second
10692 /// (regardless of whether foo is a macro or function).
10693 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10694                                         SourceLocation CallLoc,
10695                                         SourceLocation ArgLoc) {
10696   if (!CallLoc.isMacroID())
10697     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10698 
10699   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10700          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10701 }
10702 
10703 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10704 /// last two arguments transposed.
10705 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10706   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10707     return;
10708 
10709   const Expr *SizeArg =
10710     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10711 
10712   auto isLiteralZero = [](const Expr *E) {
10713     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10714   };
10715 
10716   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10717   SourceLocation CallLoc = Call->getRParenLoc();
10718   SourceManager &SM = S.getSourceManager();
10719   if (isLiteralZero(SizeArg) &&
10720       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10721 
10722     SourceLocation DiagLoc = SizeArg->getExprLoc();
10723 
10724     // Some platforms #define bzero to __builtin_memset. See if this is the
10725     // case, and if so, emit a better diagnostic.
10726     if (BId == Builtin::BIbzero ||
10727         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10728                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10729       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10730       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10731     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10732       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10733       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10734     }
10735     return;
10736   }
10737 
10738   // If the second argument to a memset is a sizeof expression and the third
10739   // isn't, this is also likely an error. This should catch
10740   // 'memset(buf, sizeof(buf), 0xff)'.
10741   if (BId == Builtin::BImemset &&
10742       doesExprLikelyComputeSize(Call->getArg(1)) &&
10743       !doesExprLikelyComputeSize(Call->getArg(2))) {
10744     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10745     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10746     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10747     return;
10748   }
10749 }
10750 
10751 /// Check for dangerous or invalid arguments to memset().
10752 ///
10753 /// This issues warnings on known problematic, dangerous or unspecified
10754 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10755 /// function calls.
10756 ///
10757 /// \param Call The call expression to diagnose.
10758 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10759                                    unsigned BId,
10760                                    IdentifierInfo *FnName) {
10761   assert(BId != 0);
10762 
10763   // It is possible to have a non-standard definition of memset.  Validate
10764   // we have enough arguments, and if not, abort further checking.
10765   unsigned ExpectedNumArgs =
10766       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10767   if (Call->getNumArgs() < ExpectedNumArgs)
10768     return;
10769 
10770   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10771                       BId == Builtin::BIstrndup ? 1 : 2);
10772   unsigned LenArg =
10773       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10774   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10775 
10776   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10777                                      Call->getBeginLoc(), Call->getRParenLoc()))
10778     return;
10779 
10780   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10781   CheckMemaccessSize(*this, BId, Call);
10782 
10783   // We have special checking when the length is a sizeof expression.
10784   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10785   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10786   llvm::FoldingSetNodeID SizeOfArgID;
10787 
10788   // Although widely used, 'bzero' is not a standard function. Be more strict
10789   // with the argument types before allowing diagnostics and only allow the
10790   // form bzero(ptr, sizeof(...)).
10791   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10792   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10793     return;
10794 
10795   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10796     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10797     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10798 
10799     QualType DestTy = Dest->getType();
10800     QualType PointeeTy;
10801     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10802       PointeeTy = DestPtrTy->getPointeeType();
10803 
10804       // Never warn about void type pointers. This can be used to suppress
10805       // false positives.
10806       if (PointeeTy->isVoidType())
10807         continue;
10808 
10809       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10810       // actually comparing the expressions for equality. Because computing the
10811       // expression IDs can be expensive, we only do this if the diagnostic is
10812       // enabled.
10813       if (SizeOfArg &&
10814           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10815                            SizeOfArg->getExprLoc())) {
10816         // We only compute IDs for expressions if the warning is enabled, and
10817         // cache the sizeof arg's ID.
10818         if (SizeOfArgID == llvm::FoldingSetNodeID())
10819           SizeOfArg->Profile(SizeOfArgID, Context, true);
10820         llvm::FoldingSetNodeID DestID;
10821         Dest->Profile(DestID, Context, true);
10822         if (DestID == SizeOfArgID) {
10823           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10824           //       over sizeof(src) as well.
10825           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10826           StringRef ReadableName = FnName->getName();
10827 
10828           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10829             if (UnaryOp->getOpcode() == UO_AddrOf)
10830               ActionIdx = 1; // If its an address-of operator, just remove it.
10831           if (!PointeeTy->isIncompleteType() &&
10832               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10833             ActionIdx = 2; // If the pointee's size is sizeof(char),
10834                            // suggest an explicit length.
10835 
10836           // If the function is defined as a builtin macro, do not show macro
10837           // expansion.
10838           SourceLocation SL = SizeOfArg->getExprLoc();
10839           SourceRange DSR = Dest->getSourceRange();
10840           SourceRange SSR = SizeOfArg->getSourceRange();
10841           SourceManager &SM = getSourceManager();
10842 
10843           if (SM.isMacroArgExpansion(SL)) {
10844             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10845             SL = SM.getSpellingLoc(SL);
10846             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10847                              SM.getSpellingLoc(DSR.getEnd()));
10848             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10849                              SM.getSpellingLoc(SSR.getEnd()));
10850           }
10851 
10852           DiagRuntimeBehavior(SL, SizeOfArg,
10853                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10854                                 << ReadableName
10855                                 << PointeeTy
10856                                 << DestTy
10857                                 << DSR
10858                                 << SSR);
10859           DiagRuntimeBehavior(SL, SizeOfArg,
10860                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10861                                 << ActionIdx
10862                                 << SSR);
10863 
10864           break;
10865         }
10866       }
10867 
10868       // Also check for cases where the sizeof argument is the exact same
10869       // type as the memory argument, and where it points to a user-defined
10870       // record type.
10871       if (SizeOfArgTy != QualType()) {
10872         if (PointeeTy->isRecordType() &&
10873             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10874           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10875                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10876                                 << FnName << SizeOfArgTy << ArgIdx
10877                                 << PointeeTy << Dest->getSourceRange()
10878                                 << LenExpr->getSourceRange());
10879           break;
10880         }
10881       }
10882     } else if (DestTy->isArrayType()) {
10883       PointeeTy = DestTy;
10884     }
10885 
10886     if (PointeeTy == QualType())
10887       continue;
10888 
10889     // Always complain about dynamic classes.
10890     bool IsContained;
10891     if (const CXXRecordDecl *ContainedRD =
10892             getContainedDynamicClass(PointeeTy, IsContained)) {
10893 
10894       unsigned OperationType = 0;
10895       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10896       // "overwritten" if we're warning about the destination for any call
10897       // but memcmp; otherwise a verb appropriate to the call.
10898       if (ArgIdx != 0 || IsCmp) {
10899         if (BId == Builtin::BImemcpy)
10900           OperationType = 1;
10901         else if(BId == Builtin::BImemmove)
10902           OperationType = 2;
10903         else if (IsCmp)
10904           OperationType = 3;
10905       }
10906 
10907       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10908                           PDiag(diag::warn_dyn_class_memaccess)
10909                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10910                               << IsContained << ContainedRD << OperationType
10911                               << Call->getCallee()->getSourceRange());
10912     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10913              BId != Builtin::BImemset)
10914       DiagRuntimeBehavior(
10915         Dest->getExprLoc(), Dest,
10916         PDiag(diag::warn_arc_object_memaccess)
10917           << ArgIdx << FnName << PointeeTy
10918           << Call->getCallee()->getSourceRange());
10919     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10920       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10921           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10922         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10923                             PDiag(diag::warn_cstruct_memaccess)
10924                                 << ArgIdx << FnName << PointeeTy << 0);
10925         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10926       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10927                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10928         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10929                             PDiag(diag::warn_cstruct_memaccess)
10930                                 << ArgIdx << FnName << PointeeTy << 1);
10931         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10932       } else {
10933         continue;
10934       }
10935     } else
10936       continue;
10937 
10938     DiagRuntimeBehavior(
10939       Dest->getExprLoc(), Dest,
10940       PDiag(diag::note_bad_memaccess_silence)
10941         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10942     break;
10943   }
10944 }
10945 
10946 // A little helper routine: ignore addition and subtraction of integer literals.
10947 // This intentionally does not ignore all integer constant expressions because
10948 // we don't want to remove sizeof().
10949 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10950   Ex = Ex->IgnoreParenCasts();
10951 
10952   while (true) {
10953     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10954     if (!BO || !BO->isAdditiveOp())
10955       break;
10956 
10957     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10958     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10959 
10960     if (isa<IntegerLiteral>(RHS))
10961       Ex = LHS;
10962     else if (isa<IntegerLiteral>(LHS))
10963       Ex = RHS;
10964     else
10965       break;
10966   }
10967 
10968   return Ex;
10969 }
10970 
10971 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10972                                                       ASTContext &Context) {
10973   // Only handle constant-sized or VLAs, but not flexible members.
10974   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10975     // Only issue the FIXIT for arrays of size > 1.
10976     if (CAT->getSize().getSExtValue() <= 1)
10977       return false;
10978   } else if (!Ty->isVariableArrayType()) {
10979     return false;
10980   }
10981   return true;
10982 }
10983 
10984 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10985 // be the size of the source, instead of the destination.
10986 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10987                                     IdentifierInfo *FnName) {
10988 
10989   // Don't crash if the user has the wrong number of arguments
10990   unsigned NumArgs = Call->getNumArgs();
10991   if ((NumArgs != 3) && (NumArgs != 4))
10992     return;
10993 
10994   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10995   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10996   const Expr *CompareWithSrc = nullptr;
10997 
10998   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10999                                      Call->getBeginLoc(), Call->getRParenLoc()))
11000     return;
11001 
11002   // Look for 'strlcpy(dst, x, sizeof(x))'
11003   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
11004     CompareWithSrc = Ex;
11005   else {
11006     // Look for 'strlcpy(dst, x, strlen(x))'
11007     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11008       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11009           SizeCall->getNumArgs() == 1)
11010         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
11011     }
11012   }
11013 
11014   if (!CompareWithSrc)
11015     return;
11016 
11017   // Determine if the argument to sizeof/strlen is equal to the source
11018   // argument.  In principle there's all kinds of things you could do
11019   // here, for instance creating an == expression and evaluating it with
11020   // EvaluateAsBooleanCondition, but this uses a more direct technique:
11021   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11022   if (!SrcArgDRE)
11023     return;
11024 
11025   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11026   if (!CompareWithSrcDRE ||
11027       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11028     return;
11029 
11030   const Expr *OriginalSizeArg = Call->getArg(2);
11031   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11032       << OriginalSizeArg->getSourceRange() << FnName;
11033 
11034   // Output a FIXIT hint if the destination is an array (rather than a
11035   // pointer to an array).  This could be enhanced to handle some
11036   // pointers if we know the actual size, like if DstArg is 'array+2'
11037   // we could say 'sizeof(array)-2'.
11038   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
11039   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
11040     return;
11041 
11042   SmallString<128> sizeString;
11043   llvm::raw_svector_ostream OS(sizeString);
11044   OS << "sizeof(";
11045   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11046   OS << ")";
11047 
11048   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
11049       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
11050                                       OS.str());
11051 }
11052 
11053 /// Check if two expressions refer to the same declaration.
11054 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11055   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11056     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11057       return D1->getDecl() == D2->getDecl();
11058   return false;
11059 }
11060 
11061 static const Expr *getStrlenExprArg(const Expr *E) {
11062   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11063     const FunctionDecl *FD = CE->getDirectCallee();
11064     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11065       return nullptr;
11066     return CE->getArg(0)->IgnoreParenCasts();
11067   }
11068   return nullptr;
11069 }
11070 
11071 // Warn on anti-patterns as the 'size' argument to strncat.
11072 // The correct size argument should look like following:
11073 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
11074 void Sema::CheckStrncatArguments(const CallExpr *CE,
11075                                  IdentifierInfo *FnName) {
11076   // Don't crash if the user has the wrong number of arguments.
11077   if (CE->getNumArgs() < 3)
11078     return;
11079   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11080   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11081   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11082 
11083   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11084                                      CE->getRParenLoc()))
11085     return;
11086 
11087   // Identify common expressions, which are wrongly used as the size argument
11088   // to strncat and may lead to buffer overflows.
11089   unsigned PatternType = 0;
11090   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11091     // - sizeof(dst)
11092     if (referToTheSameDecl(SizeOfArg, DstArg))
11093       PatternType = 1;
11094     // - sizeof(src)
11095     else if (referToTheSameDecl(SizeOfArg, SrcArg))
11096       PatternType = 2;
11097   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11098     if (BE->getOpcode() == BO_Sub) {
11099       const Expr *L = BE->getLHS()->IgnoreParenCasts();
11100       const Expr *R = BE->getRHS()->IgnoreParenCasts();
11101       // - sizeof(dst) - strlen(dst)
11102       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11103           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
11104         PatternType = 1;
11105       // - sizeof(src) - (anything)
11106       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11107         PatternType = 2;
11108     }
11109   }
11110 
11111   if (PatternType == 0)
11112     return;
11113 
11114   // Generate the diagnostic.
11115   SourceLocation SL = LenArg->getBeginLoc();
11116   SourceRange SR = LenArg->getSourceRange();
11117   SourceManager &SM = getSourceManager();
11118 
11119   // If the function is defined as a builtin macro, do not show macro expansion.
11120   if (SM.isMacroArgExpansion(SL)) {
11121     SL = SM.getSpellingLoc(SL);
11122     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11123                      SM.getSpellingLoc(SR.getEnd()));
11124   }
11125 
11126   // Check if the destination is an array (rather than a pointer to an array).
11127   QualType DstTy = DstArg->getType();
11128   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11129                                                                     Context);
11130   if (!isKnownSizeArray) {
11131     if (PatternType == 1)
11132       Diag(SL, diag::warn_strncat_wrong_size) << SR;
11133     else
11134       Diag(SL, diag::warn_strncat_src_size) << SR;
11135     return;
11136   }
11137 
11138   if (PatternType == 1)
11139     Diag(SL, diag::warn_strncat_large_size) << SR;
11140   else
11141     Diag(SL, diag::warn_strncat_src_size) << SR;
11142 
11143   SmallString<128> sizeString;
11144   llvm::raw_svector_ostream OS(sizeString);
11145   OS << "sizeof(";
11146   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11147   OS << ") - ";
11148   OS << "strlen(";
11149   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11150   OS << ") - 1";
11151 
11152   Diag(SL, diag::note_strncat_wrong_size)
11153     << FixItHint::CreateReplacement(SR, OS.str());
11154 }
11155 
11156 namespace {
11157 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11158                                 const UnaryOperator *UnaryExpr, const Decl *D) {
11159   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
11160     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11161         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11162     return;
11163   }
11164 }
11165 
11166 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11167                                  const UnaryOperator *UnaryExpr) {
11168   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11169     const Decl *D = Lvalue->getDecl();
11170     if (isa<DeclaratorDecl>(D))
11171       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
11172         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11173   }
11174 
11175   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11176     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11177                                       Lvalue->getMemberDecl());
11178 }
11179 
11180 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11181                             const UnaryOperator *UnaryExpr) {
11182   const auto *Lambda = dyn_cast<LambdaExpr>(
11183       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11184   if (!Lambda)
11185     return;
11186 
11187   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11188       << CalleeName << 2 /*object: lambda expression*/;
11189 }
11190 
11191 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11192                                   const DeclRefExpr *Lvalue) {
11193   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11194   if (Var == nullptr)
11195     return;
11196 
11197   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11198       << CalleeName << 0 /*object: */ << Var;
11199 }
11200 
11201 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11202                             const CastExpr *Cast) {
11203   SmallString<128> SizeString;
11204   llvm::raw_svector_ostream OS(SizeString);
11205 
11206   clang::CastKind Kind = Cast->getCastKind();
11207   if (Kind == clang::CK_BitCast &&
11208       !Cast->getSubExpr()->getType()->isFunctionPointerType())
11209     return;
11210   if (Kind == clang::CK_IntegralToPointer &&
11211       !isa<IntegerLiteral>(
11212           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11213     return;
11214 
11215   switch (Cast->getCastKind()) {
11216   case clang::CK_BitCast:
11217   case clang::CK_IntegralToPointer:
11218   case clang::CK_FunctionToPointerDecay:
11219     OS << '\'';
11220     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11221     OS << '\'';
11222     break;
11223   default:
11224     return;
11225   }
11226 
11227   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11228       << CalleeName << 0 /*object: */ << OS.str();
11229 }
11230 } // namespace
11231 
11232 /// Alerts the user that they are attempting to free a non-malloc'd object.
11233 void Sema::CheckFreeArguments(const CallExpr *E) {
11234   const std::string CalleeName =
11235       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11236 
11237   { // Prefer something that doesn't involve a cast to make things simpler.
11238     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11239     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11240       switch (UnaryExpr->getOpcode()) {
11241       case UnaryOperator::Opcode::UO_AddrOf:
11242         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11243       case UnaryOperator::Opcode::UO_Plus:
11244         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11245       default:
11246         break;
11247       }
11248 
11249     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11250       if (Lvalue->getType()->isArrayType())
11251         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11252 
11253     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11254       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11255           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11256       return;
11257     }
11258 
11259     if (isa<BlockExpr>(Arg)) {
11260       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11261           << CalleeName << 1 /*object: block*/;
11262       return;
11263     }
11264   }
11265   // Maybe the cast was important, check after the other cases.
11266   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11267     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11268 }
11269 
11270 void
11271 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11272                          SourceLocation ReturnLoc,
11273                          bool isObjCMethod,
11274                          const AttrVec *Attrs,
11275                          const FunctionDecl *FD) {
11276   // Check if the return value is null but should not be.
11277   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11278        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
11279       CheckNonNullExpr(*this, RetValExp))
11280     Diag(ReturnLoc, diag::warn_null_ret)
11281       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11282 
11283   // C++11 [basic.stc.dynamic.allocation]p4:
11284   //   If an allocation function declared with a non-throwing
11285   //   exception-specification fails to allocate storage, it shall return
11286   //   a null pointer. Any other allocation function that fails to allocate
11287   //   storage shall indicate failure only by throwing an exception [...]
11288   if (FD) {
11289     OverloadedOperatorKind Op = FD->getOverloadedOperator();
11290     if (Op == OO_New || Op == OO_Array_New) {
11291       const FunctionProtoType *Proto
11292         = FD->getType()->castAs<FunctionProtoType>();
11293       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11294           CheckNonNullExpr(*this, RetValExp))
11295         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11296           << FD << getLangOpts().CPlusPlus11;
11297     }
11298   }
11299 
11300   // PPC MMA non-pointer types are not allowed as return type. Checking the type
11301   // here prevent the user from using a PPC MMA type as trailing return type.
11302   if (Context.getTargetInfo().getTriple().isPPC64())
11303     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11304 }
11305 
11306 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
11307 
11308 /// Check for comparisons of floating point operands using != and ==.
11309 /// Issue a warning if these are no self-comparisons, as they are not likely
11310 /// to do what the programmer intended.
11311 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
11312   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
11313   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
11314 
11315   // Special case: check for x == x (which is OK).
11316   // Do not emit warnings for such cases.
11317   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11318     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11319       if (DRL->getDecl() == DRR->getDecl())
11320         return;
11321 
11322   // Special case: check for comparisons against literals that can be exactly
11323   //  represented by APFloat.  In such cases, do not emit a warning.  This
11324   //  is a heuristic: often comparison against such literals are used to
11325   //  detect if a value in a variable has not changed.  This clearly can
11326   //  lead to false negatives.
11327   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11328     if (FLL->isExact())
11329       return;
11330   } else
11331     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11332       if (FLR->isExact())
11333         return;
11334 
11335   // Check for comparisons with builtin types.
11336   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11337     if (CL->getBuiltinCallee())
11338       return;
11339 
11340   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11341     if (CR->getBuiltinCallee())
11342       return;
11343 
11344   // Emit the diagnostic.
11345   Diag(Loc, diag::warn_floatingpoint_eq)
11346     << LHS->getSourceRange() << RHS->getSourceRange();
11347 }
11348 
11349 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11350 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11351 
11352 namespace {
11353 
11354 /// Structure recording the 'active' range of an integer-valued
11355 /// expression.
11356 struct IntRange {
11357   /// The number of bits active in the int. Note that this includes exactly one
11358   /// sign bit if !NonNegative.
11359   unsigned Width;
11360 
11361   /// True if the int is known not to have negative values. If so, all leading
11362   /// bits before Width are known zero, otherwise they are known to be the
11363   /// same as the MSB within Width.
11364   bool NonNegative;
11365 
11366   IntRange(unsigned Width, bool NonNegative)
11367       : Width(Width), NonNegative(NonNegative) {}
11368 
11369   /// Number of bits excluding the sign bit.
11370   unsigned valueBits() const {
11371     return NonNegative ? Width : Width - 1;
11372   }
11373 
11374   /// Returns the range of the bool type.
11375   static IntRange forBoolType() {
11376     return IntRange(1, true);
11377   }
11378 
11379   /// Returns the range of an opaque value of the given integral type.
11380   static IntRange forValueOfType(ASTContext &C, QualType T) {
11381     return forValueOfCanonicalType(C,
11382                           T->getCanonicalTypeInternal().getTypePtr());
11383   }
11384 
11385   /// Returns the range of an opaque value of a canonical integral type.
11386   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11387     assert(T->isCanonicalUnqualified());
11388 
11389     if (const VectorType *VT = dyn_cast<VectorType>(T))
11390       T = VT->getElementType().getTypePtr();
11391     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11392       T = CT->getElementType().getTypePtr();
11393     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11394       T = AT->getValueType().getTypePtr();
11395 
11396     if (!C.getLangOpts().CPlusPlus) {
11397       // For enum types in C code, use the underlying datatype.
11398       if (const EnumType *ET = dyn_cast<EnumType>(T))
11399         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11400     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11401       // For enum types in C++, use the known bit width of the enumerators.
11402       EnumDecl *Enum = ET->getDecl();
11403       // In C++11, enums can have a fixed underlying type. Use this type to
11404       // compute the range.
11405       if (Enum->isFixed()) {
11406         return IntRange(C.getIntWidth(QualType(T, 0)),
11407                         !ET->isSignedIntegerOrEnumerationType());
11408       }
11409 
11410       unsigned NumPositive = Enum->getNumPositiveBits();
11411       unsigned NumNegative = Enum->getNumNegativeBits();
11412 
11413       if (NumNegative == 0)
11414         return IntRange(NumPositive, true/*NonNegative*/);
11415       else
11416         return IntRange(std::max(NumPositive + 1, NumNegative),
11417                         false/*NonNegative*/);
11418     }
11419 
11420     if (const auto *EIT = dyn_cast<BitIntType>(T))
11421       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11422 
11423     const BuiltinType *BT = cast<BuiltinType>(T);
11424     assert(BT->isInteger());
11425 
11426     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11427   }
11428 
11429   /// Returns the "target" range of a canonical integral type, i.e.
11430   /// the range of values expressible in the type.
11431   ///
11432   /// This matches forValueOfCanonicalType except that enums have the
11433   /// full range of their type, not the range of their enumerators.
11434   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11435     assert(T->isCanonicalUnqualified());
11436 
11437     if (const VectorType *VT = dyn_cast<VectorType>(T))
11438       T = VT->getElementType().getTypePtr();
11439     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11440       T = CT->getElementType().getTypePtr();
11441     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11442       T = AT->getValueType().getTypePtr();
11443     if (const EnumType *ET = dyn_cast<EnumType>(T))
11444       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11445 
11446     if (const auto *EIT = dyn_cast<BitIntType>(T))
11447       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11448 
11449     const BuiltinType *BT = cast<BuiltinType>(T);
11450     assert(BT->isInteger());
11451 
11452     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11453   }
11454 
11455   /// Returns the supremum of two ranges: i.e. their conservative merge.
11456   static IntRange join(IntRange L, IntRange R) {
11457     bool Unsigned = L.NonNegative && R.NonNegative;
11458     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11459                     L.NonNegative && R.NonNegative);
11460   }
11461 
11462   /// Return the range of a bitwise-AND of the two ranges.
11463   static IntRange bit_and(IntRange L, IntRange R) {
11464     unsigned Bits = std::max(L.Width, R.Width);
11465     bool NonNegative = false;
11466     if (L.NonNegative) {
11467       Bits = std::min(Bits, L.Width);
11468       NonNegative = true;
11469     }
11470     if (R.NonNegative) {
11471       Bits = std::min(Bits, R.Width);
11472       NonNegative = true;
11473     }
11474     return IntRange(Bits, NonNegative);
11475   }
11476 
11477   /// Return the range of a sum of the two ranges.
11478   static IntRange sum(IntRange L, IntRange R) {
11479     bool Unsigned = L.NonNegative && R.NonNegative;
11480     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11481                     Unsigned);
11482   }
11483 
11484   /// Return the range of a difference of the two ranges.
11485   static IntRange difference(IntRange L, IntRange R) {
11486     // We need a 1-bit-wider range if:
11487     //   1) LHS can be negative: least value can be reduced.
11488     //   2) RHS can be negative: greatest value can be increased.
11489     bool CanWiden = !L.NonNegative || !R.NonNegative;
11490     bool Unsigned = L.NonNegative && R.Width == 0;
11491     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11492                         !Unsigned,
11493                     Unsigned);
11494   }
11495 
11496   /// Return the range of a product of the two ranges.
11497   static IntRange product(IntRange L, IntRange R) {
11498     // If both LHS and RHS can be negative, we can form
11499     //   -2^L * -2^R = 2^(L + R)
11500     // which requires L + R + 1 value bits to represent.
11501     bool CanWiden = !L.NonNegative && !R.NonNegative;
11502     bool Unsigned = L.NonNegative && R.NonNegative;
11503     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11504                     Unsigned);
11505   }
11506 
11507   /// Return the range of a remainder operation between the two ranges.
11508   static IntRange rem(IntRange L, IntRange R) {
11509     // The result of a remainder can't be larger than the result of
11510     // either side. The sign of the result is the sign of the LHS.
11511     bool Unsigned = L.NonNegative;
11512     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11513                     Unsigned);
11514   }
11515 };
11516 
11517 } // namespace
11518 
11519 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11520                               unsigned MaxWidth) {
11521   if (value.isSigned() && value.isNegative())
11522     return IntRange(value.getMinSignedBits(), false);
11523 
11524   if (value.getBitWidth() > MaxWidth)
11525     value = value.trunc(MaxWidth);
11526 
11527   // isNonNegative() just checks the sign bit without considering
11528   // signedness.
11529   return IntRange(value.getActiveBits(), true);
11530 }
11531 
11532 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11533                               unsigned MaxWidth) {
11534   if (result.isInt())
11535     return GetValueRange(C, result.getInt(), MaxWidth);
11536 
11537   if (result.isVector()) {
11538     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11539     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11540       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11541       R = IntRange::join(R, El);
11542     }
11543     return R;
11544   }
11545 
11546   if (result.isComplexInt()) {
11547     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11548     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11549     return IntRange::join(R, I);
11550   }
11551 
11552   // This can happen with lossless casts to intptr_t of "based" lvalues.
11553   // Assume it might use arbitrary bits.
11554   // FIXME: The only reason we need to pass the type in here is to get
11555   // the sign right on this one case.  It would be nice if APValue
11556   // preserved this.
11557   assert(result.isLValue() || result.isAddrLabelDiff());
11558   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11559 }
11560 
11561 static QualType GetExprType(const Expr *E) {
11562   QualType Ty = E->getType();
11563   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11564     Ty = AtomicRHS->getValueType();
11565   return Ty;
11566 }
11567 
11568 /// Pseudo-evaluate the given integer expression, estimating the
11569 /// range of values it might take.
11570 ///
11571 /// \param MaxWidth The width to which the value will be truncated.
11572 /// \param Approximate If \c true, return a likely range for the result: in
11573 ///        particular, assume that arithmetic on narrower types doesn't leave
11574 ///        those types. If \c false, return a range including all possible
11575 ///        result values.
11576 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11577                              bool InConstantContext, bool Approximate) {
11578   E = E->IgnoreParens();
11579 
11580   // Try a full evaluation first.
11581   Expr::EvalResult result;
11582   if (E->EvaluateAsRValue(result, C, InConstantContext))
11583     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11584 
11585   // I think we only want to look through implicit casts here; if the
11586   // user has an explicit widening cast, we should treat the value as
11587   // being of the new, wider type.
11588   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11589     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11590       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11591                           Approximate);
11592 
11593     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11594 
11595     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11596                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11597 
11598     // Assume that non-integer casts can span the full range of the type.
11599     if (!isIntegerCast)
11600       return OutputTypeRange;
11601 
11602     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11603                                      std::min(MaxWidth, OutputTypeRange.Width),
11604                                      InConstantContext, Approximate);
11605 
11606     // Bail out if the subexpr's range is as wide as the cast type.
11607     if (SubRange.Width >= OutputTypeRange.Width)
11608       return OutputTypeRange;
11609 
11610     // Otherwise, we take the smaller width, and we're non-negative if
11611     // either the output type or the subexpr is.
11612     return IntRange(SubRange.Width,
11613                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11614   }
11615 
11616   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11617     // If we can fold the condition, just take that operand.
11618     bool CondResult;
11619     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11620       return GetExprRange(C,
11621                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11622                           MaxWidth, InConstantContext, Approximate);
11623 
11624     // Otherwise, conservatively merge.
11625     // GetExprRange requires an integer expression, but a throw expression
11626     // results in a void type.
11627     Expr *E = CO->getTrueExpr();
11628     IntRange L = E->getType()->isVoidType()
11629                      ? IntRange{0, true}
11630                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11631     E = CO->getFalseExpr();
11632     IntRange R = E->getType()->isVoidType()
11633                      ? IntRange{0, true}
11634                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11635     return IntRange::join(L, R);
11636   }
11637 
11638   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11639     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11640 
11641     switch (BO->getOpcode()) {
11642     case BO_Cmp:
11643       llvm_unreachable("builtin <=> should have class type");
11644 
11645     // Boolean-valued operations are single-bit and positive.
11646     case BO_LAnd:
11647     case BO_LOr:
11648     case BO_LT:
11649     case BO_GT:
11650     case BO_LE:
11651     case BO_GE:
11652     case BO_EQ:
11653     case BO_NE:
11654       return IntRange::forBoolType();
11655 
11656     // The type of the assignments is the type of the LHS, so the RHS
11657     // is not necessarily the same type.
11658     case BO_MulAssign:
11659     case BO_DivAssign:
11660     case BO_RemAssign:
11661     case BO_AddAssign:
11662     case BO_SubAssign:
11663     case BO_XorAssign:
11664     case BO_OrAssign:
11665       // TODO: bitfields?
11666       return IntRange::forValueOfType(C, GetExprType(E));
11667 
11668     // Simple assignments just pass through the RHS, which will have
11669     // been coerced to the LHS type.
11670     case BO_Assign:
11671       // TODO: bitfields?
11672       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11673                           Approximate);
11674 
11675     // Operations with opaque sources are black-listed.
11676     case BO_PtrMemD:
11677     case BO_PtrMemI:
11678       return IntRange::forValueOfType(C, GetExprType(E));
11679 
11680     // Bitwise-and uses the *infinum* of the two source ranges.
11681     case BO_And:
11682     case BO_AndAssign:
11683       Combine = IntRange::bit_and;
11684       break;
11685 
11686     // Left shift gets black-listed based on a judgement call.
11687     case BO_Shl:
11688       // ...except that we want to treat '1 << (blah)' as logically
11689       // positive.  It's an important idiom.
11690       if (IntegerLiteral *I
11691             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11692         if (I->getValue() == 1) {
11693           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11694           return IntRange(R.Width, /*NonNegative*/ true);
11695         }
11696       }
11697       LLVM_FALLTHROUGH;
11698 
11699     case BO_ShlAssign:
11700       return IntRange::forValueOfType(C, GetExprType(E));
11701 
11702     // Right shift by a constant can narrow its left argument.
11703     case BO_Shr:
11704     case BO_ShrAssign: {
11705       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11706                                 Approximate);
11707 
11708       // If the shift amount is a positive constant, drop the width by
11709       // that much.
11710       if (Optional<llvm::APSInt> shift =
11711               BO->getRHS()->getIntegerConstantExpr(C)) {
11712         if (shift->isNonNegative()) {
11713           unsigned zext = shift->getZExtValue();
11714           if (zext >= L.Width)
11715             L.Width = (L.NonNegative ? 0 : 1);
11716           else
11717             L.Width -= zext;
11718         }
11719       }
11720 
11721       return L;
11722     }
11723 
11724     // Comma acts as its right operand.
11725     case BO_Comma:
11726       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11727                           Approximate);
11728 
11729     case BO_Add:
11730       if (!Approximate)
11731         Combine = IntRange::sum;
11732       break;
11733 
11734     case BO_Sub:
11735       if (BO->getLHS()->getType()->isPointerType())
11736         return IntRange::forValueOfType(C, GetExprType(E));
11737       if (!Approximate)
11738         Combine = IntRange::difference;
11739       break;
11740 
11741     case BO_Mul:
11742       if (!Approximate)
11743         Combine = IntRange::product;
11744       break;
11745 
11746     // The width of a division result is mostly determined by the size
11747     // of the LHS.
11748     case BO_Div: {
11749       // Don't 'pre-truncate' the operands.
11750       unsigned opWidth = C.getIntWidth(GetExprType(E));
11751       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11752                                 Approximate);
11753 
11754       // If the divisor is constant, use that.
11755       if (Optional<llvm::APSInt> divisor =
11756               BO->getRHS()->getIntegerConstantExpr(C)) {
11757         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11758         if (log2 >= L.Width)
11759           L.Width = (L.NonNegative ? 0 : 1);
11760         else
11761           L.Width = std::min(L.Width - log2, MaxWidth);
11762         return L;
11763       }
11764 
11765       // Otherwise, just use the LHS's width.
11766       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11767       // could be -1.
11768       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11769                                 Approximate);
11770       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11771     }
11772 
11773     case BO_Rem:
11774       Combine = IntRange::rem;
11775       break;
11776 
11777     // The default behavior is okay for these.
11778     case BO_Xor:
11779     case BO_Or:
11780       break;
11781     }
11782 
11783     // Combine the two ranges, but limit the result to the type in which we
11784     // performed the computation.
11785     QualType T = GetExprType(E);
11786     unsigned opWidth = C.getIntWidth(T);
11787     IntRange L =
11788         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11789     IntRange R =
11790         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11791     IntRange C = Combine(L, R);
11792     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11793     C.Width = std::min(C.Width, MaxWidth);
11794     return C;
11795   }
11796 
11797   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11798     switch (UO->getOpcode()) {
11799     // Boolean-valued operations are white-listed.
11800     case UO_LNot:
11801       return IntRange::forBoolType();
11802 
11803     // Operations with opaque sources are black-listed.
11804     case UO_Deref:
11805     case UO_AddrOf: // should be impossible
11806       return IntRange::forValueOfType(C, GetExprType(E));
11807 
11808     default:
11809       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11810                           Approximate);
11811     }
11812   }
11813 
11814   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11815     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11816                         Approximate);
11817 
11818   if (const auto *BitField = E->getSourceBitField())
11819     return IntRange(BitField->getBitWidthValue(C),
11820                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11821 
11822   return IntRange::forValueOfType(C, GetExprType(E));
11823 }
11824 
11825 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11826                              bool InConstantContext, bool Approximate) {
11827   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11828                       Approximate);
11829 }
11830 
11831 /// Checks whether the given value, which currently has the given
11832 /// source semantics, has the same value when coerced through the
11833 /// target semantics.
11834 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11835                                  const llvm::fltSemantics &Src,
11836                                  const llvm::fltSemantics &Tgt) {
11837   llvm::APFloat truncated = value;
11838 
11839   bool ignored;
11840   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11841   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11842 
11843   return truncated.bitwiseIsEqual(value);
11844 }
11845 
11846 /// Checks whether the given value, which currently has the given
11847 /// source semantics, has the same value when coerced through the
11848 /// target semantics.
11849 ///
11850 /// The value might be a vector of floats (or a complex number).
11851 static bool IsSameFloatAfterCast(const APValue &value,
11852                                  const llvm::fltSemantics &Src,
11853                                  const llvm::fltSemantics &Tgt) {
11854   if (value.isFloat())
11855     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11856 
11857   if (value.isVector()) {
11858     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11859       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11860         return false;
11861     return true;
11862   }
11863 
11864   assert(value.isComplexFloat());
11865   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11866           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11867 }
11868 
11869 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11870                                        bool IsListInit = false);
11871 
11872 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11873   // Suppress cases where we are comparing against an enum constant.
11874   if (const DeclRefExpr *DR =
11875       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11876     if (isa<EnumConstantDecl>(DR->getDecl()))
11877       return true;
11878 
11879   // Suppress cases where the value is expanded from a macro, unless that macro
11880   // is how a language represents a boolean literal. This is the case in both C
11881   // and Objective-C.
11882   SourceLocation BeginLoc = E->getBeginLoc();
11883   if (BeginLoc.isMacroID()) {
11884     StringRef MacroName = Lexer::getImmediateMacroName(
11885         BeginLoc, S.getSourceManager(), S.getLangOpts());
11886     return MacroName != "YES" && MacroName != "NO" &&
11887            MacroName != "true" && MacroName != "false";
11888   }
11889 
11890   return false;
11891 }
11892 
11893 static bool isKnownToHaveUnsignedValue(Expr *E) {
11894   return E->getType()->isIntegerType() &&
11895          (!E->getType()->isSignedIntegerType() ||
11896           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11897 }
11898 
11899 namespace {
11900 /// The promoted range of values of a type. In general this has the
11901 /// following structure:
11902 ///
11903 ///     |-----------| . . . |-----------|
11904 ///     ^           ^       ^           ^
11905 ///    Min       HoleMin  HoleMax      Max
11906 ///
11907 /// ... where there is only a hole if a signed type is promoted to unsigned
11908 /// (in which case Min and Max are the smallest and largest representable
11909 /// values).
11910 struct PromotedRange {
11911   // Min, or HoleMax if there is a hole.
11912   llvm::APSInt PromotedMin;
11913   // Max, or HoleMin if there is a hole.
11914   llvm::APSInt PromotedMax;
11915 
11916   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11917     if (R.Width == 0)
11918       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11919     else if (R.Width >= BitWidth && !Unsigned) {
11920       // Promotion made the type *narrower*. This happens when promoting
11921       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11922       // Treat all values of 'signed int' as being in range for now.
11923       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11924       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11925     } else {
11926       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11927                         .extOrTrunc(BitWidth);
11928       PromotedMin.setIsUnsigned(Unsigned);
11929 
11930       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11931                         .extOrTrunc(BitWidth);
11932       PromotedMax.setIsUnsigned(Unsigned);
11933     }
11934   }
11935 
11936   // Determine whether this range is contiguous (has no hole).
11937   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11938 
11939   // Where a constant value is within the range.
11940   enum ComparisonResult {
11941     LT = 0x1,
11942     LE = 0x2,
11943     GT = 0x4,
11944     GE = 0x8,
11945     EQ = 0x10,
11946     NE = 0x20,
11947     InRangeFlag = 0x40,
11948 
11949     Less = LE | LT | NE,
11950     Min = LE | InRangeFlag,
11951     InRange = InRangeFlag,
11952     Max = GE | InRangeFlag,
11953     Greater = GE | GT | NE,
11954 
11955     OnlyValue = LE | GE | EQ | InRangeFlag,
11956     InHole = NE
11957   };
11958 
11959   ComparisonResult compare(const llvm::APSInt &Value) const {
11960     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11961            Value.isUnsigned() == PromotedMin.isUnsigned());
11962     if (!isContiguous()) {
11963       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11964       if (Value.isMinValue()) return Min;
11965       if (Value.isMaxValue()) return Max;
11966       if (Value >= PromotedMin) return InRange;
11967       if (Value <= PromotedMax) return InRange;
11968       return InHole;
11969     }
11970 
11971     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11972     case -1: return Less;
11973     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11974     case 1:
11975       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11976       case -1: return InRange;
11977       case 0: return Max;
11978       case 1: return Greater;
11979       }
11980     }
11981 
11982     llvm_unreachable("impossible compare result");
11983   }
11984 
11985   static llvm::Optional<StringRef>
11986   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11987     if (Op == BO_Cmp) {
11988       ComparisonResult LTFlag = LT, GTFlag = GT;
11989       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11990 
11991       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11992       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11993       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11994       return llvm::None;
11995     }
11996 
11997     ComparisonResult TrueFlag, FalseFlag;
11998     if (Op == BO_EQ) {
11999       TrueFlag = EQ;
12000       FalseFlag = NE;
12001     } else if (Op == BO_NE) {
12002       TrueFlag = NE;
12003       FalseFlag = EQ;
12004     } else {
12005       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12006         TrueFlag = LT;
12007         FalseFlag = GE;
12008       } else {
12009         TrueFlag = GT;
12010         FalseFlag = LE;
12011       }
12012       if (Op == BO_GE || Op == BO_LE)
12013         std::swap(TrueFlag, FalseFlag);
12014     }
12015     if (R & TrueFlag)
12016       return StringRef("true");
12017     if (R & FalseFlag)
12018       return StringRef("false");
12019     return llvm::None;
12020   }
12021 };
12022 }
12023 
12024 static bool HasEnumType(Expr *E) {
12025   // Strip off implicit integral promotions.
12026   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12027     if (ICE->getCastKind() != CK_IntegralCast &&
12028         ICE->getCastKind() != CK_NoOp)
12029       break;
12030     E = ICE->getSubExpr();
12031   }
12032 
12033   return E->getType()->isEnumeralType();
12034 }
12035 
12036 static int classifyConstantValue(Expr *Constant) {
12037   // The values of this enumeration are used in the diagnostics
12038   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12039   enum ConstantValueKind {
12040     Miscellaneous = 0,
12041     LiteralTrue,
12042     LiteralFalse
12043   };
12044   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12045     return BL->getValue() ? ConstantValueKind::LiteralTrue
12046                           : ConstantValueKind::LiteralFalse;
12047   return ConstantValueKind::Miscellaneous;
12048 }
12049 
12050 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
12051                                         Expr *Constant, Expr *Other,
12052                                         const llvm::APSInt &Value,
12053                                         bool RhsConstant) {
12054   if (S.inTemplateInstantiation())
12055     return false;
12056 
12057   Expr *OriginalOther = Other;
12058 
12059   Constant = Constant->IgnoreParenImpCasts();
12060   Other = Other->IgnoreParenImpCasts();
12061 
12062   // Suppress warnings on tautological comparisons between values of the same
12063   // enumeration type. There are only two ways we could warn on this:
12064   //  - If the constant is outside the range of representable values of
12065   //    the enumeration. In such a case, we should warn about the cast
12066   //    to enumeration type, not about the comparison.
12067   //  - If the constant is the maximum / minimum in-range value. For an
12068   //    enumeratin type, such comparisons can be meaningful and useful.
12069   if (Constant->getType()->isEnumeralType() &&
12070       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12071     return false;
12072 
12073   IntRange OtherValueRange = GetExprRange(
12074       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
12075 
12076   QualType OtherT = Other->getType();
12077   if (const auto *AT = OtherT->getAs<AtomicType>())
12078     OtherT = AT->getValueType();
12079   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12080 
12081   // Special case for ObjC BOOL on targets where its a typedef for a signed char
12082   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12083   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12084                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
12085                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12086 
12087   // Whether we're treating Other as being a bool because of the form of
12088   // expression despite it having another type (typically 'int' in C).
12089   bool OtherIsBooleanDespiteType =
12090       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12091   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12092     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
12093 
12094   // Check if all values in the range of possible values of this expression
12095   // lead to the same comparison outcome.
12096   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
12097                                         Value.isUnsigned());
12098   auto Cmp = OtherPromotedValueRange.compare(Value);
12099   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12100   if (!Result)
12101     return false;
12102 
12103   // Also consider the range determined by the type alone. This allows us to
12104   // classify the warning under the proper diagnostic group.
12105   bool TautologicalTypeCompare = false;
12106   {
12107     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12108                                          Value.isUnsigned());
12109     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12110     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12111                                                        RhsConstant)) {
12112       TautologicalTypeCompare = true;
12113       Cmp = TypeCmp;
12114       Result = TypeResult;
12115     }
12116   }
12117 
12118   // Don't warn if the non-constant operand actually always evaluates to the
12119   // same value.
12120   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
12121     return false;
12122 
12123   // Suppress the diagnostic for an in-range comparison if the constant comes
12124   // from a macro or enumerator. We don't want to diagnose
12125   //
12126   //   some_long_value <= INT_MAX
12127   //
12128   // when sizeof(int) == sizeof(long).
12129   bool InRange = Cmp & PromotedRange::InRangeFlag;
12130   if (InRange && IsEnumConstOrFromMacro(S, Constant))
12131     return false;
12132 
12133   // A comparison of an unsigned bit-field against 0 is really a type problem,
12134   // even though at the type level the bit-field might promote to 'signed int'.
12135   if (Other->refersToBitField() && InRange && Value == 0 &&
12136       Other->getType()->isUnsignedIntegerOrEnumerationType())
12137     TautologicalTypeCompare = true;
12138 
12139   // If this is a comparison to an enum constant, include that
12140   // constant in the diagnostic.
12141   const EnumConstantDecl *ED = nullptr;
12142   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
12143     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12144 
12145   // Should be enough for uint128 (39 decimal digits)
12146   SmallString<64> PrettySourceValue;
12147   llvm::raw_svector_ostream OS(PrettySourceValue);
12148   if (ED) {
12149     OS << '\'' << *ED << "' (" << Value << ")";
12150   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12151                Constant->IgnoreParenImpCasts())) {
12152     OS << (BL->getValue() ? "YES" : "NO");
12153   } else {
12154     OS << Value;
12155   }
12156 
12157   if (!TautologicalTypeCompare) {
12158     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12159         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
12160         << E->getOpcodeStr() << OS.str() << *Result
12161         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12162     return true;
12163   }
12164 
12165   if (IsObjCSignedCharBool) {
12166     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12167                           S.PDiag(diag::warn_tautological_compare_objc_bool)
12168                               << OS.str() << *Result);
12169     return true;
12170   }
12171 
12172   // FIXME: We use a somewhat different formatting for the in-range cases and
12173   // cases involving boolean values for historical reasons. We should pick a
12174   // consistent way of presenting these diagnostics.
12175   if (!InRange || Other->isKnownToHaveBooleanValue()) {
12176 
12177     S.DiagRuntimeBehavior(
12178         E->getOperatorLoc(), E,
12179         S.PDiag(!InRange ? diag::warn_out_of_range_compare
12180                          : diag::warn_tautological_bool_compare)
12181             << OS.str() << classifyConstantValue(Constant) << OtherT
12182             << OtherIsBooleanDespiteType << *Result
12183             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12184   } else {
12185     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12186     unsigned Diag =
12187         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12188             ? (HasEnumType(OriginalOther)
12189                    ? diag::warn_unsigned_enum_always_true_comparison
12190                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12191                               : diag::warn_unsigned_always_true_comparison)
12192             : diag::warn_tautological_constant_compare;
12193 
12194     S.Diag(E->getOperatorLoc(), Diag)
12195         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12196         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12197   }
12198 
12199   return true;
12200 }
12201 
12202 /// Analyze the operands of the given comparison.  Implements the
12203 /// fallback case from AnalyzeComparison.
12204 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12205   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12206   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12207 }
12208 
12209 /// Implements -Wsign-compare.
12210 ///
12211 /// \param E the binary operator to check for warnings
12212 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12213   // The type the comparison is being performed in.
12214   QualType T = E->getLHS()->getType();
12215 
12216   // Only analyze comparison operators where both sides have been converted to
12217   // the same type.
12218   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12219     return AnalyzeImpConvsInComparison(S, E);
12220 
12221   // Don't analyze value-dependent comparisons directly.
12222   if (E->isValueDependent())
12223     return AnalyzeImpConvsInComparison(S, E);
12224 
12225   Expr *LHS = E->getLHS();
12226   Expr *RHS = E->getRHS();
12227 
12228   if (T->isIntegralType(S.Context)) {
12229     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
12230     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
12231 
12232     // We don't care about expressions whose result is a constant.
12233     if (RHSValue && LHSValue)
12234       return AnalyzeImpConvsInComparison(S, E);
12235 
12236     // We only care about expressions where just one side is literal
12237     if ((bool)RHSValue ^ (bool)LHSValue) {
12238       // Is the constant on the RHS or LHS?
12239       const bool RhsConstant = (bool)RHSValue;
12240       Expr *Const = RhsConstant ? RHS : LHS;
12241       Expr *Other = RhsConstant ? LHS : RHS;
12242       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12243 
12244       // Check whether an integer constant comparison results in a value
12245       // of 'true' or 'false'.
12246       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12247         return AnalyzeImpConvsInComparison(S, E);
12248     }
12249   }
12250 
12251   if (!T->hasUnsignedIntegerRepresentation()) {
12252     // We don't do anything special if this isn't an unsigned integral
12253     // comparison:  we're only interested in integral comparisons, and
12254     // signed comparisons only happen in cases we don't care to warn about.
12255     return AnalyzeImpConvsInComparison(S, E);
12256   }
12257 
12258   LHS = LHS->IgnoreParenImpCasts();
12259   RHS = RHS->IgnoreParenImpCasts();
12260 
12261   if (!S.getLangOpts().CPlusPlus) {
12262     // Avoid warning about comparison of integers with different signs when
12263     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12264     // the type of `E`.
12265     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12266       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12267     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12268       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12269   }
12270 
12271   // Check to see if one of the (unmodified) operands is of different
12272   // signedness.
12273   Expr *signedOperand, *unsignedOperand;
12274   if (LHS->getType()->hasSignedIntegerRepresentation()) {
12275     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12276            "unsigned comparison between two signed integer expressions?");
12277     signedOperand = LHS;
12278     unsignedOperand = RHS;
12279   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12280     signedOperand = RHS;
12281     unsignedOperand = LHS;
12282   } else {
12283     return AnalyzeImpConvsInComparison(S, E);
12284   }
12285 
12286   // Otherwise, calculate the effective range of the signed operand.
12287   IntRange signedRange = GetExprRange(
12288       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
12289 
12290   // Go ahead and analyze implicit conversions in the operands.  Note
12291   // that we skip the implicit conversions on both sides.
12292   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
12293   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
12294 
12295   // If the signed range is non-negative, -Wsign-compare won't fire.
12296   if (signedRange.NonNegative)
12297     return;
12298 
12299   // For (in)equality comparisons, if the unsigned operand is a
12300   // constant which cannot collide with a overflowed signed operand,
12301   // then reinterpreting the signed operand as unsigned will not
12302   // change the result of the comparison.
12303   if (E->isEqualityOp()) {
12304     unsigned comparisonWidth = S.Context.getIntWidth(T);
12305     IntRange unsignedRange =
12306         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
12307                      /*Approximate*/ true);
12308 
12309     // We should never be unable to prove that the unsigned operand is
12310     // non-negative.
12311     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
12312 
12313     if (unsignedRange.Width < comparisonWidth)
12314       return;
12315   }
12316 
12317   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12318                         S.PDiag(diag::warn_mixed_sign_comparison)
12319                             << LHS->getType() << RHS->getType()
12320                             << LHS->getSourceRange() << RHS->getSourceRange());
12321 }
12322 
12323 /// Analyzes an attempt to assign the given value to a bitfield.
12324 ///
12325 /// Returns true if there was something fishy about the attempt.
12326 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12327                                       SourceLocation InitLoc) {
12328   assert(Bitfield->isBitField());
12329   if (Bitfield->isInvalidDecl())
12330     return false;
12331 
12332   // White-list bool bitfields.
12333   QualType BitfieldType = Bitfield->getType();
12334   if (BitfieldType->isBooleanType())
12335      return false;
12336 
12337   if (BitfieldType->isEnumeralType()) {
12338     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12339     // If the underlying enum type was not explicitly specified as an unsigned
12340     // type and the enum contain only positive values, MSVC++ will cause an
12341     // inconsistency by storing this as a signed type.
12342     if (S.getLangOpts().CPlusPlus11 &&
12343         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12344         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12345         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12346       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12347           << BitfieldEnumDecl;
12348     }
12349   }
12350 
12351   if (Bitfield->getType()->isBooleanType())
12352     return false;
12353 
12354   // Ignore value- or type-dependent expressions.
12355   if (Bitfield->getBitWidth()->isValueDependent() ||
12356       Bitfield->getBitWidth()->isTypeDependent() ||
12357       Init->isValueDependent() ||
12358       Init->isTypeDependent())
12359     return false;
12360 
12361   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12362   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12363 
12364   Expr::EvalResult Result;
12365   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12366                                    Expr::SE_AllowSideEffects)) {
12367     // The RHS is not constant.  If the RHS has an enum type, make sure the
12368     // bitfield is wide enough to hold all the values of the enum without
12369     // truncation.
12370     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12371       EnumDecl *ED = EnumTy->getDecl();
12372       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12373 
12374       // Enum types are implicitly signed on Windows, so check if there are any
12375       // negative enumerators to see if the enum was intended to be signed or
12376       // not.
12377       bool SignedEnum = ED->getNumNegativeBits() > 0;
12378 
12379       // Check for surprising sign changes when assigning enum values to a
12380       // bitfield of different signedness.  If the bitfield is signed and we
12381       // have exactly the right number of bits to store this unsigned enum,
12382       // suggest changing the enum to an unsigned type. This typically happens
12383       // on Windows where unfixed enums always use an underlying type of 'int'.
12384       unsigned DiagID = 0;
12385       if (SignedEnum && !SignedBitfield) {
12386         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12387       } else if (SignedBitfield && !SignedEnum &&
12388                  ED->getNumPositiveBits() == FieldWidth) {
12389         DiagID = diag::warn_signed_bitfield_enum_conversion;
12390       }
12391 
12392       if (DiagID) {
12393         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12394         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12395         SourceRange TypeRange =
12396             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12397         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12398             << SignedEnum << TypeRange;
12399       }
12400 
12401       // Compute the required bitwidth. If the enum has negative values, we need
12402       // one more bit than the normal number of positive bits to represent the
12403       // sign bit.
12404       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12405                                                   ED->getNumNegativeBits())
12406                                        : ED->getNumPositiveBits();
12407 
12408       // Check the bitwidth.
12409       if (BitsNeeded > FieldWidth) {
12410         Expr *WidthExpr = Bitfield->getBitWidth();
12411         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12412             << Bitfield << ED;
12413         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12414             << BitsNeeded << ED << WidthExpr->getSourceRange();
12415       }
12416     }
12417 
12418     return false;
12419   }
12420 
12421   llvm::APSInt Value = Result.Val.getInt();
12422 
12423   unsigned OriginalWidth = Value.getBitWidth();
12424 
12425   if (!Value.isSigned() || Value.isNegative())
12426     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12427       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12428         OriginalWidth = Value.getMinSignedBits();
12429 
12430   if (OriginalWidth <= FieldWidth)
12431     return false;
12432 
12433   // Compute the value which the bitfield will contain.
12434   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12435   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12436 
12437   // Check whether the stored value is equal to the original value.
12438   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12439   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12440     return false;
12441 
12442   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12443   // therefore don't strictly fit into a signed bitfield of width 1.
12444   if (FieldWidth == 1 && Value == 1)
12445     return false;
12446 
12447   std::string PrettyValue = toString(Value, 10);
12448   std::string PrettyTrunc = toString(TruncatedValue, 10);
12449 
12450   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12451     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12452     << Init->getSourceRange();
12453 
12454   return true;
12455 }
12456 
12457 /// Analyze the given simple or compound assignment for warning-worthy
12458 /// operations.
12459 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12460   // Just recurse on the LHS.
12461   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12462 
12463   // We want to recurse on the RHS as normal unless we're assigning to
12464   // a bitfield.
12465   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12466     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12467                                   E->getOperatorLoc())) {
12468       // Recurse, ignoring any implicit conversions on the RHS.
12469       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12470                                         E->getOperatorLoc());
12471     }
12472   }
12473 
12474   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12475 
12476   // Diagnose implicitly sequentially-consistent atomic assignment.
12477   if (E->getLHS()->getType()->isAtomicType())
12478     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12479 }
12480 
12481 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12482 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12483                             SourceLocation CContext, unsigned diag,
12484                             bool pruneControlFlow = false) {
12485   if (pruneControlFlow) {
12486     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12487                           S.PDiag(diag)
12488                               << SourceType << T << E->getSourceRange()
12489                               << SourceRange(CContext));
12490     return;
12491   }
12492   S.Diag(E->getExprLoc(), diag)
12493     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12494 }
12495 
12496 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12497 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12498                             SourceLocation CContext,
12499                             unsigned diag, bool pruneControlFlow = false) {
12500   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12501 }
12502 
12503 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12504   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12505       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12506 }
12507 
12508 static void adornObjCBoolConversionDiagWithTernaryFixit(
12509     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12510   Expr *Ignored = SourceExpr->IgnoreImplicit();
12511   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12512     Ignored = OVE->getSourceExpr();
12513   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12514                      isa<BinaryOperator>(Ignored) ||
12515                      isa<CXXOperatorCallExpr>(Ignored);
12516   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12517   if (NeedsParens)
12518     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12519             << FixItHint::CreateInsertion(EndLoc, ")");
12520   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12521 }
12522 
12523 /// Diagnose an implicit cast from a floating point value to an integer value.
12524 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12525                                     SourceLocation CContext) {
12526   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12527   const bool PruneWarnings = S.inTemplateInstantiation();
12528 
12529   Expr *InnerE = E->IgnoreParenImpCasts();
12530   // We also want to warn on, e.g., "int i = -1.234"
12531   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12532     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12533       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12534 
12535   const bool IsLiteral =
12536       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12537 
12538   llvm::APFloat Value(0.0);
12539   bool IsConstant =
12540     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12541   if (!IsConstant) {
12542     if (isObjCSignedCharBool(S, T)) {
12543       return adornObjCBoolConversionDiagWithTernaryFixit(
12544           S, E,
12545           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12546               << E->getType());
12547     }
12548 
12549     return DiagnoseImpCast(S, E, T, CContext,
12550                            diag::warn_impcast_float_integer, PruneWarnings);
12551   }
12552 
12553   bool isExact = false;
12554 
12555   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12556                             T->hasUnsignedIntegerRepresentation());
12557   llvm::APFloat::opStatus Result = Value.convertToInteger(
12558       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12559 
12560   // FIXME: Force the precision of the source value down so we don't print
12561   // digits which are usually useless (we don't really care here if we
12562   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12563   // would automatically print the shortest representation, but it's a bit
12564   // tricky to implement.
12565   SmallString<16> PrettySourceValue;
12566   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12567   precision = (precision * 59 + 195) / 196;
12568   Value.toString(PrettySourceValue, precision);
12569 
12570   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12571     return adornObjCBoolConversionDiagWithTernaryFixit(
12572         S, E,
12573         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12574             << PrettySourceValue);
12575   }
12576 
12577   if (Result == llvm::APFloat::opOK && isExact) {
12578     if (IsLiteral) return;
12579     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12580                            PruneWarnings);
12581   }
12582 
12583   // Conversion of a floating-point value to a non-bool integer where the
12584   // integral part cannot be represented by the integer type is undefined.
12585   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12586     return DiagnoseImpCast(
12587         S, E, T, CContext,
12588         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12589                   : diag::warn_impcast_float_to_integer_out_of_range,
12590         PruneWarnings);
12591 
12592   unsigned DiagID = 0;
12593   if (IsLiteral) {
12594     // Warn on floating point literal to integer.
12595     DiagID = diag::warn_impcast_literal_float_to_integer;
12596   } else if (IntegerValue == 0) {
12597     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12598       return DiagnoseImpCast(S, E, T, CContext,
12599                              diag::warn_impcast_float_integer, PruneWarnings);
12600     }
12601     // Warn on non-zero to zero conversion.
12602     DiagID = diag::warn_impcast_float_to_integer_zero;
12603   } else {
12604     if (IntegerValue.isUnsigned()) {
12605       if (!IntegerValue.isMaxValue()) {
12606         return DiagnoseImpCast(S, E, T, CContext,
12607                                diag::warn_impcast_float_integer, PruneWarnings);
12608       }
12609     } else {  // IntegerValue.isSigned()
12610       if (!IntegerValue.isMaxSignedValue() &&
12611           !IntegerValue.isMinSignedValue()) {
12612         return DiagnoseImpCast(S, E, T, CContext,
12613                                diag::warn_impcast_float_integer, PruneWarnings);
12614       }
12615     }
12616     // Warn on evaluatable floating point expression to integer conversion.
12617     DiagID = diag::warn_impcast_float_to_integer;
12618   }
12619 
12620   SmallString<16> PrettyTargetValue;
12621   if (IsBool)
12622     PrettyTargetValue = Value.isZero() ? "false" : "true";
12623   else
12624     IntegerValue.toString(PrettyTargetValue);
12625 
12626   if (PruneWarnings) {
12627     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12628                           S.PDiag(DiagID)
12629                               << E->getType() << T.getUnqualifiedType()
12630                               << PrettySourceValue << PrettyTargetValue
12631                               << E->getSourceRange() << SourceRange(CContext));
12632   } else {
12633     S.Diag(E->getExprLoc(), DiagID)
12634         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12635         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12636   }
12637 }
12638 
12639 /// Analyze the given compound assignment for the possible losing of
12640 /// floating-point precision.
12641 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12642   assert(isa<CompoundAssignOperator>(E) &&
12643          "Must be compound assignment operation");
12644   // Recurse on the LHS and RHS in here
12645   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12646   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12647 
12648   if (E->getLHS()->getType()->isAtomicType())
12649     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12650 
12651   // Now check the outermost expression
12652   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12653   const auto *RBT = cast<CompoundAssignOperator>(E)
12654                         ->getComputationResultType()
12655                         ->getAs<BuiltinType>();
12656 
12657   // The below checks assume source is floating point.
12658   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12659 
12660   // If source is floating point but target is an integer.
12661   if (ResultBT->isInteger())
12662     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12663                            E->getExprLoc(), diag::warn_impcast_float_integer);
12664 
12665   if (!ResultBT->isFloatingPoint())
12666     return;
12667 
12668   // If both source and target are floating points, warn about losing precision.
12669   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12670       QualType(ResultBT, 0), QualType(RBT, 0));
12671   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12672     // warn about dropping FP rank.
12673     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12674                     diag::warn_impcast_float_result_precision);
12675 }
12676 
12677 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12678                                       IntRange Range) {
12679   if (!Range.Width) return "0";
12680 
12681   llvm::APSInt ValueInRange = Value;
12682   ValueInRange.setIsSigned(!Range.NonNegative);
12683   ValueInRange = ValueInRange.trunc(Range.Width);
12684   return toString(ValueInRange, 10);
12685 }
12686 
12687 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12688   if (!isa<ImplicitCastExpr>(Ex))
12689     return false;
12690 
12691   Expr *InnerE = Ex->IgnoreParenImpCasts();
12692   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12693   const Type *Source =
12694     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12695   if (Target->isDependentType())
12696     return false;
12697 
12698   const BuiltinType *FloatCandidateBT =
12699     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12700   const Type *BoolCandidateType = ToBool ? Target : Source;
12701 
12702   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12703           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12704 }
12705 
12706 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12707                                              SourceLocation CC) {
12708   unsigned NumArgs = TheCall->getNumArgs();
12709   for (unsigned i = 0; i < NumArgs; ++i) {
12710     Expr *CurrA = TheCall->getArg(i);
12711     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12712       continue;
12713 
12714     bool IsSwapped = ((i > 0) &&
12715         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12716     IsSwapped |= ((i < (NumArgs - 1)) &&
12717         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12718     if (IsSwapped) {
12719       // Warn on this floating-point to bool conversion.
12720       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12721                       CurrA->getType(), CC,
12722                       diag::warn_impcast_floating_point_to_bool);
12723     }
12724   }
12725 }
12726 
12727 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12728                                    SourceLocation CC) {
12729   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12730                         E->getExprLoc()))
12731     return;
12732 
12733   // Don't warn on functions which have return type nullptr_t.
12734   if (isa<CallExpr>(E))
12735     return;
12736 
12737   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12738   const Expr::NullPointerConstantKind NullKind =
12739       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12740   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12741     return;
12742 
12743   // Return if target type is a safe conversion.
12744   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12745       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12746     return;
12747 
12748   SourceLocation Loc = E->getSourceRange().getBegin();
12749 
12750   // Venture through the macro stacks to get to the source of macro arguments.
12751   // The new location is a better location than the complete location that was
12752   // passed in.
12753   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12754   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12755 
12756   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12757   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12758     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12759         Loc, S.SourceMgr, S.getLangOpts());
12760     if (MacroName == "NULL")
12761       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12762   }
12763 
12764   // Only warn if the null and context location are in the same macro expansion.
12765   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12766     return;
12767 
12768   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12769       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12770       << FixItHint::CreateReplacement(Loc,
12771                                       S.getFixItZeroLiteralForType(T, Loc));
12772 }
12773 
12774 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12775                                   ObjCArrayLiteral *ArrayLiteral);
12776 
12777 static void
12778 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12779                            ObjCDictionaryLiteral *DictionaryLiteral);
12780 
12781 /// Check a single element within a collection literal against the
12782 /// target element type.
12783 static void checkObjCCollectionLiteralElement(Sema &S,
12784                                               QualType TargetElementType,
12785                                               Expr *Element,
12786                                               unsigned ElementKind) {
12787   // Skip a bitcast to 'id' or qualified 'id'.
12788   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12789     if (ICE->getCastKind() == CK_BitCast &&
12790         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12791       Element = ICE->getSubExpr();
12792   }
12793 
12794   QualType ElementType = Element->getType();
12795   ExprResult ElementResult(Element);
12796   if (ElementType->getAs<ObjCObjectPointerType>() &&
12797       S.CheckSingleAssignmentConstraints(TargetElementType,
12798                                          ElementResult,
12799                                          false, false)
12800         != Sema::Compatible) {
12801     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12802         << ElementType << ElementKind << TargetElementType
12803         << Element->getSourceRange();
12804   }
12805 
12806   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12807     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12808   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12809     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12810 }
12811 
12812 /// Check an Objective-C array literal being converted to the given
12813 /// target type.
12814 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12815                                   ObjCArrayLiteral *ArrayLiteral) {
12816   if (!S.NSArrayDecl)
12817     return;
12818 
12819   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12820   if (!TargetObjCPtr)
12821     return;
12822 
12823   if (TargetObjCPtr->isUnspecialized() ||
12824       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12825         != S.NSArrayDecl->getCanonicalDecl())
12826     return;
12827 
12828   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12829   if (TypeArgs.size() != 1)
12830     return;
12831 
12832   QualType TargetElementType = TypeArgs[0];
12833   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12834     checkObjCCollectionLiteralElement(S, TargetElementType,
12835                                       ArrayLiteral->getElement(I),
12836                                       0);
12837   }
12838 }
12839 
12840 /// Check an Objective-C dictionary literal being converted to the given
12841 /// target type.
12842 static void
12843 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12844                            ObjCDictionaryLiteral *DictionaryLiteral) {
12845   if (!S.NSDictionaryDecl)
12846     return;
12847 
12848   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12849   if (!TargetObjCPtr)
12850     return;
12851 
12852   if (TargetObjCPtr->isUnspecialized() ||
12853       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12854         != S.NSDictionaryDecl->getCanonicalDecl())
12855     return;
12856 
12857   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12858   if (TypeArgs.size() != 2)
12859     return;
12860 
12861   QualType TargetKeyType = TypeArgs[0];
12862   QualType TargetObjectType = TypeArgs[1];
12863   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12864     auto Element = DictionaryLiteral->getKeyValueElement(I);
12865     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12866     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12867   }
12868 }
12869 
12870 // Helper function to filter out cases for constant width constant conversion.
12871 // Don't warn on char array initialization or for non-decimal values.
12872 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12873                                           SourceLocation CC) {
12874   // If initializing from a constant, and the constant starts with '0',
12875   // then it is a binary, octal, or hexadecimal.  Allow these constants
12876   // to fill all the bits, even if there is a sign change.
12877   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12878     const char FirstLiteralCharacter =
12879         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12880     if (FirstLiteralCharacter == '0')
12881       return false;
12882   }
12883 
12884   // If the CC location points to a '{', and the type is char, then assume
12885   // assume it is an array initialization.
12886   if (CC.isValid() && T->isCharType()) {
12887     const char FirstContextCharacter =
12888         S.getSourceManager().getCharacterData(CC)[0];
12889     if (FirstContextCharacter == '{')
12890       return false;
12891   }
12892 
12893   return true;
12894 }
12895 
12896 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12897   const auto *IL = dyn_cast<IntegerLiteral>(E);
12898   if (!IL) {
12899     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12900       if (UO->getOpcode() == UO_Minus)
12901         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12902     }
12903   }
12904 
12905   return IL;
12906 }
12907 
12908 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12909   E = E->IgnoreParenImpCasts();
12910   SourceLocation ExprLoc = E->getExprLoc();
12911 
12912   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12913     BinaryOperator::Opcode Opc = BO->getOpcode();
12914     Expr::EvalResult Result;
12915     // Do not diagnose unsigned shifts.
12916     if (Opc == BO_Shl) {
12917       const auto *LHS = getIntegerLiteral(BO->getLHS());
12918       const auto *RHS = getIntegerLiteral(BO->getRHS());
12919       if (LHS && LHS->getValue() == 0)
12920         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12921       else if (!E->isValueDependent() && LHS && RHS &&
12922                RHS->getValue().isNonNegative() &&
12923                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12924         S.Diag(ExprLoc, diag::warn_left_shift_always)
12925             << (Result.Val.getInt() != 0);
12926       else if (E->getType()->isSignedIntegerType())
12927         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12928     }
12929   }
12930 
12931   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12932     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12933     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12934     if (!LHS || !RHS)
12935       return;
12936     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12937         (RHS->getValue() == 0 || RHS->getValue() == 1))
12938       // Do not diagnose common idioms.
12939       return;
12940     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12941       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12942   }
12943 }
12944 
12945 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12946                                     SourceLocation CC,
12947                                     bool *ICContext = nullptr,
12948                                     bool IsListInit = false) {
12949   if (E->isTypeDependent() || E->isValueDependent()) return;
12950 
12951   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12952   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12953   if (Source == Target) return;
12954   if (Target->isDependentType()) return;
12955 
12956   // If the conversion context location is invalid don't complain. We also
12957   // don't want to emit a warning if the issue occurs from the expansion of
12958   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12959   // delay this check as long as possible. Once we detect we are in that
12960   // scenario, we just return.
12961   if (CC.isInvalid())
12962     return;
12963 
12964   if (Source->isAtomicType())
12965     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12966 
12967   // Diagnose implicit casts to bool.
12968   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12969     if (isa<StringLiteral>(E))
12970       // Warn on string literal to bool.  Checks for string literals in logical
12971       // and expressions, for instance, assert(0 && "error here"), are
12972       // prevented by a check in AnalyzeImplicitConversions().
12973       return DiagnoseImpCast(S, E, T, CC,
12974                              diag::warn_impcast_string_literal_to_bool);
12975     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12976         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12977       // This covers the literal expressions that evaluate to Objective-C
12978       // objects.
12979       return DiagnoseImpCast(S, E, T, CC,
12980                              diag::warn_impcast_objective_c_literal_to_bool);
12981     }
12982     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12983       // Warn on pointer to bool conversion that is always true.
12984       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12985                                      SourceRange(CC));
12986     }
12987   }
12988 
12989   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12990   // is a typedef for signed char (macOS), then that constant value has to be 1
12991   // or 0.
12992   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12993     Expr::EvalResult Result;
12994     if (E->EvaluateAsInt(Result, S.getASTContext(),
12995                          Expr::SE_AllowSideEffects)) {
12996       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12997         adornObjCBoolConversionDiagWithTernaryFixit(
12998             S, E,
12999             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13000                 << toString(Result.Val.getInt(), 10));
13001       }
13002       return;
13003     }
13004   }
13005 
13006   // Check implicit casts from Objective-C collection literals to specialized
13007   // collection types, e.g., NSArray<NSString *> *.
13008   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13009     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
13010   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13011     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
13012 
13013   // Strip vector types.
13014   if (isa<VectorType>(Source)) {
13015     if (Target->isVLSTBuiltinType() &&
13016         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
13017                                          QualType(Source, 0)) ||
13018          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
13019                                             QualType(Source, 0))))
13020       return;
13021 
13022     if (!isa<VectorType>(Target)) {
13023       if (S.SourceMgr.isInSystemMacro(CC))
13024         return;
13025       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
13026     }
13027 
13028     // If the vector cast is cast between two vectors of the same size, it is
13029     // a bitcast, not a conversion.
13030     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
13031       return;
13032 
13033     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13034     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13035   }
13036   if (auto VecTy = dyn_cast<VectorType>(Target))
13037     Target = VecTy->getElementType().getTypePtr();
13038 
13039   // Strip complex types.
13040   if (isa<ComplexType>(Source)) {
13041     if (!isa<ComplexType>(Target)) {
13042       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13043         return;
13044 
13045       return DiagnoseImpCast(S, E, T, CC,
13046                              S.getLangOpts().CPlusPlus
13047                                  ? diag::err_impcast_complex_scalar
13048                                  : diag::warn_impcast_complex_scalar);
13049     }
13050 
13051     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13052     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13053   }
13054 
13055   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13056   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13057 
13058   // If the source is floating point...
13059   if (SourceBT && SourceBT->isFloatingPoint()) {
13060     // ...and the target is floating point...
13061     if (TargetBT && TargetBT->isFloatingPoint()) {
13062       // ...then warn if we're dropping FP rank.
13063 
13064       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
13065           QualType(SourceBT, 0), QualType(TargetBT, 0));
13066       if (Order > 0) {
13067         // Don't warn about float constants that are precisely
13068         // representable in the target type.
13069         Expr::EvalResult result;
13070         if (E->EvaluateAsRValue(result, S.Context)) {
13071           // Value might be a float, a float vector, or a float complex.
13072           if (IsSameFloatAfterCast(result.Val,
13073                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13074                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13075             return;
13076         }
13077 
13078         if (S.SourceMgr.isInSystemMacro(CC))
13079           return;
13080 
13081         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
13082       }
13083       // ... or possibly if we're increasing rank, too
13084       else if (Order < 0) {
13085         if (S.SourceMgr.isInSystemMacro(CC))
13086           return;
13087 
13088         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
13089       }
13090       return;
13091     }
13092 
13093     // If the target is integral, always warn.
13094     if (TargetBT && TargetBT->isInteger()) {
13095       if (S.SourceMgr.isInSystemMacro(CC))
13096         return;
13097 
13098       DiagnoseFloatingImpCast(S, E, T, CC);
13099     }
13100 
13101     // Detect the case where a call result is converted from floating-point to
13102     // to bool, and the final argument to the call is converted from bool, to
13103     // discover this typo:
13104     //
13105     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
13106     //
13107     // FIXME: This is an incredibly special case; is there some more general
13108     // way to detect this class of misplaced-parentheses bug?
13109     if (Target->isBooleanType() && isa<CallExpr>(E)) {
13110       // Check last argument of function call to see if it is an
13111       // implicit cast from a type matching the type the result
13112       // is being cast to.
13113       CallExpr *CEx = cast<CallExpr>(E);
13114       if (unsigned NumArgs = CEx->getNumArgs()) {
13115         Expr *LastA = CEx->getArg(NumArgs - 1);
13116         Expr *InnerE = LastA->IgnoreParenImpCasts();
13117         if (isa<ImplicitCastExpr>(LastA) &&
13118             InnerE->getType()->isBooleanType()) {
13119           // Warn on this floating-point to bool conversion
13120           DiagnoseImpCast(S, E, T, CC,
13121                           diag::warn_impcast_floating_point_to_bool);
13122         }
13123       }
13124     }
13125     return;
13126   }
13127 
13128   // Valid casts involving fixed point types should be accounted for here.
13129   if (Source->isFixedPointType()) {
13130     if (Target->isUnsaturatedFixedPointType()) {
13131       Expr::EvalResult Result;
13132       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
13133                                   S.isConstantEvaluated())) {
13134         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13135         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
13136         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
13137         if (Value > MaxVal || Value < MinVal) {
13138           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13139                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13140                                     << Value.toString() << T
13141                                     << E->getSourceRange()
13142                                     << clang::SourceRange(CC));
13143           return;
13144         }
13145       }
13146     } else if (Target->isIntegerType()) {
13147       Expr::EvalResult Result;
13148       if (!S.isConstantEvaluated() &&
13149           E->EvaluateAsFixedPoint(Result, S.Context,
13150                                   Expr::SE_AllowSideEffects)) {
13151         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13152 
13153         bool Overflowed;
13154         llvm::APSInt IntResult = FXResult.convertToInt(
13155             S.Context.getIntWidth(T),
13156             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
13157 
13158         if (Overflowed) {
13159           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13160                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13161                                     << FXResult.toString() << T
13162                                     << E->getSourceRange()
13163                                     << clang::SourceRange(CC));
13164           return;
13165         }
13166       }
13167     }
13168   } else if (Target->isUnsaturatedFixedPointType()) {
13169     if (Source->isIntegerType()) {
13170       Expr::EvalResult Result;
13171       if (!S.isConstantEvaluated() &&
13172           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
13173         llvm::APSInt Value = Result.Val.getInt();
13174 
13175         bool Overflowed;
13176         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13177             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
13178 
13179         if (Overflowed) {
13180           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13181                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13182                                     << toString(Value, /*Radix=*/10) << T
13183                                     << E->getSourceRange()
13184                                     << clang::SourceRange(CC));
13185           return;
13186         }
13187       }
13188     }
13189   }
13190 
13191   // If we are casting an integer type to a floating point type without
13192   // initialization-list syntax, we might lose accuracy if the floating
13193   // point type has a narrower significand than the integer type.
13194   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13195       TargetBT->isFloatingType() && !IsListInit) {
13196     // Determine the number of precision bits in the source integer type.
13197     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
13198                                         /*Approximate*/ true);
13199     unsigned int SourcePrecision = SourceRange.Width;
13200 
13201     // Determine the number of precision bits in the
13202     // target floating point type.
13203     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13204         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13205 
13206     if (SourcePrecision > 0 && TargetPrecision > 0 &&
13207         SourcePrecision > TargetPrecision) {
13208 
13209       if (Optional<llvm::APSInt> SourceInt =
13210               E->getIntegerConstantExpr(S.Context)) {
13211         // If the source integer is a constant, convert it to the target
13212         // floating point type. Issue a warning if the value changes
13213         // during the whole conversion.
13214         llvm::APFloat TargetFloatValue(
13215             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13216         llvm::APFloat::opStatus ConversionStatus =
13217             TargetFloatValue.convertFromAPInt(
13218                 *SourceInt, SourceBT->isSignedInteger(),
13219                 llvm::APFloat::rmNearestTiesToEven);
13220 
13221         if (ConversionStatus != llvm::APFloat::opOK) {
13222           SmallString<32> PrettySourceValue;
13223           SourceInt->toString(PrettySourceValue, 10);
13224           SmallString<32> PrettyTargetValue;
13225           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13226 
13227           S.DiagRuntimeBehavior(
13228               E->getExprLoc(), E,
13229               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
13230                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
13231                   << E->getSourceRange() << clang::SourceRange(CC));
13232         }
13233       } else {
13234         // Otherwise, the implicit conversion may lose precision.
13235         DiagnoseImpCast(S, E, T, CC,
13236                         diag::warn_impcast_integer_float_precision);
13237       }
13238     }
13239   }
13240 
13241   DiagnoseNullConversion(S, E, T, CC);
13242 
13243   S.DiscardMisalignedMemberAddress(Target, E);
13244 
13245   if (Target->isBooleanType())
13246     DiagnoseIntInBoolContext(S, E);
13247 
13248   if (!Source->isIntegerType() || !Target->isIntegerType())
13249     return;
13250 
13251   // TODO: remove this early return once the false positives for constant->bool
13252   // in templates, macros, etc, are reduced or removed.
13253   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13254     return;
13255 
13256   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
13257       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13258     return adornObjCBoolConversionDiagWithTernaryFixit(
13259         S, E,
13260         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13261             << E->getType());
13262   }
13263 
13264   IntRange SourceTypeRange =
13265       IntRange::forTargetOfCanonicalType(S.Context, Source);
13266   IntRange LikelySourceRange =
13267       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
13268   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
13269 
13270   if (LikelySourceRange.Width > TargetRange.Width) {
13271     // If the source is a constant, use a default-on diagnostic.
13272     // TODO: this should happen for bitfield stores, too.
13273     Expr::EvalResult Result;
13274     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
13275                          S.isConstantEvaluated())) {
13276       llvm::APSInt Value(32);
13277       Value = Result.Val.getInt();
13278 
13279       if (S.SourceMgr.isInSystemMacro(CC))
13280         return;
13281 
13282       std::string PrettySourceValue = toString(Value, 10);
13283       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13284 
13285       S.DiagRuntimeBehavior(
13286           E->getExprLoc(), E,
13287           S.PDiag(diag::warn_impcast_integer_precision_constant)
13288               << PrettySourceValue << PrettyTargetValue << E->getType() << T
13289               << E->getSourceRange() << SourceRange(CC));
13290       return;
13291     }
13292 
13293     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13294     if (S.SourceMgr.isInSystemMacro(CC))
13295       return;
13296 
13297     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
13298       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
13299                              /* pruneControlFlow */ true);
13300     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
13301   }
13302 
13303   if (TargetRange.Width > SourceTypeRange.Width) {
13304     if (auto *UO = dyn_cast<UnaryOperator>(E))
13305       if (UO->getOpcode() == UO_Minus)
13306         if (Source->isUnsignedIntegerType()) {
13307           if (Target->isUnsignedIntegerType())
13308             return DiagnoseImpCast(S, E, T, CC,
13309                                    diag::warn_impcast_high_order_zero_bits);
13310           if (Target->isSignedIntegerType())
13311             return DiagnoseImpCast(S, E, T, CC,
13312                                    diag::warn_impcast_nonnegative_result);
13313         }
13314   }
13315 
13316   if (TargetRange.Width == LikelySourceRange.Width &&
13317       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13318       Source->isSignedIntegerType()) {
13319     // Warn when doing a signed to signed conversion, warn if the positive
13320     // source value is exactly the width of the target type, which will
13321     // cause a negative value to be stored.
13322 
13323     Expr::EvalResult Result;
13324     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
13325         !S.SourceMgr.isInSystemMacro(CC)) {
13326       llvm::APSInt Value = Result.Val.getInt();
13327       if (isSameWidthConstantConversion(S, E, T, CC)) {
13328         std::string PrettySourceValue = toString(Value, 10);
13329         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13330 
13331         S.DiagRuntimeBehavior(
13332             E->getExprLoc(), E,
13333             S.PDiag(diag::warn_impcast_integer_precision_constant)
13334                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13335                 << E->getSourceRange() << SourceRange(CC));
13336         return;
13337       }
13338     }
13339 
13340     // Fall through for non-constants to give a sign conversion warning.
13341   }
13342 
13343   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13344       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13345        LikelySourceRange.Width == TargetRange.Width)) {
13346     if (S.SourceMgr.isInSystemMacro(CC))
13347       return;
13348 
13349     unsigned DiagID = diag::warn_impcast_integer_sign;
13350 
13351     // Traditionally, gcc has warned about this under -Wsign-compare.
13352     // We also want to warn about it in -Wconversion.
13353     // So if -Wconversion is off, use a completely identical diagnostic
13354     // in the sign-compare group.
13355     // The conditional-checking code will
13356     if (ICContext) {
13357       DiagID = diag::warn_impcast_integer_sign_conditional;
13358       *ICContext = true;
13359     }
13360 
13361     return DiagnoseImpCast(S, E, T, CC, DiagID);
13362   }
13363 
13364   // Diagnose conversions between different enumeration types.
13365   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13366   // type, to give us better diagnostics.
13367   QualType SourceType = E->getType();
13368   if (!S.getLangOpts().CPlusPlus) {
13369     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13370       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13371         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13372         SourceType = S.Context.getTypeDeclType(Enum);
13373         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13374       }
13375   }
13376 
13377   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13378     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13379       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13380           TargetEnum->getDecl()->hasNameForLinkage() &&
13381           SourceEnum != TargetEnum) {
13382         if (S.SourceMgr.isInSystemMacro(CC))
13383           return;
13384 
13385         return DiagnoseImpCast(S, E, SourceType, T, CC,
13386                                diag::warn_impcast_different_enum_types);
13387       }
13388 }
13389 
13390 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13391                                      SourceLocation CC, QualType T);
13392 
13393 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13394                                     SourceLocation CC, bool &ICContext) {
13395   E = E->IgnoreParenImpCasts();
13396 
13397   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13398     return CheckConditionalOperator(S, CO, CC, T);
13399 
13400   AnalyzeImplicitConversions(S, E, CC);
13401   if (E->getType() != T)
13402     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13403 }
13404 
13405 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13406                                      SourceLocation CC, QualType T) {
13407   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13408 
13409   Expr *TrueExpr = E->getTrueExpr();
13410   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13411     TrueExpr = BCO->getCommon();
13412 
13413   bool Suspicious = false;
13414   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13415   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13416 
13417   if (T->isBooleanType())
13418     DiagnoseIntInBoolContext(S, E);
13419 
13420   // If -Wconversion would have warned about either of the candidates
13421   // for a signedness conversion to the context type...
13422   if (!Suspicious) return;
13423 
13424   // ...but it's currently ignored...
13425   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13426     return;
13427 
13428   // ...then check whether it would have warned about either of the
13429   // candidates for a signedness conversion to the condition type.
13430   if (E->getType() == T) return;
13431 
13432   Suspicious = false;
13433   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13434                           E->getType(), CC, &Suspicious);
13435   if (!Suspicious)
13436     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13437                             E->getType(), CC, &Suspicious);
13438 }
13439 
13440 /// Check conversion of given expression to boolean.
13441 /// Input argument E is a logical expression.
13442 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13443   if (S.getLangOpts().Bool)
13444     return;
13445   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13446     return;
13447   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13448 }
13449 
13450 namespace {
13451 struct AnalyzeImplicitConversionsWorkItem {
13452   Expr *E;
13453   SourceLocation CC;
13454   bool IsListInit;
13455 };
13456 }
13457 
13458 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13459 /// that should be visited are added to WorkList.
13460 static void AnalyzeImplicitConversions(
13461     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13462     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13463   Expr *OrigE = Item.E;
13464   SourceLocation CC = Item.CC;
13465 
13466   QualType T = OrigE->getType();
13467   Expr *E = OrigE->IgnoreParenImpCasts();
13468 
13469   // Propagate whether we are in a C++ list initialization expression.
13470   // If so, we do not issue warnings for implicit int-float conversion
13471   // precision loss, because C++11 narrowing already handles it.
13472   bool IsListInit = Item.IsListInit ||
13473                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13474 
13475   if (E->isTypeDependent() || E->isValueDependent())
13476     return;
13477 
13478   Expr *SourceExpr = E;
13479   // Examine, but don't traverse into the source expression of an
13480   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13481   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13482   // evaluate it in the context of checking the specific conversion to T though.
13483   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13484     if (auto *Src = OVE->getSourceExpr())
13485       SourceExpr = Src;
13486 
13487   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13488     if (UO->getOpcode() == UO_Not &&
13489         UO->getSubExpr()->isKnownToHaveBooleanValue())
13490       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13491           << OrigE->getSourceRange() << T->isBooleanType()
13492           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13493 
13494   if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
13495     if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13496         BO->getLHS()->isKnownToHaveBooleanValue() &&
13497         BO->getRHS()->isKnownToHaveBooleanValue() &&
13498         BO->getLHS()->HasSideEffects(S.Context) &&
13499         BO->getRHS()->HasSideEffects(S.Context)) {
13500       S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13501           << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange()
13502           << FixItHint::CreateReplacement(
13503                  BO->getOperatorLoc(),
13504                  (BO->getOpcode() == BO_And ? "&&" : "||"));
13505       S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13506     }
13507 
13508   // For conditional operators, we analyze the arguments as if they
13509   // were being fed directly into the output.
13510   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13511     CheckConditionalOperator(S, CO, CC, T);
13512     return;
13513   }
13514 
13515   // Check implicit argument conversions for function calls.
13516   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13517     CheckImplicitArgumentConversions(S, Call, CC);
13518 
13519   // Go ahead and check any implicit conversions we might have skipped.
13520   // The non-canonical typecheck is just an optimization;
13521   // CheckImplicitConversion will filter out dead implicit conversions.
13522   if (SourceExpr->getType() != T)
13523     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13524 
13525   // Now continue drilling into this expression.
13526 
13527   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13528     // The bound subexpressions in a PseudoObjectExpr are not reachable
13529     // as transitive children.
13530     // FIXME: Use a more uniform representation for this.
13531     for (auto *SE : POE->semantics())
13532       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13533         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13534   }
13535 
13536   // Skip past explicit casts.
13537   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13538     E = CE->getSubExpr()->IgnoreParenImpCasts();
13539     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13540       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13541     WorkList.push_back({E, CC, IsListInit});
13542     return;
13543   }
13544 
13545   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13546     // Do a somewhat different check with comparison operators.
13547     if (BO->isComparisonOp())
13548       return AnalyzeComparison(S, BO);
13549 
13550     // And with simple assignments.
13551     if (BO->getOpcode() == BO_Assign)
13552       return AnalyzeAssignment(S, BO);
13553     // And with compound assignments.
13554     if (BO->isAssignmentOp())
13555       return AnalyzeCompoundAssignment(S, BO);
13556   }
13557 
13558   // These break the otherwise-useful invariant below.  Fortunately,
13559   // we don't really need to recurse into them, because any internal
13560   // expressions should have been analyzed already when they were
13561   // built into statements.
13562   if (isa<StmtExpr>(E)) return;
13563 
13564   // Don't descend into unevaluated contexts.
13565   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13566 
13567   // Now just recurse over the expression's children.
13568   CC = E->getExprLoc();
13569   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13570   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13571   for (Stmt *SubStmt : E->children()) {
13572     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13573     if (!ChildExpr)
13574       continue;
13575 
13576     if (IsLogicalAndOperator &&
13577         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13578       // Ignore checking string literals that are in logical and operators.
13579       // This is a common pattern for asserts.
13580       continue;
13581     WorkList.push_back({ChildExpr, CC, IsListInit});
13582   }
13583 
13584   if (BO && BO->isLogicalOp()) {
13585     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13586     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13587       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13588 
13589     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13590     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13591       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13592   }
13593 
13594   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13595     if (U->getOpcode() == UO_LNot) {
13596       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13597     } else if (U->getOpcode() != UO_AddrOf) {
13598       if (U->getSubExpr()->getType()->isAtomicType())
13599         S.Diag(U->getSubExpr()->getBeginLoc(),
13600                diag::warn_atomic_implicit_seq_cst);
13601     }
13602   }
13603 }
13604 
13605 /// AnalyzeImplicitConversions - Find and report any interesting
13606 /// implicit conversions in the given expression.  There are a couple
13607 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13608 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13609                                        bool IsListInit/*= false*/) {
13610   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13611   WorkList.push_back({OrigE, CC, IsListInit});
13612   while (!WorkList.empty())
13613     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13614 }
13615 
13616 /// Diagnose integer type and any valid implicit conversion to it.
13617 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13618   // Taking into account implicit conversions,
13619   // allow any integer.
13620   if (!E->getType()->isIntegerType()) {
13621     S.Diag(E->getBeginLoc(),
13622            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13623     return true;
13624   }
13625   // Potentially emit standard warnings for implicit conversions if enabled
13626   // using -Wconversion.
13627   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13628   return false;
13629 }
13630 
13631 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13632 // Returns true when emitting a warning about taking the address of a reference.
13633 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13634                               const PartialDiagnostic &PD) {
13635   E = E->IgnoreParenImpCasts();
13636 
13637   const FunctionDecl *FD = nullptr;
13638 
13639   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13640     if (!DRE->getDecl()->getType()->isReferenceType())
13641       return false;
13642   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13643     if (!M->getMemberDecl()->getType()->isReferenceType())
13644       return false;
13645   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13646     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13647       return false;
13648     FD = Call->getDirectCallee();
13649   } else {
13650     return false;
13651   }
13652 
13653   SemaRef.Diag(E->getExprLoc(), PD);
13654 
13655   // If possible, point to location of function.
13656   if (FD) {
13657     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13658   }
13659 
13660   return true;
13661 }
13662 
13663 // Returns true if the SourceLocation is expanded from any macro body.
13664 // Returns false if the SourceLocation is invalid, is from not in a macro
13665 // expansion, or is from expanded from a top-level macro argument.
13666 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13667   if (Loc.isInvalid())
13668     return false;
13669 
13670   while (Loc.isMacroID()) {
13671     if (SM.isMacroBodyExpansion(Loc))
13672       return true;
13673     Loc = SM.getImmediateMacroCallerLoc(Loc);
13674   }
13675 
13676   return false;
13677 }
13678 
13679 /// Diagnose pointers that are always non-null.
13680 /// \param E the expression containing the pointer
13681 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13682 /// compared to a null pointer
13683 /// \param IsEqual True when the comparison is equal to a null pointer
13684 /// \param Range Extra SourceRange to highlight in the diagnostic
13685 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13686                                         Expr::NullPointerConstantKind NullKind,
13687                                         bool IsEqual, SourceRange Range) {
13688   if (!E)
13689     return;
13690 
13691   // Don't warn inside macros.
13692   if (E->getExprLoc().isMacroID()) {
13693     const SourceManager &SM = getSourceManager();
13694     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13695         IsInAnyMacroBody(SM, Range.getBegin()))
13696       return;
13697   }
13698   E = E->IgnoreImpCasts();
13699 
13700   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13701 
13702   if (isa<CXXThisExpr>(E)) {
13703     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13704                                 : diag::warn_this_bool_conversion;
13705     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13706     return;
13707   }
13708 
13709   bool IsAddressOf = false;
13710 
13711   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13712     if (UO->getOpcode() != UO_AddrOf)
13713       return;
13714     IsAddressOf = true;
13715     E = UO->getSubExpr();
13716   }
13717 
13718   if (IsAddressOf) {
13719     unsigned DiagID = IsCompare
13720                           ? diag::warn_address_of_reference_null_compare
13721                           : diag::warn_address_of_reference_bool_conversion;
13722     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13723                                          << IsEqual;
13724     if (CheckForReference(*this, E, PD)) {
13725       return;
13726     }
13727   }
13728 
13729   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13730     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13731     std::string Str;
13732     llvm::raw_string_ostream S(Str);
13733     E->printPretty(S, nullptr, getPrintingPolicy());
13734     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13735                                 : diag::warn_cast_nonnull_to_bool;
13736     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13737       << E->getSourceRange() << Range << IsEqual;
13738     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13739   };
13740 
13741   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13742   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13743     if (auto *Callee = Call->getDirectCallee()) {
13744       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13745         ComplainAboutNonnullParamOrCall(A);
13746         return;
13747       }
13748     }
13749   }
13750 
13751   // Expect to find a single Decl.  Skip anything more complicated.
13752   ValueDecl *D = nullptr;
13753   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13754     D = R->getDecl();
13755   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13756     D = M->getMemberDecl();
13757   }
13758 
13759   // Weak Decls can be null.
13760   if (!D || D->isWeak())
13761     return;
13762 
13763   // Check for parameter decl with nonnull attribute
13764   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13765     if (getCurFunction() &&
13766         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13767       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13768         ComplainAboutNonnullParamOrCall(A);
13769         return;
13770       }
13771 
13772       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13773         // Skip function template not specialized yet.
13774         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13775           return;
13776         auto ParamIter = llvm::find(FD->parameters(), PV);
13777         assert(ParamIter != FD->param_end());
13778         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13779 
13780         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13781           if (!NonNull->args_size()) {
13782               ComplainAboutNonnullParamOrCall(NonNull);
13783               return;
13784           }
13785 
13786           for (const ParamIdx &ArgNo : NonNull->args()) {
13787             if (ArgNo.getASTIndex() == ParamNo) {
13788               ComplainAboutNonnullParamOrCall(NonNull);
13789               return;
13790             }
13791           }
13792         }
13793       }
13794     }
13795   }
13796 
13797   QualType T = D->getType();
13798   const bool IsArray = T->isArrayType();
13799   const bool IsFunction = T->isFunctionType();
13800 
13801   // Address of function is used to silence the function warning.
13802   if (IsAddressOf && IsFunction) {
13803     return;
13804   }
13805 
13806   // Found nothing.
13807   if (!IsAddressOf && !IsFunction && !IsArray)
13808     return;
13809 
13810   // Pretty print the expression for the diagnostic.
13811   std::string Str;
13812   llvm::raw_string_ostream S(Str);
13813   E->printPretty(S, nullptr, getPrintingPolicy());
13814 
13815   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13816                               : diag::warn_impcast_pointer_to_bool;
13817   enum {
13818     AddressOf,
13819     FunctionPointer,
13820     ArrayPointer
13821   } DiagType;
13822   if (IsAddressOf)
13823     DiagType = AddressOf;
13824   else if (IsFunction)
13825     DiagType = FunctionPointer;
13826   else if (IsArray)
13827     DiagType = ArrayPointer;
13828   else
13829     llvm_unreachable("Could not determine diagnostic.");
13830   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13831                                 << Range << IsEqual;
13832 
13833   if (!IsFunction)
13834     return;
13835 
13836   // Suggest '&' to silence the function warning.
13837   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13838       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13839 
13840   // Check to see if '()' fixit should be emitted.
13841   QualType ReturnType;
13842   UnresolvedSet<4> NonTemplateOverloads;
13843   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13844   if (ReturnType.isNull())
13845     return;
13846 
13847   if (IsCompare) {
13848     // There are two cases here.  If there is null constant, the only suggest
13849     // for a pointer return type.  If the null is 0, then suggest if the return
13850     // type is a pointer or an integer type.
13851     if (!ReturnType->isPointerType()) {
13852       if (NullKind == Expr::NPCK_ZeroExpression ||
13853           NullKind == Expr::NPCK_ZeroLiteral) {
13854         if (!ReturnType->isIntegerType())
13855           return;
13856       } else {
13857         return;
13858       }
13859     }
13860   } else { // !IsCompare
13861     // For function to bool, only suggest if the function pointer has bool
13862     // return type.
13863     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13864       return;
13865   }
13866   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13867       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13868 }
13869 
13870 /// Diagnoses "dangerous" implicit conversions within the given
13871 /// expression (which is a full expression).  Implements -Wconversion
13872 /// and -Wsign-compare.
13873 ///
13874 /// \param CC the "context" location of the implicit conversion, i.e.
13875 ///   the most location of the syntactic entity requiring the implicit
13876 ///   conversion
13877 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13878   // Don't diagnose in unevaluated contexts.
13879   if (isUnevaluatedContext())
13880     return;
13881 
13882   // Don't diagnose for value- or type-dependent expressions.
13883   if (E->isTypeDependent() || E->isValueDependent())
13884     return;
13885 
13886   // Check for array bounds violations in cases where the check isn't triggered
13887   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13888   // ArraySubscriptExpr is on the RHS of a variable initialization.
13889   CheckArrayAccess(E);
13890 
13891   // This is not the right CC for (e.g.) a variable initialization.
13892   AnalyzeImplicitConversions(*this, E, CC);
13893 }
13894 
13895 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13896 /// Input argument E is a logical expression.
13897 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13898   ::CheckBoolLikeConversion(*this, E, CC);
13899 }
13900 
13901 /// Diagnose when expression is an integer constant expression and its evaluation
13902 /// results in integer overflow
13903 void Sema::CheckForIntOverflow (Expr *E) {
13904   // Use a work list to deal with nested struct initializers.
13905   SmallVector<Expr *, 2> Exprs(1, E);
13906 
13907   do {
13908     Expr *OriginalE = Exprs.pop_back_val();
13909     Expr *E = OriginalE->IgnoreParenCasts();
13910 
13911     if (isa<BinaryOperator>(E)) {
13912       E->EvaluateForOverflow(Context);
13913       continue;
13914     }
13915 
13916     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13917       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13918     else if (isa<ObjCBoxedExpr>(OriginalE))
13919       E->EvaluateForOverflow(Context);
13920     else if (auto Call = dyn_cast<CallExpr>(E))
13921       Exprs.append(Call->arg_begin(), Call->arg_end());
13922     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13923       Exprs.append(Message->arg_begin(), Message->arg_end());
13924   } while (!Exprs.empty());
13925 }
13926 
13927 namespace {
13928 
13929 /// Visitor for expressions which looks for unsequenced operations on the
13930 /// same object.
13931 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13932   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13933 
13934   /// A tree of sequenced regions within an expression. Two regions are
13935   /// unsequenced if one is an ancestor or a descendent of the other. When we
13936   /// finish processing an expression with sequencing, such as a comma
13937   /// expression, we fold its tree nodes into its parent, since they are
13938   /// unsequenced with respect to nodes we will visit later.
13939   class SequenceTree {
13940     struct Value {
13941       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13942       unsigned Parent : 31;
13943       unsigned Merged : 1;
13944     };
13945     SmallVector<Value, 8> Values;
13946 
13947   public:
13948     /// A region within an expression which may be sequenced with respect
13949     /// to some other region.
13950     class Seq {
13951       friend class SequenceTree;
13952 
13953       unsigned Index;
13954 
13955       explicit Seq(unsigned N) : Index(N) {}
13956 
13957     public:
13958       Seq() : Index(0) {}
13959     };
13960 
13961     SequenceTree() { Values.push_back(Value(0)); }
13962     Seq root() const { return Seq(0); }
13963 
13964     /// Create a new sequence of operations, which is an unsequenced
13965     /// subset of \p Parent. This sequence of operations is sequenced with
13966     /// respect to other children of \p Parent.
13967     Seq allocate(Seq Parent) {
13968       Values.push_back(Value(Parent.Index));
13969       return Seq(Values.size() - 1);
13970     }
13971 
13972     /// Merge a sequence of operations into its parent.
13973     void merge(Seq S) {
13974       Values[S.Index].Merged = true;
13975     }
13976 
13977     /// Determine whether two operations are unsequenced. This operation
13978     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13979     /// should have been merged into its parent as appropriate.
13980     bool isUnsequenced(Seq Cur, Seq Old) {
13981       unsigned C = representative(Cur.Index);
13982       unsigned Target = representative(Old.Index);
13983       while (C >= Target) {
13984         if (C == Target)
13985           return true;
13986         C = Values[C].Parent;
13987       }
13988       return false;
13989     }
13990 
13991   private:
13992     /// Pick a representative for a sequence.
13993     unsigned representative(unsigned K) {
13994       if (Values[K].Merged)
13995         // Perform path compression as we go.
13996         return Values[K].Parent = representative(Values[K].Parent);
13997       return K;
13998     }
13999   };
14000 
14001   /// An object for which we can track unsequenced uses.
14002   using Object = const NamedDecl *;
14003 
14004   /// Different flavors of object usage which we track. We only track the
14005   /// least-sequenced usage of each kind.
14006   enum UsageKind {
14007     /// A read of an object. Multiple unsequenced reads are OK.
14008     UK_Use,
14009 
14010     /// A modification of an object which is sequenced before the value
14011     /// computation of the expression, such as ++n in C++.
14012     UK_ModAsValue,
14013 
14014     /// A modification of an object which is not sequenced before the value
14015     /// computation of the expression, such as n++.
14016     UK_ModAsSideEffect,
14017 
14018     UK_Count = UK_ModAsSideEffect + 1
14019   };
14020 
14021   /// Bundle together a sequencing region and the expression corresponding
14022   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14023   struct Usage {
14024     const Expr *UsageExpr;
14025     SequenceTree::Seq Seq;
14026 
14027     Usage() : UsageExpr(nullptr) {}
14028   };
14029 
14030   struct UsageInfo {
14031     Usage Uses[UK_Count];
14032 
14033     /// Have we issued a diagnostic for this object already?
14034     bool Diagnosed;
14035 
14036     UsageInfo() : Diagnosed(false) {}
14037   };
14038   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14039 
14040   Sema &SemaRef;
14041 
14042   /// Sequenced regions within the expression.
14043   SequenceTree Tree;
14044 
14045   /// Declaration modifications and references which we have seen.
14046   UsageInfoMap UsageMap;
14047 
14048   /// The region we are currently within.
14049   SequenceTree::Seq Region;
14050 
14051   /// Filled in with declarations which were modified as a side-effect
14052   /// (that is, post-increment operations).
14053   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14054 
14055   /// Expressions to check later. We defer checking these to reduce
14056   /// stack usage.
14057   SmallVectorImpl<const Expr *> &WorkList;
14058 
14059   /// RAII object wrapping the visitation of a sequenced subexpression of an
14060   /// expression. At the end of this process, the side-effects of the evaluation
14061   /// become sequenced with respect to the value computation of the result, so
14062   /// we downgrade any UK_ModAsSideEffect within the evaluation to
14063   /// UK_ModAsValue.
14064   struct SequencedSubexpression {
14065     SequencedSubexpression(SequenceChecker &Self)
14066       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14067       Self.ModAsSideEffect = &ModAsSideEffect;
14068     }
14069 
14070     ~SequencedSubexpression() {
14071       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14072         // Add a new usage with usage kind UK_ModAsValue, and then restore
14073         // the previous usage with UK_ModAsSideEffect (thus clearing it if
14074         // the previous one was empty).
14075         UsageInfo &UI = Self.UsageMap[M.first];
14076         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14077         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14078         SideEffectUsage = M.second;
14079       }
14080       Self.ModAsSideEffect = OldModAsSideEffect;
14081     }
14082 
14083     SequenceChecker &Self;
14084     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14085     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14086   };
14087 
14088   /// RAII object wrapping the visitation of a subexpression which we might
14089   /// choose to evaluate as a constant. If any subexpression is evaluated and
14090   /// found to be non-constant, this allows us to suppress the evaluation of
14091   /// the outer expression.
14092   class EvaluationTracker {
14093   public:
14094     EvaluationTracker(SequenceChecker &Self)
14095         : Self(Self), Prev(Self.EvalTracker) {
14096       Self.EvalTracker = this;
14097     }
14098 
14099     ~EvaluationTracker() {
14100       Self.EvalTracker = Prev;
14101       if (Prev)
14102         Prev->EvalOK &= EvalOK;
14103     }
14104 
14105     bool evaluate(const Expr *E, bool &Result) {
14106       if (!EvalOK || E->isValueDependent())
14107         return false;
14108       EvalOK = E->EvaluateAsBooleanCondition(
14109           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
14110       return EvalOK;
14111     }
14112 
14113   private:
14114     SequenceChecker &Self;
14115     EvaluationTracker *Prev;
14116     bool EvalOK = true;
14117   } *EvalTracker = nullptr;
14118 
14119   /// Find the object which is produced by the specified expression,
14120   /// if any.
14121   Object getObject(const Expr *E, bool Mod) const {
14122     E = E->IgnoreParenCasts();
14123     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14124       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14125         return getObject(UO->getSubExpr(), Mod);
14126     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14127       if (BO->getOpcode() == BO_Comma)
14128         return getObject(BO->getRHS(), Mod);
14129       if (Mod && BO->isAssignmentOp())
14130         return getObject(BO->getLHS(), Mod);
14131     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14132       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14133       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14134         return ME->getMemberDecl();
14135     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14136       // FIXME: If this is a reference, map through to its value.
14137       return DRE->getDecl();
14138     return nullptr;
14139   }
14140 
14141   /// Note that an object \p O was modified or used by an expression
14142   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14143   /// the object \p O as obtained via the \p UsageMap.
14144   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14145     // Get the old usage for the given object and usage kind.
14146     Usage &U = UI.Uses[UK];
14147     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14148       // If we have a modification as side effect and are in a sequenced
14149       // subexpression, save the old Usage so that we can restore it later
14150       // in SequencedSubexpression::~SequencedSubexpression.
14151       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14152         ModAsSideEffect->push_back(std::make_pair(O, U));
14153       // Then record the new usage with the current sequencing region.
14154       U.UsageExpr = UsageExpr;
14155       U.Seq = Region;
14156     }
14157   }
14158 
14159   /// Check whether a modification or use of an object \p O in an expression
14160   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14161   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14162   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14163   /// usage and false we are checking for a mod-use unsequenced usage.
14164   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14165                   UsageKind OtherKind, bool IsModMod) {
14166     if (UI.Diagnosed)
14167       return;
14168 
14169     const Usage &U = UI.Uses[OtherKind];
14170     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14171       return;
14172 
14173     const Expr *Mod = U.UsageExpr;
14174     const Expr *ModOrUse = UsageExpr;
14175     if (OtherKind == UK_Use)
14176       std::swap(Mod, ModOrUse);
14177 
14178     SemaRef.DiagRuntimeBehavior(
14179         Mod->getExprLoc(), {Mod, ModOrUse},
14180         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14181                                : diag::warn_unsequenced_mod_use)
14182             << O << SourceRange(ModOrUse->getExprLoc()));
14183     UI.Diagnosed = true;
14184   }
14185 
14186   // A note on note{Pre, Post}{Use, Mod}:
14187   //
14188   // (It helps to follow the algorithm with an expression such as
14189   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14190   //  operations before C++17 and both are well-defined in C++17).
14191   //
14192   // When visiting a node which uses/modify an object we first call notePreUse
14193   // or notePreMod before visiting its sub-expression(s). At this point the
14194   // children of the current node have not yet been visited and so the eventual
14195   // uses/modifications resulting from the children of the current node have not
14196   // been recorded yet.
14197   //
14198   // We then visit the children of the current node. After that notePostUse or
14199   // notePostMod is called. These will 1) detect an unsequenced modification
14200   // as side effect (as in "k++ + k") and 2) add a new usage with the
14201   // appropriate usage kind.
14202   //
14203   // We also have to be careful that some operation sequences modification as
14204   // side effect as well (for example: || or ,). To account for this we wrap
14205   // the visitation of such a sub-expression (for example: the LHS of || or ,)
14206   // with SequencedSubexpression. SequencedSubexpression is an RAII object
14207   // which record usages which are modifications as side effect, and then
14208   // downgrade them (or more accurately restore the previous usage which was a
14209   // modification as side effect) when exiting the scope of the sequenced
14210   // subexpression.
14211 
14212   void notePreUse(Object O, const Expr *UseExpr) {
14213     UsageInfo &UI = UsageMap[O];
14214     // Uses conflict with other modifications.
14215     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14216   }
14217 
14218   void notePostUse(Object O, const Expr *UseExpr) {
14219     UsageInfo &UI = UsageMap[O];
14220     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14221                /*IsModMod=*/false);
14222     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14223   }
14224 
14225   void notePreMod(Object O, const Expr *ModExpr) {
14226     UsageInfo &UI = UsageMap[O];
14227     // Modifications conflict with other modifications and with uses.
14228     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14229     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14230   }
14231 
14232   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14233     UsageInfo &UI = UsageMap[O];
14234     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14235                /*IsModMod=*/true);
14236     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14237   }
14238 
14239 public:
14240   SequenceChecker(Sema &S, const Expr *E,
14241                   SmallVectorImpl<const Expr *> &WorkList)
14242       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14243     Visit(E);
14244     // Silence a -Wunused-private-field since WorkList is now unused.
14245     // TODO: Evaluate if it can be used, and if not remove it.
14246     (void)this->WorkList;
14247   }
14248 
14249   void VisitStmt(const Stmt *S) {
14250     // Skip all statements which aren't expressions for now.
14251   }
14252 
14253   void VisitExpr(const Expr *E) {
14254     // By default, just recurse to evaluated subexpressions.
14255     Base::VisitStmt(E);
14256   }
14257 
14258   void VisitCastExpr(const CastExpr *E) {
14259     Object O = Object();
14260     if (E->getCastKind() == CK_LValueToRValue)
14261       O = getObject(E->getSubExpr(), false);
14262 
14263     if (O)
14264       notePreUse(O, E);
14265     VisitExpr(E);
14266     if (O)
14267       notePostUse(O, E);
14268   }
14269 
14270   void VisitSequencedExpressions(const Expr *SequencedBefore,
14271                                  const Expr *SequencedAfter) {
14272     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14273     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14274     SequenceTree::Seq OldRegion = Region;
14275 
14276     {
14277       SequencedSubexpression SeqBefore(*this);
14278       Region = BeforeRegion;
14279       Visit(SequencedBefore);
14280     }
14281 
14282     Region = AfterRegion;
14283     Visit(SequencedAfter);
14284 
14285     Region = OldRegion;
14286 
14287     Tree.merge(BeforeRegion);
14288     Tree.merge(AfterRegion);
14289   }
14290 
14291   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14292     // C++17 [expr.sub]p1:
14293     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14294     //   expression E1 is sequenced before the expression E2.
14295     if (SemaRef.getLangOpts().CPlusPlus17)
14296       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14297     else {
14298       Visit(ASE->getLHS());
14299       Visit(ASE->getRHS());
14300     }
14301   }
14302 
14303   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14304   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14305   void VisitBinPtrMem(const BinaryOperator *BO) {
14306     // C++17 [expr.mptr.oper]p4:
14307     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14308     //  the expression E1 is sequenced before the expression E2.
14309     if (SemaRef.getLangOpts().CPlusPlus17)
14310       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14311     else {
14312       Visit(BO->getLHS());
14313       Visit(BO->getRHS());
14314     }
14315   }
14316 
14317   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14318   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14319   void VisitBinShlShr(const BinaryOperator *BO) {
14320     // C++17 [expr.shift]p4:
14321     //  The expression E1 is sequenced before the expression E2.
14322     if (SemaRef.getLangOpts().CPlusPlus17)
14323       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14324     else {
14325       Visit(BO->getLHS());
14326       Visit(BO->getRHS());
14327     }
14328   }
14329 
14330   void VisitBinComma(const BinaryOperator *BO) {
14331     // C++11 [expr.comma]p1:
14332     //   Every value computation and side effect associated with the left
14333     //   expression is sequenced before every value computation and side
14334     //   effect associated with the right expression.
14335     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14336   }
14337 
14338   void VisitBinAssign(const BinaryOperator *BO) {
14339     SequenceTree::Seq RHSRegion;
14340     SequenceTree::Seq LHSRegion;
14341     if (SemaRef.getLangOpts().CPlusPlus17) {
14342       RHSRegion = Tree.allocate(Region);
14343       LHSRegion = Tree.allocate(Region);
14344     } else {
14345       RHSRegion = Region;
14346       LHSRegion = Region;
14347     }
14348     SequenceTree::Seq OldRegion = Region;
14349 
14350     // C++11 [expr.ass]p1:
14351     //  [...] the assignment is sequenced after the value computation
14352     //  of the right and left operands, [...]
14353     //
14354     // so check it before inspecting the operands and update the
14355     // map afterwards.
14356     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14357     if (O)
14358       notePreMod(O, BO);
14359 
14360     if (SemaRef.getLangOpts().CPlusPlus17) {
14361       // C++17 [expr.ass]p1:
14362       //  [...] The right operand is sequenced before the left operand. [...]
14363       {
14364         SequencedSubexpression SeqBefore(*this);
14365         Region = RHSRegion;
14366         Visit(BO->getRHS());
14367       }
14368 
14369       Region = LHSRegion;
14370       Visit(BO->getLHS());
14371 
14372       if (O && isa<CompoundAssignOperator>(BO))
14373         notePostUse(O, BO);
14374 
14375     } else {
14376       // C++11 does not specify any sequencing between the LHS and RHS.
14377       Region = LHSRegion;
14378       Visit(BO->getLHS());
14379 
14380       if (O && isa<CompoundAssignOperator>(BO))
14381         notePostUse(O, BO);
14382 
14383       Region = RHSRegion;
14384       Visit(BO->getRHS());
14385     }
14386 
14387     // C++11 [expr.ass]p1:
14388     //  the assignment is sequenced [...] before the value computation of the
14389     //  assignment expression.
14390     // C11 6.5.16/3 has no such rule.
14391     Region = OldRegion;
14392     if (O)
14393       notePostMod(O, BO,
14394                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14395                                                   : UK_ModAsSideEffect);
14396     if (SemaRef.getLangOpts().CPlusPlus17) {
14397       Tree.merge(RHSRegion);
14398       Tree.merge(LHSRegion);
14399     }
14400   }
14401 
14402   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14403     VisitBinAssign(CAO);
14404   }
14405 
14406   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14407   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14408   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14409     Object O = getObject(UO->getSubExpr(), true);
14410     if (!O)
14411       return VisitExpr(UO);
14412 
14413     notePreMod(O, UO);
14414     Visit(UO->getSubExpr());
14415     // C++11 [expr.pre.incr]p1:
14416     //   the expression ++x is equivalent to x+=1
14417     notePostMod(O, UO,
14418                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14419                                                 : UK_ModAsSideEffect);
14420   }
14421 
14422   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14423   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14424   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14425     Object O = getObject(UO->getSubExpr(), true);
14426     if (!O)
14427       return VisitExpr(UO);
14428 
14429     notePreMod(O, UO);
14430     Visit(UO->getSubExpr());
14431     notePostMod(O, UO, UK_ModAsSideEffect);
14432   }
14433 
14434   void VisitBinLOr(const BinaryOperator *BO) {
14435     // C++11 [expr.log.or]p2:
14436     //  If the second expression is evaluated, every value computation and
14437     //  side effect associated with the first expression is sequenced before
14438     //  every value computation and side effect associated with the
14439     //  second expression.
14440     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14441     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14442     SequenceTree::Seq OldRegion = Region;
14443 
14444     EvaluationTracker Eval(*this);
14445     {
14446       SequencedSubexpression Sequenced(*this);
14447       Region = LHSRegion;
14448       Visit(BO->getLHS());
14449     }
14450 
14451     // C++11 [expr.log.or]p1:
14452     //  [...] the second operand is not evaluated if the first operand
14453     //  evaluates to true.
14454     bool EvalResult = false;
14455     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14456     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14457     if (ShouldVisitRHS) {
14458       Region = RHSRegion;
14459       Visit(BO->getRHS());
14460     }
14461 
14462     Region = OldRegion;
14463     Tree.merge(LHSRegion);
14464     Tree.merge(RHSRegion);
14465   }
14466 
14467   void VisitBinLAnd(const BinaryOperator *BO) {
14468     // C++11 [expr.log.and]p2:
14469     //  If the second expression is evaluated, every value computation and
14470     //  side effect associated with the first expression is sequenced before
14471     //  every value computation and side effect associated with the
14472     //  second expression.
14473     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14474     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14475     SequenceTree::Seq OldRegion = Region;
14476 
14477     EvaluationTracker Eval(*this);
14478     {
14479       SequencedSubexpression Sequenced(*this);
14480       Region = LHSRegion;
14481       Visit(BO->getLHS());
14482     }
14483 
14484     // C++11 [expr.log.and]p1:
14485     //  [...] the second operand is not evaluated if the first operand is false.
14486     bool EvalResult = false;
14487     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14488     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14489     if (ShouldVisitRHS) {
14490       Region = RHSRegion;
14491       Visit(BO->getRHS());
14492     }
14493 
14494     Region = OldRegion;
14495     Tree.merge(LHSRegion);
14496     Tree.merge(RHSRegion);
14497   }
14498 
14499   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14500     // C++11 [expr.cond]p1:
14501     //  [...] Every value computation and side effect associated with the first
14502     //  expression is sequenced before every value computation and side effect
14503     //  associated with the second or third expression.
14504     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14505 
14506     // No sequencing is specified between the true and false expression.
14507     // However since exactly one of both is going to be evaluated we can
14508     // consider them to be sequenced. This is needed to avoid warning on
14509     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14510     // both the true and false expressions because we can't evaluate x.
14511     // This will still allow us to detect an expression like (pre C++17)
14512     // "(x ? y += 1 : y += 2) = y".
14513     //
14514     // We don't wrap the visitation of the true and false expression with
14515     // SequencedSubexpression because we don't want to downgrade modifications
14516     // as side effect in the true and false expressions after the visition
14517     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14518     // not warn between the two "y++", but we should warn between the "y++"
14519     // and the "y".
14520     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14521     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14522     SequenceTree::Seq OldRegion = Region;
14523 
14524     EvaluationTracker Eval(*this);
14525     {
14526       SequencedSubexpression Sequenced(*this);
14527       Region = ConditionRegion;
14528       Visit(CO->getCond());
14529     }
14530 
14531     // C++11 [expr.cond]p1:
14532     // [...] The first expression is contextually converted to bool (Clause 4).
14533     // It is evaluated and if it is true, the result of the conditional
14534     // expression is the value of the second expression, otherwise that of the
14535     // third expression. Only one of the second and third expressions is
14536     // evaluated. [...]
14537     bool EvalResult = false;
14538     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14539     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14540     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14541     if (ShouldVisitTrueExpr) {
14542       Region = TrueRegion;
14543       Visit(CO->getTrueExpr());
14544     }
14545     if (ShouldVisitFalseExpr) {
14546       Region = FalseRegion;
14547       Visit(CO->getFalseExpr());
14548     }
14549 
14550     Region = OldRegion;
14551     Tree.merge(ConditionRegion);
14552     Tree.merge(TrueRegion);
14553     Tree.merge(FalseRegion);
14554   }
14555 
14556   void VisitCallExpr(const CallExpr *CE) {
14557     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14558 
14559     if (CE->isUnevaluatedBuiltinCall(Context))
14560       return;
14561 
14562     // C++11 [intro.execution]p15:
14563     //   When calling a function [...], every value computation and side effect
14564     //   associated with any argument expression, or with the postfix expression
14565     //   designating the called function, is sequenced before execution of every
14566     //   expression or statement in the body of the function [and thus before
14567     //   the value computation of its result].
14568     SequencedSubexpression Sequenced(*this);
14569     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14570       // C++17 [expr.call]p5
14571       //   The postfix-expression is sequenced before each expression in the
14572       //   expression-list and any default argument. [...]
14573       SequenceTree::Seq CalleeRegion;
14574       SequenceTree::Seq OtherRegion;
14575       if (SemaRef.getLangOpts().CPlusPlus17) {
14576         CalleeRegion = Tree.allocate(Region);
14577         OtherRegion = Tree.allocate(Region);
14578       } else {
14579         CalleeRegion = Region;
14580         OtherRegion = Region;
14581       }
14582       SequenceTree::Seq OldRegion = Region;
14583 
14584       // Visit the callee expression first.
14585       Region = CalleeRegion;
14586       if (SemaRef.getLangOpts().CPlusPlus17) {
14587         SequencedSubexpression Sequenced(*this);
14588         Visit(CE->getCallee());
14589       } else {
14590         Visit(CE->getCallee());
14591       }
14592 
14593       // Then visit the argument expressions.
14594       Region = OtherRegion;
14595       for (const Expr *Argument : CE->arguments())
14596         Visit(Argument);
14597 
14598       Region = OldRegion;
14599       if (SemaRef.getLangOpts().CPlusPlus17) {
14600         Tree.merge(CalleeRegion);
14601         Tree.merge(OtherRegion);
14602       }
14603     });
14604   }
14605 
14606   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14607     // C++17 [over.match.oper]p2:
14608     //   [...] the operator notation is first transformed to the equivalent
14609     //   function-call notation as summarized in Table 12 (where @ denotes one
14610     //   of the operators covered in the specified subclause). However, the
14611     //   operands are sequenced in the order prescribed for the built-in
14612     //   operator (Clause 8).
14613     //
14614     // From the above only overloaded binary operators and overloaded call
14615     // operators have sequencing rules in C++17 that we need to handle
14616     // separately.
14617     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14618         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14619       return VisitCallExpr(CXXOCE);
14620 
14621     enum {
14622       NoSequencing,
14623       LHSBeforeRHS,
14624       RHSBeforeLHS,
14625       LHSBeforeRest
14626     } SequencingKind;
14627     switch (CXXOCE->getOperator()) {
14628     case OO_Equal:
14629     case OO_PlusEqual:
14630     case OO_MinusEqual:
14631     case OO_StarEqual:
14632     case OO_SlashEqual:
14633     case OO_PercentEqual:
14634     case OO_CaretEqual:
14635     case OO_AmpEqual:
14636     case OO_PipeEqual:
14637     case OO_LessLessEqual:
14638     case OO_GreaterGreaterEqual:
14639       SequencingKind = RHSBeforeLHS;
14640       break;
14641 
14642     case OO_LessLess:
14643     case OO_GreaterGreater:
14644     case OO_AmpAmp:
14645     case OO_PipePipe:
14646     case OO_Comma:
14647     case OO_ArrowStar:
14648     case OO_Subscript:
14649       SequencingKind = LHSBeforeRHS;
14650       break;
14651 
14652     case OO_Call:
14653       SequencingKind = LHSBeforeRest;
14654       break;
14655 
14656     default:
14657       SequencingKind = NoSequencing;
14658       break;
14659     }
14660 
14661     if (SequencingKind == NoSequencing)
14662       return VisitCallExpr(CXXOCE);
14663 
14664     // This is a call, so all subexpressions are sequenced before the result.
14665     SequencedSubexpression Sequenced(*this);
14666 
14667     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14668       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14669              "Should only get there with C++17 and above!");
14670       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14671              "Should only get there with an overloaded binary operator"
14672              " or an overloaded call operator!");
14673 
14674       if (SequencingKind == LHSBeforeRest) {
14675         assert(CXXOCE->getOperator() == OO_Call &&
14676                "We should only have an overloaded call operator here!");
14677 
14678         // This is very similar to VisitCallExpr, except that we only have the
14679         // C++17 case. The postfix-expression is the first argument of the
14680         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14681         // are in the following arguments.
14682         //
14683         // Note that we intentionally do not visit the callee expression since
14684         // it is just a decayed reference to a function.
14685         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14686         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14687         SequenceTree::Seq OldRegion = Region;
14688 
14689         assert(CXXOCE->getNumArgs() >= 1 &&
14690                "An overloaded call operator must have at least one argument"
14691                " for the postfix-expression!");
14692         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14693         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14694                                           CXXOCE->getNumArgs() - 1);
14695 
14696         // Visit the postfix-expression first.
14697         {
14698           Region = PostfixExprRegion;
14699           SequencedSubexpression Sequenced(*this);
14700           Visit(PostfixExpr);
14701         }
14702 
14703         // Then visit the argument expressions.
14704         Region = ArgsRegion;
14705         for (const Expr *Arg : Args)
14706           Visit(Arg);
14707 
14708         Region = OldRegion;
14709         Tree.merge(PostfixExprRegion);
14710         Tree.merge(ArgsRegion);
14711       } else {
14712         assert(CXXOCE->getNumArgs() == 2 &&
14713                "Should only have two arguments here!");
14714         assert((SequencingKind == LHSBeforeRHS ||
14715                 SequencingKind == RHSBeforeLHS) &&
14716                "Unexpected sequencing kind!");
14717 
14718         // We do not visit the callee expression since it is just a decayed
14719         // reference to a function.
14720         const Expr *E1 = CXXOCE->getArg(0);
14721         const Expr *E2 = CXXOCE->getArg(1);
14722         if (SequencingKind == RHSBeforeLHS)
14723           std::swap(E1, E2);
14724 
14725         return VisitSequencedExpressions(E1, E2);
14726       }
14727     });
14728   }
14729 
14730   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14731     // This is a call, so all subexpressions are sequenced before the result.
14732     SequencedSubexpression Sequenced(*this);
14733 
14734     if (!CCE->isListInitialization())
14735       return VisitExpr(CCE);
14736 
14737     // In C++11, list initializations are sequenced.
14738     SmallVector<SequenceTree::Seq, 32> Elts;
14739     SequenceTree::Seq Parent = Region;
14740     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14741                                               E = CCE->arg_end();
14742          I != E; ++I) {
14743       Region = Tree.allocate(Parent);
14744       Elts.push_back(Region);
14745       Visit(*I);
14746     }
14747 
14748     // Forget that the initializers are sequenced.
14749     Region = Parent;
14750     for (unsigned I = 0; I < Elts.size(); ++I)
14751       Tree.merge(Elts[I]);
14752   }
14753 
14754   void VisitInitListExpr(const InitListExpr *ILE) {
14755     if (!SemaRef.getLangOpts().CPlusPlus11)
14756       return VisitExpr(ILE);
14757 
14758     // In C++11, list initializations are sequenced.
14759     SmallVector<SequenceTree::Seq, 32> Elts;
14760     SequenceTree::Seq Parent = Region;
14761     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14762       const Expr *E = ILE->getInit(I);
14763       if (!E)
14764         continue;
14765       Region = Tree.allocate(Parent);
14766       Elts.push_back(Region);
14767       Visit(E);
14768     }
14769 
14770     // Forget that the initializers are sequenced.
14771     Region = Parent;
14772     for (unsigned I = 0; I < Elts.size(); ++I)
14773       Tree.merge(Elts[I]);
14774   }
14775 };
14776 
14777 } // namespace
14778 
14779 void Sema::CheckUnsequencedOperations(const Expr *E) {
14780   SmallVector<const Expr *, 8> WorkList;
14781   WorkList.push_back(E);
14782   while (!WorkList.empty()) {
14783     const Expr *Item = WorkList.pop_back_val();
14784     SequenceChecker(*this, Item, WorkList);
14785   }
14786 }
14787 
14788 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14789                               bool IsConstexpr) {
14790   llvm::SaveAndRestore<bool> ConstantContext(
14791       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14792   CheckImplicitConversions(E, CheckLoc);
14793   if (!E->isInstantiationDependent())
14794     CheckUnsequencedOperations(E);
14795   if (!IsConstexpr && !E->isValueDependent())
14796     CheckForIntOverflow(E);
14797   DiagnoseMisalignedMembers();
14798 }
14799 
14800 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14801                                        FieldDecl *BitField,
14802                                        Expr *Init) {
14803   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14804 }
14805 
14806 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14807                                          SourceLocation Loc) {
14808   if (!PType->isVariablyModifiedType())
14809     return;
14810   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14811     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14812     return;
14813   }
14814   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14815     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14816     return;
14817   }
14818   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14819     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14820     return;
14821   }
14822 
14823   const ArrayType *AT = S.Context.getAsArrayType(PType);
14824   if (!AT)
14825     return;
14826 
14827   if (AT->getSizeModifier() != ArrayType::Star) {
14828     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14829     return;
14830   }
14831 
14832   S.Diag(Loc, diag::err_array_star_in_function_definition);
14833 }
14834 
14835 /// CheckParmsForFunctionDef - Check that the parameters of the given
14836 /// function are appropriate for the definition of a function. This
14837 /// takes care of any checks that cannot be performed on the
14838 /// declaration itself, e.g., that the types of each of the function
14839 /// parameters are complete.
14840 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14841                                     bool CheckParameterNames) {
14842   bool HasInvalidParm = false;
14843   for (ParmVarDecl *Param : Parameters) {
14844     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14845     // function declarator that is part of a function definition of
14846     // that function shall not have incomplete type.
14847     //
14848     // This is also C++ [dcl.fct]p6.
14849     if (!Param->isInvalidDecl() &&
14850         RequireCompleteType(Param->getLocation(), Param->getType(),
14851                             diag::err_typecheck_decl_incomplete_type)) {
14852       Param->setInvalidDecl();
14853       HasInvalidParm = true;
14854     }
14855 
14856     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14857     // declaration of each parameter shall include an identifier.
14858     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14859         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14860       // Diagnose this as an extension in C17 and earlier.
14861       if (!getLangOpts().C2x)
14862         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14863     }
14864 
14865     // C99 6.7.5.3p12:
14866     //   If the function declarator is not part of a definition of that
14867     //   function, parameters may have incomplete type and may use the [*]
14868     //   notation in their sequences of declarator specifiers to specify
14869     //   variable length array types.
14870     QualType PType = Param->getOriginalType();
14871     // FIXME: This diagnostic should point the '[*]' if source-location
14872     // information is added for it.
14873     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14874 
14875     // If the parameter is a c++ class type and it has to be destructed in the
14876     // callee function, declare the destructor so that it can be called by the
14877     // callee function. Do not perform any direct access check on the dtor here.
14878     if (!Param->isInvalidDecl()) {
14879       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14880         if (!ClassDecl->isInvalidDecl() &&
14881             !ClassDecl->hasIrrelevantDestructor() &&
14882             !ClassDecl->isDependentContext() &&
14883             ClassDecl->isParamDestroyedInCallee()) {
14884           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14885           MarkFunctionReferenced(Param->getLocation(), Destructor);
14886           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14887         }
14888       }
14889     }
14890 
14891     // Parameters with the pass_object_size attribute only need to be marked
14892     // constant at function definitions. Because we lack information about
14893     // whether we're on a declaration or definition when we're instantiating the
14894     // attribute, we need to check for constness here.
14895     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14896       if (!Param->getType().isConstQualified())
14897         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14898             << Attr->getSpelling() << 1;
14899 
14900     // Check for parameter names shadowing fields from the class.
14901     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14902       // The owning context for the parameter should be the function, but we
14903       // want to see if this function's declaration context is a record.
14904       DeclContext *DC = Param->getDeclContext();
14905       if (DC && DC->isFunctionOrMethod()) {
14906         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14907           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14908                                      RD, /*DeclIsField*/ false);
14909       }
14910     }
14911   }
14912 
14913   return HasInvalidParm;
14914 }
14915 
14916 Optional<std::pair<CharUnits, CharUnits>>
14917 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14918 
14919 /// Compute the alignment and offset of the base class object given the
14920 /// derived-to-base cast expression and the alignment and offset of the derived
14921 /// class object.
14922 static std::pair<CharUnits, CharUnits>
14923 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14924                                    CharUnits BaseAlignment, CharUnits Offset,
14925                                    ASTContext &Ctx) {
14926   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14927        ++PathI) {
14928     const CXXBaseSpecifier *Base = *PathI;
14929     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14930     if (Base->isVirtual()) {
14931       // The complete object may have a lower alignment than the non-virtual
14932       // alignment of the base, in which case the base may be misaligned. Choose
14933       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14934       // conservative lower bound of the complete object alignment.
14935       CharUnits NonVirtualAlignment =
14936           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14937       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14938       Offset = CharUnits::Zero();
14939     } else {
14940       const ASTRecordLayout &RL =
14941           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14942       Offset += RL.getBaseClassOffset(BaseDecl);
14943     }
14944     DerivedType = Base->getType();
14945   }
14946 
14947   return std::make_pair(BaseAlignment, Offset);
14948 }
14949 
14950 /// Compute the alignment and offset of a binary additive operator.
14951 static Optional<std::pair<CharUnits, CharUnits>>
14952 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14953                                      bool IsSub, ASTContext &Ctx) {
14954   QualType PointeeType = PtrE->getType()->getPointeeType();
14955 
14956   if (!PointeeType->isConstantSizeType())
14957     return llvm::None;
14958 
14959   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14960 
14961   if (!P)
14962     return llvm::None;
14963 
14964   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14965   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14966     CharUnits Offset = EltSize * IdxRes->getExtValue();
14967     if (IsSub)
14968       Offset = -Offset;
14969     return std::make_pair(P->first, P->second + Offset);
14970   }
14971 
14972   // If the integer expression isn't a constant expression, compute the lower
14973   // bound of the alignment using the alignment and offset of the pointer
14974   // expression and the element size.
14975   return std::make_pair(
14976       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14977       CharUnits::Zero());
14978 }
14979 
14980 /// This helper function takes an lvalue expression and returns the alignment of
14981 /// a VarDecl and a constant offset from the VarDecl.
14982 Optional<std::pair<CharUnits, CharUnits>>
14983 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14984   E = E->IgnoreParens();
14985   switch (E->getStmtClass()) {
14986   default:
14987     break;
14988   case Stmt::CStyleCastExprClass:
14989   case Stmt::CXXStaticCastExprClass:
14990   case Stmt::ImplicitCastExprClass: {
14991     auto *CE = cast<CastExpr>(E);
14992     const Expr *From = CE->getSubExpr();
14993     switch (CE->getCastKind()) {
14994     default:
14995       break;
14996     case CK_NoOp:
14997       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14998     case CK_UncheckedDerivedToBase:
14999     case CK_DerivedToBase: {
15000       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15001       if (!P)
15002         break;
15003       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15004                                                 P->second, Ctx);
15005     }
15006     }
15007     break;
15008   }
15009   case Stmt::ArraySubscriptExprClass: {
15010     auto *ASE = cast<ArraySubscriptExpr>(E);
15011     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
15012                                                 false, Ctx);
15013   }
15014   case Stmt::DeclRefExprClass: {
15015     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15016       // FIXME: If VD is captured by copy or is an escaping __block variable,
15017       // use the alignment of VD's type.
15018       if (!VD->getType()->isReferenceType())
15019         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15020       if (VD->hasInit())
15021         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15022     }
15023     break;
15024   }
15025   case Stmt::MemberExprClass: {
15026     auto *ME = cast<MemberExpr>(E);
15027     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15028     if (!FD || FD->getType()->isReferenceType() ||
15029         FD->getParent()->isInvalidDecl())
15030       break;
15031     Optional<std::pair<CharUnits, CharUnits>> P;
15032     if (ME->isArrow())
15033       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15034     else
15035       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15036     if (!P)
15037       break;
15038     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15039     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15040     return std::make_pair(P->first,
15041                           P->second + CharUnits::fromQuantity(Offset));
15042   }
15043   case Stmt::UnaryOperatorClass: {
15044     auto *UO = cast<UnaryOperator>(E);
15045     switch (UO->getOpcode()) {
15046     default:
15047       break;
15048     case UO_Deref:
15049       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
15050     }
15051     break;
15052   }
15053   case Stmt::BinaryOperatorClass: {
15054     auto *BO = cast<BinaryOperator>(E);
15055     auto Opcode = BO->getOpcode();
15056     switch (Opcode) {
15057     default:
15058       break;
15059     case BO_Comma:
15060       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
15061     }
15062     break;
15063   }
15064   }
15065   return llvm::None;
15066 }
15067 
15068 /// This helper function takes a pointer expression and returns the alignment of
15069 /// a VarDecl and a constant offset from the VarDecl.
15070 Optional<std::pair<CharUnits, CharUnits>>
15071 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
15072   E = E->IgnoreParens();
15073   switch (E->getStmtClass()) {
15074   default:
15075     break;
15076   case Stmt::CStyleCastExprClass:
15077   case Stmt::CXXStaticCastExprClass:
15078   case Stmt::ImplicitCastExprClass: {
15079     auto *CE = cast<CastExpr>(E);
15080     const Expr *From = CE->getSubExpr();
15081     switch (CE->getCastKind()) {
15082     default:
15083       break;
15084     case CK_NoOp:
15085       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15086     case CK_ArrayToPointerDecay:
15087       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15088     case CK_UncheckedDerivedToBase:
15089     case CK_DerivedToBase: {
15090       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15091       if (!P)
15092         break;
15093       return getDerivedToBaseAlignmentAndOffset(
15094           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15095     }
15096     }
15097     break;
15098   }
15099   case Stmt::CXXThisExprClass: {
15100     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15101     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
15102     return std::make_pair(Alignment, CharUnits::Zero());
15103   }
15104   case Stmt::UnaryOperatorClass: {
15105     auto *UO = cast<UnaryOperator>(E);
15106     if (UO->getOpcode() == UO_AddrOf)
15107       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
15108     break;
15109   }
15110   case Stmt::BinaryOperatorClass: {
15111     auto *BO = cast<BinaryOperator>(E);
15112     auto Opcode = BO->getOpcode();
15113     switch (Opcode) {
15114     default:
15115       break;
15116     case BO_Add:
15117     case BO_Sub: {
15118       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15119       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15120         std::swap(LHS, RHS);
15121       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15122                                                   Ctx);
15123     }
15124     case BO_Comma:
15125       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15126     }
15127     break;
15128   }
15129   }
15130   return llvm::None;
15131 }
15132 
15133 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
15134   // See if we can compute the alignment of a VarDecl and an offset from it.
15135   Optional<std::pair<CharUnits, CharUnits>> P =
15136       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
15137 
15138   if (P)
15139     return P->first.alignmentAtOffset(P->second);
15140 
15141   // If that failed, return the type's alignment.
15142   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
15143 }
15144 
15145 /// CheckCastAlign - Implements -Wcast-align, which warns when a
15146 /// pointer cast increases the alignment requirements.
15147 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
15148   // This is actually a lot of work to potentially be doing on every
15149   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15150   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15151     return;
15152 
15153   // Ignore dependent types.
15154   if (T->isDependentType() || Op->getType()->isDependentType())
15155     return;
15156 
15157   // Require that the destination be a pointer type.
15158   const PointerType *DestPtr = T->getAs<PointerType>();
15159   if (!DestPtr) return;
15160 
15161   // If the destination has alignment 1, we're done.
15162   QualType DestPointee = DestPtr->getPointeeType();
15163   if (DestPointee->isIncompleteType()) return;
15164   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15165   if (DestAlign.isOne()) return;
15166 
15167   // Require that the source be a pointer type.
15168   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15169   if (!SrcPtr) return;
15170   QualType SrcPointee = SrcPtr->getPointeeType();
15171 
15172   // Explicitly allow casts from cv void*.  We already implicitly
15173   // allowed casts to cv void*, since they have alignment 1.
15174   // Also allow casts involving incomplete types, which implicitly
15175   // includes 'void'.
15176   if (SrcPointee->isIncompleteType()) return;
15177 
15178   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15179 
15180   if (SrcAlign >= DestAlign) return;
15181 
15182   Diag(TRange.getBegin(), diag::warn_cast_align)
15183     << Op->getType() << T
15184     << static_cast<unsigned>(SrcAlign.getQuantity())
15185     << static_cast<unsigned>(DestAlign.getQuantity())
15186     << TRange << Op->getSourceRange();
15187 }
15188 
15189 /// Check whether this array fits the idiom of a size-one tail padded
15190 /// array member of a struct.
15191 ///
15192 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
15193 /// commonly used to emulate flexible arrays in C89 code.
15194 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
15195                                     const NamedDecl *ND) {
15196   if (Size != 1 || !ND) return false;
15197 
15198   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
15199   if (!FD) return false;
15200 
15201   // Don't consider sizes resulting from macro expansions or template argument
15202   // substitution to form C89 tail-padded arrays.
15203 
15204   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
15205   while (TInfo) {
15206     TypeLoc TL = TInfo->getTypeLoc();
15207     // Look through typedefs.
15208     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
15209       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
15210       TInfo = TDL->getTypeSourceInfo();
15211       continue;
15212     }
15213     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
15214       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
15215       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
15216         return false;
15217     }
15218     break;
15219   }
15220 
15221   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
15222   if (!RD) return false;
15223   if (RD->isUnion()) return false;
15224   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15225     if (!CRD->isStandardLayout()) return false;
15226   }
15227 
15228   // See if this is the last field decl in the record.
15229   const Decl *D = FD;
15230   while ((D = D->getNextDeclInContext()))
15231     if (isa<FieldDecl>(D))
15232       return false;
15233   return true;
15234 }
15235 
15236 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15237                             const ArraySubscriptExpr *ASE,
15238                             bool AllowOnePastEnd, bool IndexNegated) {
15239   // Already diagnosed by the constant evaluator.
15240   if (isConstantEvaluated())
15241     return;
15242 
15243   IndexExpr = IndexExpr->IgnoreParenImpCasts();
15244   if (IndexExpr->isValueDependent())
15245     return;
15246 
15247   const Type *EffectiveType =
15248       BaseExpr->getType()->getPointeeOrArrayElementType();
15249   BaseExpr = BaseExpr->IgnoreParenCasts();
15250   const ConstantArrayType *ArrayTy =
15251       Context.getAsConstantArrayType(BaseExpr->getType());
15252 
15253   const Type *BaseType =
15254       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15255   bool IsUnboundedArray = (BaseType == nullptr);
15256   if (EffectiveType->isDependentType() ||
15257       (!IsUnboundedArray && BaseType->isDependentType()))
15258     return;
15259 
15260   Expr::EvalResult Result;
15261   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15262     return;
15263 
15264   llvm::APSInt index = Result.Val.getInt();
15265   if (IndexNegated) {
15266     index.setIsUnsigned(false);
15267     index = -index;
15268   }
15269 
15270   const NamedDecl *ND = nullptr;
15271   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15272     ND = DRE->getDecl();
15273   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
15274     ND = ME->getMemberDecl();
15275 
15276   if (IsUnboundedArray) {
15277     if (index.isUnsigned() || !index.isNegative()) {
15278       const auto &ASTC = getASTContext();
15279       unsigned AddrBits =
15280           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
15281               EffectiveType->getCanonicalTypeInternal()));
15282       if (index.getBitWidth() < AddrBits)
15283         index = index.zext(AddrBits);
15284       Optional<CharUnits> ElemCharUnits =
15285           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15286       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15287       // pointer) bounds-checking isn't meaningful.
15288       if (!ElemCharUnits)
15289         return;
15290       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15291       // If index has more active bits than address space, we already know
15292       // we have a bounds violation to warn about.  Otherwise, compute
15293       // address of (index + 1)th element, and warn about bounds violation
15294       // only if that address exceeds address space.
15295       if (index.getActiveBits() <= AddrBits) {
15296         bool Overflow;
15297         llvm::APInt Product(index);
15298         Product += 1;
15299         Product = Product.umul_ov(ElemBytes, Overflow);
15300         if (!Overflow && Product.getActiveBits() <= AddrBits)
15301           return;
15302       }
15303 
15304       // Need to compute max possible elements in address space, since that
15305       // is included in diag message.
15306       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15307       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15308       MaxElems += 1;
15309       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15310       MaxElems = MaxElems.udiv(ElemBytes);
15311 
15312       unsigned DiagID =
15313           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15314               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15315 
15316       // Diag message shows element size in bits and in "bytes" (platform-
15317       // dependent CharUnits)
15318       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15319                           PDiag(DiagID)
15320                               << toString(index, 10, true) << AddrBits
15321                               << (unsigned)ASTC.toBits(*ElemCharUnits)
15322                               << toString(ElemBytes, 10, false)
15323                               << toString(MaxElems, 10, false)
15324                               << (unsigned)MaxElems.getLimitedValue(~0U)
15325                               << IndexExpr->getSourceRange());
15326 
15327       if (!ND) {
15328         // Try harder to find a NamedDecl to point at in the note.
15329         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15330           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15331         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15332           ND = DRE->getDecl();
15333         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15334           ND = ME->getMemberDecl();
15335       }
15336 
15337       if (ND)
15338         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15339                             PDiag(diag::note_array_declared_here) << ND);
15340     }
15341     return;
15342   }
15343 
15344   if (index.isUnsigned() || !index.isNegative()) {
15345     // It is possible that the type of the base expression after
15346     // IgnoreParenCasts is incomplete, even though the type of the base
15347     // expression before IgnoreParenCasts is complete (see PR39746 for an
15348     // example). In this case we have no information about whether the array
15349     // access exceeds the array bounds. However we can still diagnose an array
15350     // access which precedes the array bounds.
15351     if (BaseType->isIncompleteType())
15352       return;
15353 
15354     llvm::APInt size = ArrayTy->getSize();
15355     if (!size.isStrictlyPositive())
15356       return;
15357 
15358     if (BaseType != EffectiveType) {
15359       // Make sure we're comparing apples to apples when comparing index to size
15360       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15361       uint64_t array_typesize = Context.getTypeSize(BaseType);
15362       // Handle ptrarith_typesize being zero, such as when casting to void*
15363       if (!ptrarith_typesize) ptrarith_typesize = 1;
15364       if (ptrarith_typesize != array_typesize) {
15365         // There's a cast to a different size type involved
15366         uint64_t ratio = array_typesize / ptrarith_typesize;
15367         // TODO: Be smarter about handling cases where array_typesize is not a
15368         // multiple of ptrarith_typesize
15369         if (ptrarith_typesize * ratio == array_typesize)
15370           size *= llvm::APInt(size.getBitWidth(), ratio);
15371       }
15372     }
15373 
15374     if (size.getBitWidth() > index.getBitWidth())
15375       index = index.zext(size.getBitWidth());
15376     else if (size.getBitWidth() < index.getBitWidth())
15377       size = size.zext(index.getBitWidth());
15378 
15379     // For array subscripting the index must be less than size, but for pointer
15380     // arithmetic also allow the index (offset) to be equal to size since
15381     // computing the next address after the end of the array is legal and
15382     // commonly done e.g. in C++ iterators and range-based for loops.
15383     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15384       return;
15385 
15386     // Also don't warn for arrays of size 1 which are members of some
15387     // structure. These are often used to approximate flexible arrays in C89
15388     // code.
15389     if (IsTailPaddedMemberArray(*this, size, ND))
15390       return;
15391 
15392     // Suppress the warning if the subscript expression (as identified by the
15393     // ']' location) and the index expression are both from macro expansions
15394     // within a system header.
15395     if (ASE) {
15396       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15397           ASE->getRBracketLoc());
15398       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15399         SourceLocation IndexLoc =
15400             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15401         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15402           return;
15403       }
15404     }
15405 
15406     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15407                           : diag::warn_ptr_arith_exceeds_bounds;
15408 
15409     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15410                         PDiag(DiagID) << toString(index, 10, true)
15411                                       << toString(size, 10, true)
15412                                       << (unsigned)size.getLimitedValue(~0U)
15413                                       << IndexExpr->getSourceRange());
15414   } else {
15415     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15416     if (!ASE) {
15417       DiagID = diag::warn_ptr_arith_precedes_bounds;
15418       if (index.isNegative()) index = -index;
15419     }
15420 
15421     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15422                         PDiag(DiagID) << toString(index, 10, true)
15423                                       << IndexExpr->getSourceRange());
15424   }
15425 
15426   if (!ND) {
15427     // Try harder to find a NamedDecl to point at in the note.
15428     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15429       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15430     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15431       ND = DRE->getDecl();
15432     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15433       ND = ME->getMemberDecl();
15434   }
15435 
15436   if (ND)
15437     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15438                         PDiag(diag::note_array_declared_here) << ND);
15439 }
15440 
15441 void Sema::CheckArrayAccess(const Expr *expr) {
15442   int AllowOnePastEnd = 0;
15443   while (expr) {
15444     expr = expr->IgnoreParenImpCasts();
15445     switch (expr->getStmtClass()) {
15446       case Stmt::ArraySubscriptExprClass: {
15447         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15448         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15449                          AllowOnePastEnd > 0);
15450         expr = ASE->getBase();
15451         break;
15452       }
15453       case Stmt::MemberExprClass: {
15454         expr = cast<MemberExpr>(expr)->getBase();
15455         break;
15456       }
15457       case Stmt::OMPArraySectionExprClass: {
15458         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15459         if (ASE->getLowerBound())
15460           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15461                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15462         return;
15463       }
15464       case Stmt::UnaryOperatorClass: {
15465         // Only unwrap the * and & unary operators
15466         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15467         expr = UO->getSubExpr();
15468         switch (UO->getOpcode()) {
15469           case UO_AddrOf:
15470             AllowOnePastEnd++;
15471             break;
15472           case UO_Deref:
15473             AllowOnePastEnd--;
15474             break;
15475           default:
15476             return;
15477         }
15478         break;
15479       }
15480       case Stmt::ConditionalOperatorClass: {
15481         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15482         if (const Expr *lhs = cond->getLHS())
15483           CheckArrayAccess(lhs);
15484         if (const Expr *rhs = cond->getRHS())
15485           CheckArrayAccess(rhs);
15486         return;
15487       }
15488       case Stmt::CXXOperatorCallExprClass: {
15489         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15490         for (const auto *Arg : OCE->arguments())
15491           CheckArrayAccess(Arg);
15492         return;
15493       }
15494       default:
15495         return;
15496     }
15497   }
15498 }
15499 
15500 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15501 
15502 namespace {
15503 
15504 struct RetainCycleOwner {
15505   VarDecl *Variable = nullptr;
15506   SourceRange Range;
15507   SourceLocation Loc;
15508   bool Indirect = false;
15509 
15510   RetainCycleOwner() = default;
15511 
15512   void setLocsFrom(Expr *e) {
15513     Loc = e->getExprLoc();
15514     Range = e->getSourceRange();
15515   }
15516 };
15517 
15518 } // namespace
15519 
15520 /// Consider whether capturing the given variable can possibly lead to
15521 /// a retain cycle.
15522 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15523   // In ARC, it's captured strongly iff the variable has __strong
15524   // lifetime.  In MRR, it's captured strongly if the variable is
15525   // __block and has an appropriate type.
15526   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15527     return false;
15528 
15529   owner.Variable = var;
15530   if (ref)
15531     owner.setLocsFrom(ref);
15532   return true;
15533 }
15534 
15535 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15536   while (true) {
15537     e = e->IgnoreParens();
15538     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15539       switch (cast->getCastKind()) {
15540       case CK_BitCast:
15541       case CK_LValueBitCast:
15542       case CK_LValueToRValue:
15543       case CK_ARCReclaimReturnedObject:
15544         e = cast->getSubExpr();
15545         continue;
15546 
15547       default:
15548         return false;
15549       }
15550     }
15551 
15552     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15553       ObjCIvarDecl *ivar = ref->getDecl();
15554       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15555         return false;
15556 
15557       // Try to find a retain cycle in the base.
15558       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15559         return false;
15560 
15561       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15562       owner.Indirect = true;
15563       return true;
15564     }
15565 
15566     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15567       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15568       if (!var) return false;
15569       return considerVariable(var, ref, owner);
15570     }
15571 
15572     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15573       if (member->isArrow()) return false;
15574 
15575       // Don't count this as an indirect ownership.
15576       e = member->getBase();
15577       continue;
15578     }
15579 
15580     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15581       // Only pay attention to pseudo-objects on property references.
15582       ObjCPropertyRefExpr *pre
15583         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15584                                               ->IgnoreParens());
15585       if (!pre) return false;
15586       if (pre->isImplicitProperty()) return false;
15587       ObjCPropertyDecl *property = pre->getExplicitProperty();
15588       if (!property->isRetaining() &&
15589           !(property->getPropertyIvarDecl() &&
15590             property->getPropertyIvarDecl()->getType()
15591               .getObjCLifetime() == Qualifiers::OCL_Strong))
15592           return false;
15593 
15594       owner.Indirect = true;
15595       if (pre->isSuperReceiver()) {
15596         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15597         if (!owner.Variable)
15598           return false;
15599         owner.Loc = pre->getLocation();
15600         owner.Range = pre->getSourceRange();
15601         return true;
15602       }
15603       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15604                               ->getSourceExpr());
15605       continue;
15606     }
15607 
15608     // Array ivars?
15609 
15610     return false;
15611   }
15612 }
15613 
15614 namespace {
15615 
15616   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15617     ASTContext &Context;
15618     VarDecl *Variable;
15619     Expr *Capturer = nullptr;
15620     bool VarWillBeReased = false;
15621 
15622     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15623         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15624           Context(Context), Variable(variable) {}
15625 
15626     void VisitDeclRefExpr(DeclRefExpr *ref) {
15627       if (ref->getDecl() == Variable && !Capturer)
15628         Capturer = ref;
15629     }
15630 
15631     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15632       if (Capturer) return;
15633       Visit(ref->getBase());
15634       if (Capturer && ref->isFreeIvar())
15635         Capturer = ref;
15636     }
15637 
15638     void VisitBlockExpr(BlockExpr *block) {
15639       // Look inside nested blocks
15640       if (block->getBlockDecl()->capturesVariable(Variable))
15641         Visit(block->getBlockDecl()->getBody());
15642     }
15643 
15644     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15645       if (Capturer) return;
15646       if (OVE->getSourceExpr())
15647         Visit(OVE->getSourceExpr());
15648     }
15649 
15650     void VisitBinaryOperator(BinaryOperator *BinOp) {
15651       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15652         return;
15653       Expr *LHS = BinOp->getLHS();
15654       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15655         if (DRE->getDecl() != Variable)
15656           return;
15657         if (Expr *RHS = BinOp->getRHS()) {
15658           RHS = RHS->IgnoreParenCasts();
15659           Optional<llvm::APSInt> Value;
15660           VarWillBeReased =
15661               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15662                *Value == 0);
15663         }
15664       }
15665     }
15666   };
15667 
15668 } // namespace
15669 
15670 /// Check whether the given argument is a block which captures a
15671 /// variable.
15672 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15673   assert(owner.Variable && owner.Loc.isValid());
15674 
15675   e = e->IgnoreParenCasts();
15676 
15677   // Look through [^{...} copy] and Block_copy(^{...}).
15678   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15679     Selector Cmd = ME->getSelector();
15680     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15681       e = ME->getInstanceReceiver();
15682       if (!e)
15683         return nullptr;
15684       e = e->IgnoreParenCasts();
15685     }
15686   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15687     if (CE->getNumArgs() == 1) {
15688       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15689       if (Fn) {
15690         const IdentifierInfo *FnI = Fn->getIdentifier();
15691         if (FnI && FnI->isStr("_Block_copy")) {
15692           e = CE->getArg(0)->IgnoreParenCasts();
15693         }
15694       }
15695     }
15696   }
15697 
15698   BlockExpr *block = dyn_cast<BlockExpr>(e);
15699   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15700     return nullptr;
15701 
15702   FindCaptureVisitor visitor(S.Context, owner.Variable);
15703   visitor.Visit(block->getBlockDecl()->getBody());
15704   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15705 }
15706 
15707 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15708                                 RetainCycleOwner &owner) {
15709   assert(capturer);
15710   assert(owner.Variable && owner.Loc.isValid());
15711 
15712   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15713     << owner.Variable << capturer->getSourceRange();
15714   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15715     << owner.Indirect << owner.Range;
15716 }
15717 
15718 /// Check for a keyword selector that starts with the word 'add' or
15719 /// 'set'.
15720 static bool isSetterLikeSelector(Selector sel) {
15721   if (sel.isUnarySelector()) return false;
15722 
15723   StringRef str = sel.getNameForSlot(0);
15724   while (!str.empty() && str.front() == '_') str = str.substr(1);
15725   if (str.startswith("set"))
15726     str = str.substr(3);
15727   else if (str.startswith("add")) {
15728     // Specially allow 'addOperationWithBlock:'.
15729     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15730       return false;
15731     str = str.substr(3);
15732   }
15733   else
15734     return false;
15735 
15736   if (str.empty()) return true;
15737   return !isLowercase(str.front());
15738 }
15739 
15740 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15741                                                     ObjCMessageExpr *Message) {
15742   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15743                                                 Message->getReceiverInterface(),
15744                                                 NSAPI::ClassId_NSMutableArray);
15745   if (!IsMutableArray) {
15746     return None;
15747   }
15748 
15749   Selector Sel = Message->getSelector();
15750 
15751   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15752     S.NSAPIObj->getNSArrayMethodKind(Sel);
15753   if (!MKOpt) {
15754     return None;
15755   }
15756 
15757   NSAPI::NSArrayMethodKind MK = *MKOpt;
15758 
15759   switch (MK) {
15760     case NSAPI::NSMutableArr_addObject:
15761     case NSAPI::NSMutableArr_insertObjectAtIndex:
15762     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15763       return 0;
15764     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15765       return 1;
15766 
15767     default:
15768       return None;
15769   }
15770 
15771   return None;
15772 }
15773 
15774 static
15775 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15776                                                   ObjCMessageExpr *Message) {
15777   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15778                                             Message->getReceiverInterface(),
15779                                             NSAPI::ClassId_NSMutableDictionary);
15780   if (!IsMutableDictionary) {
15781     return None;
15782   }
15783 
15784   Selector Sel = Message->getSelector();
15785 
15786   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15787     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15788   if (!MKOpt) {
15789     return None;
15790   }
15791 
15792   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15793 
15794   switch (MK) {
15795     case NSAPI::NSMutableDict_setObjectForKey:
15796     case NSAPI::NSMutableDict_setValueForKey:
15797     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15798       return 0;
15799 
15800     default:
15801       return None;
15802   }
15803 
15804   return None;
15805 }
15806 
15807 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15808   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15809                                                 Message->getReceiverInterface(),
15810                                                 NSAPI::ClassId_NSMutableSet);
15811 
15812   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15813                                             Message->getReceiverInterface(),
15814                                             NSAPI::ClassId_NSMutableOrderedSet);
15815   if (!IsMutableSet && !IsMutableOrderedSet) {
15816     return None;
15817   }
15818 
15819   Selector Sel = Message->getSelector();
15820 
15821   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15822   if (!MKOpt) {
15823     return None;
15824   }
15825 
15826   NSAPI::NSSetMethodKind MK = *MKOpt;
15827 
15828   switch (MK) {
15829     case NSAPI::NSMutableSet_addObject:
15830     case NSAPI::NSOrderedSet_setObjectAtIndex:
15831     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15832     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15833       return 0;
15834     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15835       return 1;
15836   }
15837 
15838   return None;
15839 }
15840 
15841 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15842   if (!Message->isInstanceMessage()) {
15843     return;
15844   }
15845 
15846   Optional<int> ArgOpt;
15847 
15848   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15849       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15850       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15851     return;
15852   }
15853 
15854   int ArgIndex = *ArgOpt;
15855 
15856   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15857   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15858     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15859   }
15860 
15861   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15862     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15863       if (ArgRE->isObjCSelfExpr()) {
15864         Diag(Message->getSourceRange().getBegin(),
15865              diag::warn_objc_circular_container)
15866           << ArgRE->getDecl() << StringRef("'super'");
15867       }
15868     }
15869   } else {
15870     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15871 
15872     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15873       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15874     }
15875 
15876     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15877       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15878         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15879           ValueDecl *Decl = ReceiverRE->getDecl();
15880           Diag(Message->getSourceRange().getBegin(),
15881                diag::warn_objc_circular_container)
15882             << Decl << Decl;
15883           if (!ArgRE->isObjCSelfExpr()) {
15884             Diag(Decl->getLocation(),
15885                  diag::note_objc_circular_container_declared_here)
15886               << Decl;
15887           }
15888         }
15889       }
15890     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15891       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15892         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15893           ObjCIvarDecl *Decl = IvarRE->getDecl();
15894           Diag(Message->getSourceRange().getBegin(),
15895                diag::warn_objc_circular_container)
15896             << Decl << Decl;
15897           Diag(Decl->getLocation(),
15898                diag::note_objc_circular_container_declared_here)
15899             << Decl;
15900         }
15901       }
15902     }
15903   }
15904 }
15905 
15906 /// Check a message send to see if it's likely to cause a retain cycle.
15907 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15908   // Only check instance methods whose selector looks like a setter.
15909   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15910     return;
15911 
15912   // Try to find a variable that the receiver is strongly owned by.
15913   RetainCycleOwner owner;
15914   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15915     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15916       return;
15917   } else {
15918     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15919     owner.Variable = getCurMethodDecl()->getSelfDecl();
15920     owner.Loc = msg->getSuperLoc();
15921     owner.Range = msg->getSuperLoc();
15922   }
15923 
15924   // Check whether the receiver is captured by any of the arguments.
15925   const ObjCMethodDecl *MD = msg->getMethodDecl();
15926   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15927     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15928       // noescape blocks should not be retained by the method.
15929       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15930         continue;
15931       return diagnoseRetainCycle(*this, capturer, owner);
15932     }
15933   }
15934 }
15935 
15936 /// Check a property assign to see if it's likely to cause a retain cycle.
15937 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15938   RetainCycleOwner owner;
15939   if (!findRetainCycleOwner(*this, receiver, owner))
15940     return;
15941 
15942   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15943     diagnoseRetainCycle(*this, capturer, owner);
15944 }
15945 
15946 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15947   RetainCycleOwner Owner;
15948   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15949     return;
15950 
15951   // Because we don't have an expression for the variable, we have to set the
15952   // location explicitly here.
15953   Owner.Loc = Var->getLocation();
15954   Owner.Range = Var->getSourceRange();
15955 
15956   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15957     diagnoseRetainCycle(*this, Capturer, Owner);
15958 }
15959 
15960 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15961                                      Expr *RHS, bool isProperty) {
15962   // Check if RHS is an Objective-C object literal, which also can get
15963   // immediately zapped in a weak reference.  Note that we explicitly
15964   // allow ObjCStringLiterals, since those are designed to never really die.
15965   RHS = RHS->IgnoreParenImpCasts();
15966 
15967   // This enum needs to match with the 'select' in
15968   // warn_objc_arc_literal_assign (off-by-1).
15969   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15970   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15971     return false;
15972 
15973   S.Diag(Loc, diag::warn_arc_literal_assign)
15974     << (unsigned) Kind
15975     << (isProperty ? 0 : 1)
15976     << RHS->getSourceRange();
15977 
15978   return true;
15979 }
15980 
15981 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15982                                     Qualifiers::ObjCLifetime LT,
15983                                     Expr *RHS, bool isProperty) {
15984   // Strip off any implicit cast added to get to the one ARC-specific.
15985   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15986     if (cast->getCastKind() == CK_ARCConsumeObject) {
15987       S.Diag(Loc, diag::warn_arc_retained_assign)
15988         << (LT == Qualifiers::OCL_ExplicitNone)
15989         << (isProperty ? 0 : 1)
15990         << RHS->getSourceRange();
15991       return true;
15992     }
15993     RHS = cast->getSubExpr();
15994   }
15995 
15996   if (LT == Qualifiers::OCL_Weak &&
15997       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15998     return true;
15999 
16000   return false;
16001 }
16002 
16003 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
16004                               QualType LHS, Expr *RHS) {
16005   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
16006 
16007   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
16008     return false;
16009 
16010   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
16011     return true;
16012 
16013   return false;
16014 }
16015 
16016 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
16017                               Expr *LHS, Expr *RHS) {
16018   QualType LHSType;
16019   // PropertyRef on LHS type need be directly obtained from
16020   // its declaration as it has a PseudoType.
16021   ObjCPropertyRefExpr *PRE
16022     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
16023   if (PRE && !PRE->isImplicitProperty()) {
16024     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16025     if (PD)
16026       LHSType = PD->getType();
16027   }
16028 
16029   if (LHSType.isNull())
16030     LHSType = LHS->getType();
16031 
16032   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
16033 
16034   if (LT == Qualifiers::OCL_Weak) {
16035     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
16036       getCurFunction()->markSafeWeakUse(LHS);
16037   }
16038 
16039   if (checkUnsafeAssigns(Loc, LHSType, RHS))
16040     return;
16041 
16042   // FIXME. Check for other life times.
16043   if (LT != Qualifiers::OCL_None)
16044     return;
16045 
16046   if (PRE) {
16047     if (PRE->isImplicitProperty())
16048       return;
16049     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16050     if (!PD)
16051       return;
16052 
16053     unsigned Attributes = PD->getPropertyAttributes();
16054     if (Attributes & ObjCPropertyAttribute::kind_assign) {
16055       // when 'assign' attribute was not explicitly specified
16056       // by user, ignore it and rely on property type itself
16057       // for lifetime info.
16058       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16059       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16060           LHSType->isObjCRetainableType())
16061         return;
16062 
16063       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16064         if (cast->getCastKind() == CK_ARCConsumeObject) {
16065           Diag(Loc, diag::warn_arc_retained_property_assign)
16066           << RHS->getSourceRange();
16067           return;
16068         }
16069         RHS = cast->getSubExpr();
16070       }
16071     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16072       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
16073         return;
16074     }
16075   }
16076 }
16077 
16078 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16079 
16080 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16081                                         SourceLocation StmtLoc,
16082                                         const NullStmt *Body) {
16083   // Do not warn if the body is a macro that expands to nothing, e.g:
16084   //
16085   // #define CALL(x)
16086   // if (condition)
16087   //   CALL(0);
16088   if (Body->hasLeadingEmptyMacro())
16089     return false;
16090 
16091   // Get line numbers of statement and body.
16092   bool StmtLineInvalid;
16093   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16094                                                       &StmtLineInvalid);
16095   if (StmtLineInvalid)
16096     return false;
16097 
16098   bool BodyLineInvalid;
16099   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16100                                                       &BodyLineInvalid);
16101   if (BodyLineInvalid)
16102     return false;
16103 
16104   // Warn if null statement and body are on the same line.
16105   if (StmtLine != BodyLine)
16106     return false;
16107 
16108   return true;
16109 }
16110 
16111 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
16112                                  const Stmt *Body,
16113                                  unsigned DiagID) {
16114   // Since this is a syntactic check, don't emit diagnostic for template
16115   // instantiations, this just adds noise.
16116   if (CurrentInstantiationScope)
16117     return;
16118 
16119   // The body should be a null statement.
16120   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16121   if (!NBody)
16122     return;
16123 
16124   // Do the usual checks.
16125   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16126     return;
16127 
16128   Diag(NBody->getSemiLoc(), DiagID);
16129   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16130 }
16131 
16132 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
16133                                  const Stmt *PossibleBody) {
16134   assert(!CurrentInstantiationScope); // Ensured by caller
16135 
16136   SourceLocation StmtLoc;
16137   const Stmt *Body;
16138   unsigned DiagID;
16139   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16140     StmtLoc = FS->getRParenLoc();
16141     Body = FS->getBody();
16142     DiagID = diag::warn_empty_for_body;
16143   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16144     StmtLoc = WS->getCond()->getSourceRange().getEnd();
16145     Body = WS->getBody();
16146     DiagID = diag::warn_empty_while_body;
16147   } else
16148     return; // Neither `for' nor `while'.
16149 
16150   // The body should be a null statement.
16151   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16152   if (!NBody)
16153     return;
16154 
16155   // Skip expensive checks if diagnostic is disabled.
16156   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16157     return;
16158 
16159   // Do the usual checks.
16160   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16161     return;
16162 
16163   // `for(...);' and `while(...);' are popular idioms, so in order to keep
16164   // noise level low, emit diagnostics only if for/while is followed by a
16165   // CompoundStmt, e.g.:
16166   //    for (int i = 0; i < n; i++);
16167   //    {
16168   //      a(i);
16169   //    }
16170   // or if for/while is followed by a statement with more indentation
16171   // than for/while itself:
16172   //    for (int i = 0; i < n; i++);
16173   //      a(i);
16174   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16175   if (!ProbableTypo) {
16176     bool BodyColInvalid;
16177     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16178         PossibleBody->getBeginLoc(), &BodyColInvalid);
16179     if (BodyColInvalid)
16180       return;
16181 
16182     bool StmtColInvalid;
16183     unsigned StmtCol =
16184         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16185     if (StmtColInvalid)
16186       return;
16187 
16188     if (BodyCol > StmtCol)
16189       ProbableTypo = true;
16190   }
16191 
16192   if (ProbableTypo) {
16193     Diag(NBody->getSemiLoc(), DiagID);
16194     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16195   }
16196 }
16197 
16198 //===--- CHECK: Warn on self move with std::move. -------------------------===//
16199 
16200 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
16201 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16202                              SourceLocation OpLoc) {
16203   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16204     return;
16205 
16206   if (inTemplateInstantiation())
16207     return;
16208 
16209   // Strip parens and casts away.
16210   LHSExpr = LHSExpr->IgnoreParenImpCasts();
16211   RHSExpr = RHSExpr->IgnoreParenImpCasts();
16212 
16213   // Check for a call expression
16214   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
16215   if (!CE || CE->getNumArgs() != 1)
16216     return;
16217 
16218   // Check for a call to std::move
16219   if (!CE->isCallToStdMove())
16220     return;
16221 
16222   // Get argument from std::move
16223   RHSExpr = CE->getArg(0);
16224 
16225   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16226   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16227 
16228   // Two DeclRefExpr's, check that the decls are the same.
16229   if (LHSDeclRef && RHSDeclRef) {
16230     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16231       return;
16232     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16233         RHSDeclRef->getDecl()->getCanonicalDecl())
16234       return;
16235 
16236     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16237                                         << LHSExpr->getSourceRange()
16238                                         << RHSExpr->getSourceRange();
16239     return;
16240   }
16241 
16242   // Member variables require a different approach to check for self moves.
16243   // MemberExpr's are the same if every nested MemberExpr refers to the same
16244   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16245   // the base Expr's are CXXThisExpr's.
16246   const Expr *LHSBase = LHSExpr;
16247   const Expr *RHSBase = RHSExpr;
16248   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16249   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16250   if (!LHSME || !RHSME)
16251     return;
16252 
16253   while (LHSME && RHSME) {
16254     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16255         RHSME->getMemberDecl()->getCanonicalDecl())
16256       return;
16257 
16258     LHSBase = LHSME->getBase();
16259     RHSBase = RHSME->getBase();
16260     LHSME = dyn_cast<MemberExpr>(LHSBase);
16261     RHSME = dyn_cast<MemberExpr>(RHSBase);
16262   }
16263 
16264   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16265   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16266   if (LHSDeclRef && RHSDeclRef) {
16267     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16268       return;
16269     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16270         RHSDeclRef->getDecl()->getCanonicalDecl())
16271       return;
16272 
16273     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16274                                         << LHSExpr->getSourceRange()
16275                                         << RHSExpr->getSourceRange();
16276     return;
16277   }
16278 
16279   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16280     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16281                                         << LHSExpr->getSourceRange()
16282                                         << RHSExpr->getSourceRange();
16283 }
16284 
16285 //===--- Layout compatibility ----------------------------------------------//
16286 
16287 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
16288 
16289 /// Check if two enumeration types are layout-compatible.
16290 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
16291   // C++11 [dcl.enum] p8:
16292   // Two enumeration types are layout-compatible if they have the same
16293   // underlying type.
16294   return ED1->isComplete() && ED2->isComplete() &&
16295          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16296 }
16297 
16298 /// Check if two fields are layout-compatible.
16299 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
16300                                FieldDecl *Field2) {
16301   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16302     return false;
16303 
16304   if (Field1->isBitField() != Field2->isBitField())
16305     return false;
16306 
16307   if (Field1->isBitField()) {
16308     // Make sure that the bit-fields are the same length.
16309     unsigned Bits1 = Field1->getBitWidthValue(C);
16310     unsigned Bits2 = Field2->getBitWidthValue(C);
16311 
16312     if (Bits1 != Bits2)
16313       return false;
16314   }
16315 
16316   return true;
16317 }
16318 
16319 /// Check if two standard-layout structs are layout-compatible.
16320 /// (C++11 [class.mem] p17)
16321 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
16322                                      RecordDecl *RD2) {
16323   // If both records are C++ classes, check that base classes match.
16324   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
16325     // If one of records is a CXXRecordDecl we are in C++ mode,
16326     // thus the other one is a CXXRecordDecl, too.
16327     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
16328     // Check number of base classes.
16329     if (D1CXX->getNumBases() != D2CXX->getNumBases())
16330       return false;
16331 
16332     // Check the base classes.
16333     for (CXXRecordDecl::base_class_const_iterator
16334                Base1 = D1CXX->bases_begin(),
16335            BaseEnd1 = D1CXX->bases_end(),
16336               Base2 = D2CXX->bases_begin();
16337          Base1 != BaseEnd1;
16338          ++Base1, ++Base2) {
16339       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16340         return false;
16341     }
16342   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16343     // If only RD2 is a C++ class, it should have zero base classes.
16344     if (D2CXX->getNumBases() > 0)
16345       return false;
16346   }
16347 
16348   // Check the fields.
16349   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16350                              Field2End = RD2->field_end(),
16351                              Field1 = RD1->field_begin(),
16352                              Field1End = RD1->field_end();
16353   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16354     if (!isLayoutCompatible(C, *Field1, *Field2))
16355       return false;
16356   }
16357   if (Field1 != Field1End || Field2 != Field2End)
16358     return false;
16359 
16360   return true;
16361 }
16362 
16363 /// Check if two standard-layout unions are layout-compatible.
16364 /// (C++11 [class.mem] p18)
16365 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16366                                     RecordDecl *RD2) {
16367   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16368   for (auto *Field2 : RD2->fields())
16369     UnmatchedFields.insert(Field2);
16370 
16371   for (auto *Field1 : RD1->fields()) {
16372     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16373         I = UnmatchedFields.begin(),
16374         E = UnmatchedFields.end();
16375 
16376     for ( ; I != E; ++I) {
16377       if (isLayoutCompatible(C, Field1, *I)) {
16378         bool Result = UnmatchedFields.erase(*I);
16379         (void) Result;
16380         assert(Result);
16381         break;
16382       }
16383     }
16384     if (I == E)
16385       return false;
16386   }
16387 
16388   return UnmatchedFields.empty();
16389 }
16390 
16391 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16392                                RecordDecl *RD2) {
16393   if (RD1->isUnion() != RD2->isUnion())
16394     return false;
16395 
16396   if (RD1->isUnion())
16397     return isLayoutCompatibleUnion(C, RD1, RD2);
16398   else
16399     return isLayoutCompatibleStruct(C, RD1, RD2);
16400 }
16401 
16402 /// Check if two types are layout-compatible in C++11 sense.
16403 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16404   if (T1.isNull() || T2.isNull())
16405     return false;
16406 
16407   // C++11 [basic.types] p11:
16408   // If two types T1 and T2 are the same type, then T1 and T2 are
16409   // layout-compatible types.
16410   if (C.hasSameType(T1, T2))
16411     return true;
16412 
16413   T1 = T1.getCanonicalType().getUnqualifiedType();
16414   T2 = T2.getCanonicalType().getUnqualifiedType();
16415 
16416   const Type::TypeClass TC1 = T1->getTypeClass();
16417   const Type::TypeClass TC2 = T2->getTypeClass();
16418 
16419   if (TC1 != TC2)
16420     return false;
16421 
16422   if (TC1 == Type::Enum) {
16423     return isLayoutCompatible(C,
16424                               cast<EnumType>(T1)->getDecl(),
16425                               cast<EnumType>(T2)->getDecl());
16426   } else if (TC1 == Type::Record) {
16427     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16428       return false;
16429 
16430     return isLayoutCompatible(C,
16431                               cast<RecordType>(T1)->getDecl(),
16432                               cast<RecordType>(T2)->getDecl());
16433   }
16434 
16435   return false;
16436 }
16437 
16438 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16439 
16440 /// Given a type tag expression find the type tag itself.
16441 ///
16442 /// \param TypeExpr Type tag expression, as it appears in user's code.
16443 ///
16444 /// \param VD Declaration of an identifier that appears in a type tag.
16445 ///
16446 /// \param MagicValue Type tag magic value.
16447 ///
16448 /// \param isConstantEvaluated whether the evalaution should be performed in
16449 
16450 /// constant context.
16451 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16452                             const ValueDecl **VD, uint64_t *MagicValue,
16453                             bool isConstantEvaluated) {
16454   while(true) {
16455     if (!TypeExpr)
16456       return false;
16457 
16458     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16459 
16460     switch (TypeExpr->getStmtClass()) {
16461     case Stmt::UnaryOperatorClass: {
16462       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16463       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16464         TypeExpr = UO->getSubExpr();
16465         continue;
16466       }
16467       return false;
16468     }
16469 
16470     case Stmt::DeclRefExprClass: {
16471       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16472       *VD = DRE->getDecl();
16473       return true;
16474     }
16475 
16476     case Stmt::IntegerLiteralClass: {
16477       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16478       llvm::APInt MagicValueAPInt = IL->getValue();
16479       if (MagicValueAPInt.getActiveBits() <= 64) {
16480         *MagicValue = MagicValueAPInt.getZExtValue();
16481         return true;
16482       } else
16483         return false;
16484     }
16485 
16486     case Stmt::BinaryConditionalOperatorClass:
16487     case Stmt::ConditionalOperatorClass: {
16488       const AbstractConditionalOperator *ACO =
16489           cast<AbstractConditionalOperator>(TypeExpr);
16490       bool Result;
16491       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16492                                                      isConstantEvaluated)) {
16493         if (Result)
16494           TypeExpr = ACO->getTrueExpr();
16495         else
16496           TypeExpr = ACO->getFalseExpr();
16497         continue;
16498       }
16499       return false;
16500     }
16501 
16502     case Stmt::BinaryOperatorClass: {
16503       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16504       if (BO->getOpcode() == BO_Comma) {
16505         TypeExpr = BO->getRHS();
16506         continue;
16507       }
16508       return false;
16509     }
16510 
16511     default:
16512       return false;
16513     }
16514   }
16515 }
16516 
16517 /// Retrieve the C type corresponding to type tag TypeExpr.
16518 ///
16519 /// \param TypeExpr Expression that specifies a type tag.
16520 ///
16521 /// \param MagicValues Registered magic values.
16522 ///
16523 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16524 ///        kind.
16525 ///
16526 /// \param TypeInfo Information about the corresponding C type.
16527 ///
16528 /// \param isConstantEvaluated whether the evalaution should be performed in
16529 /// constant context.
16530 ///
16531 /// \returns true if the corresponding C type was found.
16532 static bool GetMatchingCType(
16533     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16534     const ASTContext &Ctx,
16535     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16536         *MagicValues,
16537     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16538     bool isConstantEvaluated) {
16539   FoundWrongKind = false;
16540 
16541   // Variable declaration that has type_tag_for_datatype attribute.
16542   const ValueDecl *VD = nullptr;
16543 
16544   uint64_t MagicValue;
16545 
16546   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16547     return false;
16548 
16549   if (VD) {
16550     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16551       if (I->getArgumentKind() != ArgumentKind) {
16552         FoundWrongKind = true;
16553         return false;
16554       }
16555       TypeInfo.Type = I->getMatchingCType();
16556       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16557       TypeInfo.MustBeNull = I->getMustBeNull();
16558       return true;
16559     }
16560     return false;
16561   }
16562 
16563   if (!MagicValues)
16564     return false;
16565 
16566   llvm::DenseMap<Sema::TypeTagMagicValue,
16567                  Sema::TypeTagData>::const_iterator I =
16568       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16569   if (I == MagicValues->end())
16570     return false;
16571 
16572   TypeInfo = I->second;
16573   return true;
16574 }
16575 
16576 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16577                                       uint64_t MagicValue, QualType Type,
16578                                       bool LayoutCompatible,
16579                                       bool MustBeNull) {
16580   if (!TypeTagForDatatypeMagicValues)
16581     TypeTagForDatatypeMagicValues.reset(
16582         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16583 
16584   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16585   (*TypeTagForDatatypeMagicValues)[Magic] =
16586       TypeTagData(Type, LayoutCompatible, MustBeNull);
16587 }
16588 
16589 static bool IsSameCharType(QualType T1, QualType T2) {
16590   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16591   if (!BT1)
16592     return false;
16593 
16594   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16595   if (!BT2)
16596     return false;
16597 
16598   BuiltinType::Kind T1Kind = BT1->getKind();
16599   BuiltinType::Kind T2Kind = BT2->getKind();
16600 
16601   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16602          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16603          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16604          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16605 }
16606 
16607 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16608                                     const ArrayRef<const Expr *> ExprArgs,
16609                                     SourceLocation CallSiteLoc) {
16610   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16611   bool IsPointerAttr = Attr->getIsPointer();
16612 
16613   // Retrieve the argument representing the 'type_tag'.
16614   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16615   if (TypeTagIdxAST >= ExprArgs.size()) {
16616     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16617         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16618     return;
16619   }
16620   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16621   bool FoundWrongKind;
16622   TypeTagData TypeInfo;
16623   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16624                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16625                         TypeInfo, isConstantEvaluated())) {
16626     if (FoundWrongKind)
16627       Diag(TypeTagExpr->getExprLoc(),
16628            diag::warn_type_tag_for_datatype_wrong_kind)
16629         << TypeTagExpr->getSourceRange();
16630     return;
16631   }
16632 
16633   // Retrieve the argument representing the 'arg_idx'.
16634   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16635   if (ArgumentIdxAST >= ExprArgs.size()) {
16636     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16637         << 1 << Attr->getArgumentIdx().getSourceIndex();
16638     return;
16639   }
16640   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16641   if (IsPointerAttr) {
16642     // Skip implicit cast of pointer to `void *' (as a function argument).
16643     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16644       if (ICE->getType()->isVoidPointerType() &&
16645           ICE->getCastKind() == CK_BitCast)
16646         ArgumentExpr = ICE->getSubExpr();
16647   }
16648   QualType ArgumentType = ArgumentExpr->getType();
16649 
16650   // Passing a `void*' pointer shouldn't trigger a warning.
16651   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16652     return;
16653 
16654   if (TypeInfo.MustBeNull) {
16655     // Type tag with matching void type requires a null pointer.
16656     if (!ArgumentExpr->isNullPointerConstant(Context,
16657                                              Expr::NPC_ValueDependentIsNotNull)) {
16658       Diag(ArgumentExpr->getExprLoc(),
16659            diag::warn_type_safety_null_pointer_required)
16660           << ArgumentKind->getName()
16661           << ArgumentExpr->getSourceRange()
16662           << TypeTagExpr->getSourceRange();
16663     }
16664     return;
16665   }
16666 
16667   QualType RequiredType = TypeInfo.Type;
16668   if (IsPointerAttr)
16669     RequiredType = Context.getPointerType(RequiredType);
16670 
16671   bool mismatch = false;
16672   if (!TypeInfo.LayoutCompatible) {
16673     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16674 
16675     // C++11 [basic.fundamental] p1:
16676     // Plain char, signed char, and unsigned char are three distinct types.
16677     //
16678     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16679     // char' depending on the current char signedness mode.
16680     if (mismatch)
16681       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16682                                            RequiredType->getPointeeType())) ||
16683           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16684         mismatch = false;
16685   } else
16686     if (IsPointerAttr)
16687       mismatch = !isLayoutCompatible(Context,
16688                                      ArgumentType->getPointeeType(),
16689                                      RequiredType->getPointeeType());
16690     else
16691       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16692 
16693   if (mismatch)
16694     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16695         << ArgumentType << ArgumentKind
16696         << TypeInfo.LayoutCompatible << RequiredType
16697         << ArgumentExpr->getSourceRange()
16698         << TypeTagExpr->getSourceRange();
16699 }
16700 
16701 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16702                                          CharUnits Alignment) {
16703   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16704 }
16705 
16706 void Sema::DiagnoseMisalignedMembers() {
16707   for (MisalignedMember &m : MisalignedMembers) {
16708     const NamedDecl *ND = m.RD;
16709     if (ND->getName().empty()) {
16710       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16711         ND = TD;
16712     }
16713     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16714         << m.MD << ND << m.E->getSourceRange();
16715   }
16716   MisalignedMembers.clear();
16717 }
16718 
16719 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16720   E = E->IgnoreParens();
16721   if (!T->isPointerType() && !T->isIntegerType())
16722     return;
16723   if (isa<UnaryOperator>(E) &&
16724       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16725     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16726     if (isa<MemberExpr>(Op)) {
16727       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16728       if (MA != MisalignedMembers.end() &&
16729           (T->isIntegerType() ||
16730            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16731                                    Context.getTypeAlignInChars(
16732                                        T->getPointeeType()) <= MA->Alignment))))
16733         MisalignedMembers.erase(MA);
16734     }
16735   }
16736 }
16737 
16738 void Sema::RefersToMemberWithReducedAlignment(
16739     Expr *E,
16740     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16741         Action) {
16742   const auto *ME = dyn_cast<MemberExpr>(E);
16743   if (!ME)
16744     return;
16745 
16746   // No need to check expressions with an __unaligned-qualified type.
16747   if (E->getType().getQualifiers().hasUnaligned())
16748     return;
16749 
16750   // For a chain of MemberExpr like "a.b.c.d" this list
16751   // will keep FieldDecl's like [d, c, b].
16752   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16753   const MemberExpr *TopME = nullptr;
16754   bool AnyIsPacked = false;
16755   do {
16756     QualType BaseType = ME->getBase()->getType();
16757     if (BaseType->isDependentType())
16758       return;
16759     if (ME->isArrow())
16760       BaseType = BaseType->getPointeeType();
16761     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16762     if (RD->isInvalidDecl())
16763       return;
16764 
16765     ValueDecl *MD = ME->getMemberDecl();
16766     auto *FD = dyn_cast<FieldDecl>(MD);
16767     // We do not care about non-data members.
16768     if (!FD || FD->isInvalidDecl())
16769       return;
16770 
16771     AnyIsPacked =
16772         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16773     ReverseMemberChain.push_back(FD);
16774 
16775     TopME = ME;
16776     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16777   } while (ME);
16778   assert(TopME && "We did not compute a topmost MemberExpr!");
16779 
16780   // Not the scope of this diagnostic.
16781   if (!AnyIsPacked)
16782     return;
16783 
16784   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16785   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16786   // TODO: The innermost base of the member expression may be too complicated.
16787   // For now, just disregard these cases. This is left for future
16788   // improvement.
16789   if (!DRE && !isa<CXXThisExpr>(TopBase))
16790       return;
16791 
16792   // Alignment expected by the whole expression.
16793   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16794 
16795   // No need to do anything else with this case.
16796   if (ExpectedAlignment.isOne())
16797     return;
16798 
16799   // Synthesize offset of the whole access.
16800   CharUnits Offset;
16801   for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16802     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16803 
16804   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16805   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16806       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16807 
16808   // The base expression of the innermost MemberExpr may give
16809   // stronger guarantees than the class containing the member.
16810   if (DRE && !TopME->isArrow()) {
16811     const ValueDecl *VD = DRE->getDecl();
16812     if (!VD->getType()->isReferenceType())
16813       CompleteObjectAlignment =
16814           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16815   }
16816 
16817   // Check if the synthesized offset fulfills the alignment.
16818   if (Offset % ExpectedAlignment != 0 ||
16819       // It may fulfill the offset it but the effective alignment may still be
16820       // lower than the expected expression alignment.
16821       CompleteObjectAlignment < ExpectedAlignment) {
16822     // If this happens, we want to determine a sensible culprit of this.
16823     // Intuitively, watching the chain of member expressions from right to
16824     // left, we start with the required alignment (as required by the field
16825     // type) but some packed attribute in that chain has reduced the alignment.
16826     // It may happen that another packed structure increases it again. But if
16827     // we are here such increase has not been enough. So pointing the first
16828     // FieldDecl that either is packed or else its RecordDecl is,
16829     // seems reasonable.
16830     FieldDecl *FD = nullptr;
16831     CharUnits Alignment;
16832     for (FieldDecl *FDI : ReverseMemberChain) {
16833       if (FDI->hasAttr<PackedAttr>() ||
16834           FDI->getParent()->hasAttr<PackedAttr>()) {
16835         FD = FDI;
16836         Alignment = std::min(
16837             Context.getTypeAlignInChars(FD->getType()),
16838             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16839         break;
16840       }
16841     }
16842     assert(FD && "We did not find a packed FieldDecl!");
16843     Action(E, FD->getParent(), FD, Alignment);
16844   }
16845 }
16846 
16847 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16848   using namespace std::placeholders;
16849 
16850   RefersToMemberWithReducedAlignment(
16851       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16852                      _2, _3, _4));
16853 }
16854 
16855 // Check if \p Ty is a valid type for the elementwise math builtins. If it is
16856 // not a valid type, emit an error message and return true. Otherwise return
16857 // false.
16858 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc,
16859                                         QualType Ty) {
16860   if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) {
16861     S.Diag(Loc, diag::err_builtin_invalid_arg_type)
16862         << 1 << /* vector, integer or float ty*/ 0 << Ty;
16863     return true;
16864   }
16865   return false;
16866 }
16867 
16868 bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) {
16869   if (checkArgCount(*this, TheCall, 1))
16870     return true;
16871 
16872   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16873   if (A.isInvalid())
16874     return true;
16875 
16876   TheCall->setArg(0, A.get());
16877   QualType TyA = A.get()->getType();
16878 
16879   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
16880     return true;
16881 
16882   TheCall->setType(TyA);
16883   return false;
16884 }
16885 
16886 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) {
16887   if (checkArgCount(*this, TheCall, 2))
16888     return true;
16889 
16890   ExprResult A = TheCall->getArg(0);
16891   ExprResult B = TheCall->getArg(1);
16892   // Do standard promotions between the two arguments, returning their common
16893   // type.
16894   QualType Res =
16895       UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
16896   if (A.isInvalid() || B.isInvalid())
16897     return true;
16898 
16899   QualType TyA = A.get()->getType();
16900   QualType TyB = B.get()->getType();
16901 
16902   if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
16903     return Diag(A.get()->getBeginLoc(),
16904                 diag::err_typecheck_call_different_arg_types)
16905            << TyA << TyB;
16906 
16907   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
16908     return true;
16909 
16910   TheCall->setArg(0, A.get());
16911   TheCall->setArg(1, B.get());
16912   TheCall->setType(Res);
16913   return false;
16914 }
16915 
16916 bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
16917   if (checkArgCount(*this, TheCall, 1))
16918     return true;
16919 
16920   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16921   if (A.isInvalid())
16922     return true;
16923 
16924   TheCall->setArg(0, A.get());
16925   return false;
16926 }
16927 
16928 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16929                                             ExprResult CallResult) {
16930   if (checkArgCount(*this, TheCall, 1))
16931     return ExprError();
16932 
16933   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16934   if (MatrixArg.isInvalid())
16935     return MatrixArg;
16936   Expr *Matrix = MatrixArg.get();
16937 
16938   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16939   if (!MType) {
16940     Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16941         << 1 << /* matrix ty*/ 1 << Matrix->getType();
16942     return ExprError();
16943   }
16944 
16945   // Create returned matrix type by swapping rows and columns of the argument
16946   // matrix type.
16947   QualType ResultType = Context.getConstantMatrixType(
16948       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16949 
16950   // Change the return type to the type of the returned matrix.
16951   TheCall->setType(ResultType);
16952 
16953   // Update call argument to use the possibly converted matrix argument.
16954   TheCall->setArg(0, Matrix);
16955   return CallResult;
16956 }
16957 
16958 // Get and verify the matrix dimensions.
16959 static llvm::Optional<unsigned>
16960 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16961   SourceLocation ErrorPos;
16962   Optional<llvm::APSInt> Value =
16963       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16964   if (!Value) {
16965     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16966         << Name;
16967     return {};
16968   }
16969   uint64_t Dim = Value->getZExtValue();
16970   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16971     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16972         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16973     return {};
16974   }
16975   return Dim;
16976 }
16977 
16978 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16979                                                   ExprResult CallResult) {
16980   if (!getLangOpts().MatrixTypes) {
16981     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16982     return ExprError();
16983   }
16984 
16985   if (checkArgCount(*this, TheCall, 4))
16986     return ExprError();
16987 
16988   unsigned PtrArgIdx = 0;
16989   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16990   Expr *RowsExpr = TheCall->getArg(1);
16991   Expr *ColumnsExpr = TheCall->getArg(2);
16992   Expr *StrideExpr = TheCall->getArg(3);
16993 
16994   bool ArgError = false;
16995 
16996   // Check pointer argument.
16997   {
16998     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16999     if (PtrConv.isInvalid())
17000       return PtrConv;
17001     PtrExpr = PtrConv.get();
17002     TheCall->setArg(0, PtrExpr);
17003     if (PtrExpr->isTypeDependent()) {
17004       TheCall->setType(Context.DependentTy);
17005       return TheCall;
17006     }
17007   }
17008 
17009   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17010   QualType ElementTy;
17011   if (!PtrTy) {
17012     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17013         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17014     ArgError = true;
17015   } else {
17016     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17017 
17018     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
17019       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17020           << PtrArgIdx + 1 << /* pointer to element ty*/ 2
17021           << PtrExpr->getType();
17022       ArgError = true;
17023     }
17024   }
17025 
17026   // Apply default Lvalue conversions and convert the expression to size_t.
17027   auto ApplyArgumentConversions = [this](Expr *E) {
17028     ExprResult Conv = DefaultLvalueConversion(E);
17029     if (Conv.isInvalid())
17030       return Conv;
17031 
17032     return tryConvertExprToType(Conv.get(), Context.getSizeType());
17033   };
17034 
17035   // Apply conversion to row and column expressions.
17036   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17037   if (!RowsConv.isInvalid()) {
17038     RowsExpr = RowsConv.get();
17039     TheCall->setArg(1, RowsExpr);
17040   } else
17041     RowsExpr = nullptr;
17042 
17043   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17044   if (!ColumnsConv.isInvalid()) {
17045     ColumnsExpr = ColumnsConv.get();
17046     TheCall->setArg(2, ColumnsExpr);
17047   } else
17048     ColumnsExpr = nullptr;
17049 
17050   // If any any part of the result matrix type is still pending, just use
17051   // Context.DependentTy, until all parts are resolved.
17052   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17053       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17054     TheCall->setType(Context.DependentTy);
17055     return CallResult;
17056   }
17057 
17058   // Check row and column dimensions.
17059   llvm::Optional<unsigned> MaybeRows;
17060   if (RowsExpr)
17061     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17062 
17063   llvm::Optional<unsigned> MaybeColumns;
17064   if (ColumnsExpr)
17065     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17066 
17067   // Check stride argument.
17068   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17069   if (StrideConv.isInvalid())
17070     return ExprError();
17071   StrideExpr = StrideConv.get();
17072   TheCall->setArg(3, StrideExpr);
17073 
17074   if (MaybeRows) {
17075     if (Optional<llvm::APSInt> Value =
17076             StrideExpr->getIntegerConstantExpr(Context)) {
17077       uint64_t Stride = Value->getZExtValue();
17078       if (Stride < *MaybeRows) {
17079         Diag(StrideExpr->getBeginLoc(),
17080              diag::err_builtin_matrix_stride_too_small);
17081         ArgError = true;
17082       }
17083     }
17084   }
17085 
17086   if (ArgError || !MaybeRows || !MaybeColumns)
17087     return ExprError();
17088 
17089   TheCall->setType(
17090       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17091   return CallResult;
17092 }
17093 
17094 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17095                                                    ExprResult CallResult) {
17096   if (checkArgCount(*this, TheCall, 3))
17097     return ExprError();
17098 
17099   unsigned PtrArgIdx = 1;
17100   Expr *MatrixExpr = TheCall->getArg(0);
17101   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17102   Expr *StrideExpr = TheCall->getArg(2);
17103 
17104   bool ArgError = false;
17105 
17106   {
17107     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17108     if (MatrixConv.isInvalid())
17109       return MatrixConv;
17110     MatrixExpr = MatrixConv.get();
17111     TheCall->setArg(0, MatrixExpr);
17112   }
17113   if (MatrixExpr->isTypeDependent()) {
17114     TheCall->setType(Context.DependentTy);
17115     return TheCall;
17116   }
17117 
17118   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17119   if (!MatrixTy) {
17120     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17121         << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
17122     ArgError = true;
17123   }
17124 
17125   {
17126     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17127     if (PtrConv.isInvalid())
17128       return PtrConv;
17129     PtrExpr = PtrConv.get();
17130     TheCall->setArg(1, PtrExpr);
17131     if (PtrExpr->isTypeDependent()) {
17132       TheCall->setType(Context.DependentTy);
17133       return TheCall;
17134     }
17135   }
17136 
17137   // Check pointer argument.
17138   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17139   if (!PtrTy) {
17140     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17141         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17142     ArgError = true;
17143   } else {
17144     QualType ElementTy = PtrTy->getPointeeType();
17145     if (ElementTy.isConstQualified()) {
17146       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17147       ArgError = true;
17148     }
17149     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17150     if (MatrixTy &&
17151         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17152       Diag(PtrExpr->getBeginLoc(),
17153            diag::err_builtin_matrix_pointer_arg_mismatch)
17154           << ElementTy << MatrixTy->getElementType();
17155       ArgError = true;
17156     }
17157   }
17158 
17159   // Apply default Lvalue conversions and convert the stride expression to
17160   // size_t.
17161   {
17162     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17163     if (StrideConv.isInvalid())
17164       return StrideConv;
17165 
17166     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17167     if (StrideConv.isInvalid())
17168       return StrideConv;
17169     StrideExpr = StrideConv.get();
17170     TheCall->setArg(2, StrideExpr);
17171   }
17172 
17173   // Check stride argument.
17174   if (MatrixTy) {
17175     if (Optional<llvm::APSInt> Value =
17176             StrideExpr->getIntegerConstantExpr(Context)) {
17177       uint64_t Stride = Value->getZExtValue();
17178       if (Stride < MatrixTy->getNumRows()) {
17179         Diag(StrideExpr->getBeginLoc(),
17180              diag::err_builtin_matrix_stride_too_small);
17181         ArgError = true;
17182       }
17183     }
17184   }
17185 
17186   if (ArgError)
17187     return ExprError();
17188 
17189   return CallResult;
17190 }
17191 
17192 /// \brief Enforce the bounds of a TCB
17193 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
17194 /// directly calls other functions in the same TCB as marked by the enforce_tcb
17195 /// and enforce_tcb_leaf attributes.
17196 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
17197                                const FunctionDecl *Callee) {
17198   const FunctionDecl *Caller = getCurFunctionDecl();
17199 
17200   // Calls to builtins are not enforced.
17201   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
17202       Callee->getBuiltinID() != 0)
17203     return;
17204 
17205   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17206   // all TCBs the callee is a part of.
17207   llvm::StringSet<> CalleeTCBs;
17208   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
17209            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17210   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
17211            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17212 
17213   // Go through the TCBs the caller is a part of and emit warnings if Caller
17214   // is in a TCB that the Callee is not.
17215   for_each(
17216       Caller->specific_attrs<EnforceTCBAttr>(),
17217       [&](const auto *A) {
17218         StringRef CallerTCB = A->getTCBName();
17219         if (CalleeTCBs.count(CallerTCB) == 0) {
17220           this->Diag(TheCall->getExprLoc(),
17221                      diag::warn_tcb_enforcement_violation) << Callee
17222                                                            << CallerTCB;
17223         }
17224       });
17225 }
17226