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   case Builtin::BI__builtin_alloca_with_align_uninitialized:
1754     if (SemaBuiltinAllocaWithAlign(TheCall))
1755       return ExprError();
1756     LLVM_FALLTHROUGH;
1757   case Builtin::BI__builtin_alloca:
1758   case Builtin::BI__builtin_alloca_uninitialized:
1759     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1760         << TheCall->getDirectCallee();
1761     break;
1762   case Builtin::BI__arithmetic_fence:
1763     if (SemaBuiltinArithmeticFence(TheCall))
1764       return ExprError();
1765     break;
1766   case Builtin::BI__assume:
1767   case Builtin::BI__builtin_assume:
1768     if (SemaBuiltinAssume(TheCall))
1769       return ExprError();
1770     break;
1771   case Builtin::BI__builtin_assume_aligned:
1772     if (SemaBuiltinAssumeAligned(TheCall))
1773       return ExprError();
1774     break;
1775   case Builtin::BI__builtin_dynamic_object_size:
1776   case Builtin::BI__builtin_object_size:
1777     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1778       return ExprError();
1779     break;
1780   case Builtin::BI__builtin_longjmp:
1781     if (SemaBuiltinLongjmp(TheCall))
1782       return ExprError();
1783     break;
1784   case Builtin::BI__builtin_setjmp:
1785     if (SemaBuiltinSetjmp(TheCall))
1786       return ExprError();
1787     break;
1788   case Builtin::BI__builtin_classify_type:
1789     if (checkArgCount(*this, TheCall, 1)) return true;
1790     TheCall->setType(Context.IntTy);
1791     break;
1792   case Builtin::BI__builtin_complex:
1793     if (SemaBuiltinComplex(TheCall))
1794       return ExprError();
1795     break;
1796   case Builtin::BI__builtin_constant_p: {
1797     if (checkArgCount(*this, TheCall, 1)) return true;
1798     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1799     if (Arg.isInvalid()) return true;
1800     TheCall->setArg(0, Arg.get());
1801     TheCall->setType(Context.IntTy);
1802     break;
1803   }
1804   case Builtin::BI__builtin_launder:
1805     return SemaBuiltinLaunder(*this, TheCall);
1806   case Builtin::BI__sync_fetch_and_add:
1807   case Builtin::BI__sync_fetch_and_add_1:
1808   case Builtin::BI__sync_fetch_and_add_2:
1809   case Builtin::BI__sync_fetch_and_add_4:
1810   case Builtin::BI__sync_fetch_and_add_8:
1811   case Builtin::BI__sync_fetch_and_add_16:
1812   case Builtin::BI__sync_fetch_and_sub:
1813   case Builtin::BI__sync_fetch_and_sub_1:
1814   case Builtin::BI__sync_fetch_and_sub_2:
1815   case Builtin::BI__sync_fetch_and_sub_4:
1816   case Builtin::BI__sync_fetch_and_sub_8:
1817   case Builtin::BI__sync_fetch_and_sub_16:
1818   case Builtin::BI__sync_fetch_and_or:
1819   case Builtin::BI__sync_fetch_and_or_1:
1820   case Builtin::BI__sync_fetch_and_or_2:
1821   case Builtin::BI__sync_fetch_and_or_4:
1822   case Builtin::BI__sync_fetch_and_or_8:
1823   case Builtin::BI__sync_fetch_and_or_16:
1824   case Builtin::BI__sync_fetch_and_and:
1825   case Builtin::BI__sync_fetch_and_and_1:
1826   case Builtin::BI__sync_fetch_and_and_2:
1827   case Builtin::BI__sync_fetch_and_and_4:
1828   case Builtin::BI__sync_fetch_and_and_8:
1829   case Builtin::BI__sync_fetch_and_and_16:
1830   case Builtin::BI__sync_fetch_and_xor:
1831   case Builtin::BI__sync_fetch_and_xor_1:
1832   case Builtin::BI__sync_fetch_and_xor_2:
1833   case Builtin::BI__sync_fetch_and_xor_4:
1834   case Builtin::BI__sync_fetch_and_xor_8:
1835   case Builtin::BI__sync_fetch_and_xor_16:
1836   case Builtin::BI__sync_fetch_and_nand:
1837   case Builtin::BI__sync_fetch_and_nand_1:
1838   case Builtin::BI__sync_fetch_and_nand_2:
1839   case Builtin::BI__sync_fetch_and_nand_4:
1840   case Builtin::BI__sync_fetch_and_nand_8:
1841   case Builtin::BI__sync_fetch_and_nand_16:
1842   case Builtin::BI__sync_add_and_fetch:
1843   case Builtin::BI__sync_add_and_fetch_1:
1844   case Builtin::BI__sync_add_and_fetch_2:
1845   case Builtin::BI__sync_add_and_fetch_4:
1846   case Builtin::BI__sync_add_and_fetch_8:
1847   case Builtin::BI__sync_add_and_fetch_16:
1848   case Builtin::BI__sync_sub_and_fetch:
1849   case Builtin::BI__sync_sub_and_fetch_1:
1850   case Builtin::BI__sync_sub_and_fetch_2:
1851   case Builtin::BI__sync_sub_and_fetch_4:
1852   case Builtin::BI__sync_sub_and_fetch_8:
1853   case Builtin::BI__sync_sub_and_fetch_16:
1854   case Builtin::BI__sync_and_and_fetch:
1855   case Builtin::BI__sync_and_and_fetch_1:
1856   case Builtin::BI__sync_and_and_fetch_2:
1857   case Builtin::BI__sync_and_and_fetch_4:
1858   case Builtin::BI__sync_and_and_fetch_8:
1859   case Builtin::BI__sync_and_and_fetch_16:
1860   case Builtin::BI__sync_or_and_fetch:
1861   case Builtin::BI__sync_or_and_fetch_1:
1862   case Builtin::BI__sync_or_and_fetch_2:
1863   case Builtin::BI__sync_or_and_fetch_4:
1864   case Builtin::BI__sync_or_and_fetch_8:
1865   case Builtin::BI__sync_or_and_fetch_16:
1866   case Builtin::BI__sync_xor_and_fetch:
1867   case Builtin::BI__sync_xor_and_fetch_1:
1868   case Builtin::BI__sync_xor_and_fetch_2:
1869   case Builtin::BI__sync_xor_and_fetch_4:
1870   case Builtin::BI__sync_xor_and_fetch_8:
1871   case Builtin::BI__sync_xor_and_fetch_16:
1872   case Builtin::BI__sync_nand_and_fetch:
1873   case Builtin::BI__sync_nand_and_fetch_1:
1874   case Builtin::BI__sync_nand_and_fetch_2:
1875   case Builtin::BI__sync_nand_and_fetch_4:
1876   case Builtin::BI__sync_nand_and_fetch_8:
1877   case Builtin::BI__sync_nand_and_fetch_16:
1878   case Builtin::BI__sync_val_compare_and_swap:
1879   case Builtin::BI__sync_val_compare_and_swap_1:
1880   case Builtin::BI__sync_val_compare_and_swap_2:
1881   case Builtin::BI__sync_val_compare_and_swap_4:
1882   case Builtin::BI__sync_val_compare_and_swap_8:
1883   case Builtin::BI__sync_val_compare_and_swap_16:
1884   case Builtin::BI__sync_bool_compare_and_swap:
1885   case Builtin::BI__sync_bool_compare_and_swap_1:
1886   case Builtin::BI__sync_bool_compare_and_swap_2:
1887   case Builtin::BI__sync_bool_compare_and_swap_4:
1888   case Builtin::BI__sync_bool_compare_and_swap_8:
1889   case Builtin::BI__sync_bool_compare_and_swap_16:
1890   case Builtin::BI__sync_lock_test_and_set:
1891   case Builtin::BI__sync_lock_test_and_set_1:
1892   case Builtin::BI__sync_lock_test_and_set_2:
1893   case Builtin::BI__sync_lock_test_and_set_4:
1894   case Builtin::BI__sync_lock_test_and_set_8:
1895   case Builtin::BI__sync_lock_test_and_set_16:
1896   case Builtin::BI__sync_lock_release:
1897   case Builtin::BI__sync_lock_release_1:
1898   case Builtin::BI__sync_lock_release_2:
1899   case Builtin::BI__sync_lock_release_4:
1900   case Builtin::BI__sync_lock_release_8:
1901   case Builtin::BI__sync_lock_release_16:
1902   case Builtin::BI__sync_swap:
1903   case Builtin::BI__sync_swap_1:
1904   case Builtin::BI__sync_swap_2:
1905   case Builtin::BI__sync_swap_4:
1906   case Builtin::BI__sync_swap_8:
1907   case Builtin::BI__sync_swap_16:
1908     return SemaBuiltinAtomicOverloaded(TheCallResult);
1909   case Builtin::BI__sync_synchronize:
1910     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1911         << TheCall->getCallee()->getSourceRange();
1912     break;
1913   case Builtin::BI__builtin_nontemporal_load:
1914   case Builtin::BI__builtin_nontemporal_store:
1915     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1916   case Builtin::BI__builtin_memcpy_inline: {
1917     clang::Expr *SizeOp = TheCall->getArg(2);
1918     // We warn about copying to or from `nullptr` pointers when `size` is
1919     // greater than 0. When `size` is value dependent we cannot evaluate its
1920     // value so we bail out.
1921     if (SizeOp->isValueDependent())
1922       break;
1923     if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
1924       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1925       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1926     }
1927     break;
1928   }
1929 #define BUILTIN(ID, TYPE, ATTRS)
1930 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1931   case Builtin::BI##ID: \
1932     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1933 #include "clang/Basic/Builtins.def"
1934   case Builtin::BI__annotation:
1935     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1936       return ExprError();
1937     break;
1938   case Builtin::BI__builtin_annotation:
1939     if (SemaBuiltinAnnotation(*this, TheCall))
1940       return ExprError();
1941     break;
1942   case Builtin::BI__builtin_addressof:
1943     if (SemaBuiltinAddressof(*this, TheCall))
1944       return ExprError();
1945     break;
1946   case Builtin::BI__builtin_function_start:
1947     if (SemaBuiltinFunctionStart(*this, TheCall))
1948       return ExprError();
1949     break;
1950   case Builtin::BI__builtin_is_aligned:
1951   case Builtin::BI__builtin_align_up:
1952   case Builtin::BI__builtin_align_down:
1953     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1954       return ExprError();
1955     break;
1956   case Builtin::BI__builtin_add_overflow:
1957   case Builtin::BI__builtin_sub_overflow:
1958   case Builtin::BI__builtin_mul_overflow:
1959     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1960       return ExprError();
1961     break;
1962   case Builtin::BI__builtin_operator_new:
1963   case Builtin::BI__builtin_operator_delete: {
1964     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1965     ExprResult Res =
1966         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1967     if (Res.isInvalid())
1968       CorrectDelayedTyposInExpr(TheCallResult.get());
1969     return Res;
1970   }
1971   case Builtin::BI__builtin_dump_struct: {
1972     // We first want to ensure we are called with 2 arguments
1973     if (checkArgCount(*this, TheCall, 2))
1974       return ExprError();
1975     // Ensure that the first argument is of type 'struct XX *'
1976     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1977     const QualType PtrArgType = PtrArg->getType();
1978     if (!PtrArgType->isPointerType() ||
1979         !PtrArgType->getPointeeType()->isRecordType()) {
1980       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1981           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1982           << "structure pointer";
1983       return ExprError();
1984     }
1985 
1986     // Ensure that the second argument is of type 'FunctionType'
1987     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1988     const QualType FnPtrArgType = FnPtrArg->getType();
1989     if (!FnPtrArgType->isPointerType()) {
1990       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1991           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1992           << FnPtrArgType << "'int (*)(const char *, ...)'";
1993       return ExprError();
1994     }
1995 
1996     const auto *FuncType =
1997         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1998 
1999     if (!FuncType) {
2000       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2001           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
2002           << FnPtrArgType << "'int (*)(const char *, ...)'";
2003       return ExprError();
2004     }
2005 
2006     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
2007       if (!FT->getNumParams()) {
2008         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2009             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
2010             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
2011         return ExprError();
2012       }
2013       QualType PT = FT->getParamType(0);
2014       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
2015           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
2016           !PT->getPointeeType().isConstQualified()) {
2017         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2018             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
2019             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
2020         return ExprError();
2021       }
2022     }
2023 
2024     TheCall->setType(Context.IntTy);
2025     break;
2026   }
2027   case Builtin::BI__builtin_expect_with_probability: {
2028     // We first want to ensure we are called with 3 arguments
2029     if (checkArgCount(*this, TheCall, 3))
2030       return ExprError();
2031     // then check probability is constant float in range [0.0, 1.0]
2032     const Expr *ProbArg = TheCall->getArg(2);
2033     SmallVector<PartialDiagnosticAt, 8> Notes;
2034     Expr::EvalResult Eval;
2035     Eval.Diag = &Notes;
2036     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
2037         !Eval.Val.isFloat()) {
2038       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
2039           << ProbArg->getSourceRange();
2040       for (const PartialDiagnosticAt &PDiag : Notes)
2041         Diag(PDiag.first, PDiag.second);
2042       return ExprError();
2043     }
2044     llvm::APFloat Probability = Eval.Val.getFloat();
2045     bool LoseInfo = false;
2046     Probability.convert(llvm::APFloat::IEEEdouble(),
2047                         llvm::RoundingMode::Dynamic, &LoseInfo);
2048     if (!(Probability >= llvm::APFloat(0.0) &&
2049           Probability <= llvm::APFloat(1.0))) {
2050       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
2051           << ProbArg->getSourceRange();
2052       return ExprError();
2053     }
2054     break;
2055   }
2056   case Builtin::BI__builtin_preserve_access_index:
2057     if (SemaBuiltinPreserveAI(*this, TheCall))
2058       return ExprError();
2059     break;
2060   case Builtin::BI__builtin_call_with_static_chain:
2061     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
2062       return ExprError();
2063     break;
2064   case Builtin::BI__exception_code:
2065   case Builtin::BI_exception_code:
2066     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
2067                                  diag::err_seh___except_block))
2068       return ExprError();
2069     break;
2070   case Builtin::BI__exception_info:
2071   case Builtin::BI_exception_info:
2072     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
2073                                  diag::err_seh___except_filter))
2074       return ExprError();
2075     break;
2076   case Builtin::BI__GetExceptionInfo:
2077     if (checkArgCount(*this, TheCall, 1))
2078       return ExprError();
2079 
2080     if (CheckCXXThrowOperand(
2081             TheCall->getBeginLoc(),
2082             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
2083             TheCall))
2084       return ExprError();
2085 
2086     TheCall->setType(Context.VoidPtrTy);
2087     break;
2088   // OpenCL v2.0, s6.13.16 - Pipe functions
2089   case Builtin::BIread_pipe:
2090   case Builtin::BIwrite_pipe:
2091     // Since those two functions are declared with var args, we need a semantic
2092     // check for the argument.
2093     if (SemaBuiltinRWPipe(*this, TheCall))
2094       return ExprError();
2095     break;
2096   case Builtin::BIreserve_read_pipe:
2097   case Builtin::BIreserve_write_pipe:
2098   case Builtin::BIwork_group_reserve_read_pipe:
2099   case Builtin::BIwork_group_reserve_write_pipe:
2100     if (SemaBuiltinReserveRWPipe(*this, TheCall))
2101       return ExprError();
2102     break;
2103   case Builtin::BIsub_group_reserve_read_pipe:
2104   case Builtin::BIsub_group_reserve_write_pipe:
2105     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2106         SemaBuiltinReserveRWPipe(*this, TheCall))
2107       return ExprError();
2108     break;
2109   case Builtin::BIcommit_read_pipe:
2110   case Builtin::BIcommit_write_pipe:
2111   case Builtin::BIwork_group_commit_read_pipe:
2112   case Builtin::BIwork_group_commit_write_pipe:
2113     if (SemaBuiltinCommitRWPipe(*this, TheCall))
2114       return ExprError();
2115     break;
2116   case Builtin::BIsub_group_commit_read_pipe:
2117   case Builtin::BIsub_group_commit_write_pipe:
2118     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2119         SemaBuiltinCommitRWPipe(*this, TheCall))
2120       return ExprError();
2121     break;
2122   case Builtin::BIget_pipe_num_packets:
2123   case Builtin::BIget_pipe_max_packets:
2124     if (SemaBuiltinPipePackets(*this, TheCall))
2125       return ExprError();
2126     break;
2127   case Builtin::BIto_global:
2128   case Builtin::BIto_local:
2129   case Builtin::BIto_private:
2130     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
2131       return ExprError();
2132     break;
2133   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
2134   case Builtin::BIenqueue_kernel:
2135     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
2136       return ExprError();
2137     break;
2138   case Builtin::BIget_kernel_work_group_size:
2139   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
2140     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
2141       return ExprError();
2142     break;
2143   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
2144   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
2145     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
2146       return ExprError();
2147     break;
2148   case Builtin::BI__builtin_os_log_format:
2149     Cleanup.setExprNeedsCleanups(true);
2150     LLVM_FALLTHROUGH;
2151   case Builtin::BI__builtin_os_log_format_buffer_size:
2152     if (SemaBuiltinOSLogFormat(TheCall))
2153       return ExprError();
2154     break;
2155   case Builtin::BI__builtin_frame_address:
2156   case Builtin::BI__builtin_return_address: {
2157     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
2158       return ExprError();
2159 
2160     // -Wframe-address warning if non-zero passed to builtin
2161     // return/frame address.
2162     Expr::EvalResult Result;
2163     if (!TheCall->getArg(0)->isValueDependent() &&
2164         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
2165         Result.Val.getInt() != 0)
2166       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
2167           << ((BuiltinID == Builtin::BI__builtin_return_address)
2168                   ? "__builtin_return_address"
2169                   : "__builtin_frame_address")
2170           << TheCall->getSourceRange();
2171     break;
2172   }
2173 
2174   // __builtin_elementwise_abs restricts the element type to signed integers or
2175   // floating point types only.
2176   case Builtin::BI__builtin_elementwise_abs: {
2177     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2178       return ExprError();
2179 
2180     QualType ArgTy = TheCall->getArg(0)->getType();
2181     QualType EltTy = ArgTy;
2182 
2183     if (auto *VecTy = EltTy->getAs<VectorType>())
2184       EltTy = VecTy->getElementType();
2185     if (EltTy->isUnsignedIntegerType()) {
2186       Diag(TheCall->getArg(0)->getBeginLoc(),
2187            diag::err_builtin_invalid_arg_type)
2188           << 1 << /* signed integer or float ty*/ 3 << ArgTy;
2189       return ExprError();
2190     }
2191     break;
2192   }
2193 
2194   // These builtins restrict the element type to floating point
2195   // types only.
2196   case Builtin::BI__builtin_elementwise_ceil:
2197   case Builtin::BI__builtin_elementwise_floor:
2198   case Builtin::BI__builtin_elementwise_roundeven:
2199   case Builtin::BI__builtin_elementwise_trunc: {
2200     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2201       return ExprError();
2202 
2203     QualType ArgTy = TheCall->getArg(0)->getType();
2204     QualType EltTy = ArgTy;
2205 
2206     if (auto *VecTy = EltTy->getAs<VectorType>())
2207       EltTy = VecTy->getElementType();
2208     if (!EltTy->isFloatingType()) {
2209       Diag(TheCall->getArg(0)->getBeginLoc(),
2210            diag::err_builtin_invalid_arg_type)
2211           << 1 << /* float ty*/ 5 << ArgTy;
2212 
2213       return ExprError();
2214     }
2215     break;
2216   }
2217 
2218   case Builtin::BI__builtin_elementwise_min:
2219   case Builtin::BI__builtin_elementwise_max:
2220     if (SemaBuiltinElementwiseMath(TheCall))
2221       return ExprError();
2222     break;
2223   case Builtin::BI__builtin_reduce_max:
2224   case Builtin::BI__builtin_reduce_min: {
2225     if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2226       return ExprError();
2227 
2228     const Expr *Arg = TheCall->getArg(0);
2229     const auto *TyA = Arg->getType()->getAs<VectorType>();
2230     if (!TyA) {
2231       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2232           << 1 << /* vector ty*/ 4 << Arg->getType();
2233       return ExprError();
2234     }
2235 
2236     TheCall->setType(TyA->getElementType());
2237     break;
2238   }
2239 
2240   // These builtins support vectors of integers only.
2241   case Builtin::BI__builtin_reduce_xor:
2242   case Builtin::BI__builtin_reduce_or:
2243   case Builtin::BI__builtin_reduce_and: {
2244     if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2245       return ExprError();
2246 
2247     const Expr *Arg = TheCall->getArg(0);
2248     const auto *TyA = Arg->getType()->getAs<VectorType>();
2249     if (!TyA || !TyA->getElementType()->isIntegerType()) {
2250       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2251           << 1  << /* vector of integers */ 6 << Arg->getType();
2252       return ExprError();
2253     }
2254     TheCall->setType(TyA->getElementType());
2255     break;
2256   }
2257 
2258   case Builtin::BI__builtin_matrix_transpose:
2259     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
2260 
2261   case Builtin::BI__builtin_matrix_column_major_load:
2262     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
2263 
2264   case Builtin::BI__builtin_matrix_column_major_store:
2265     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
2266 
2267   case Builtin::BI__builtin_get_device_side_mangled_name: {
2268     auto Check = [](CallExpr *TheCall) {
2269       if (TheCall->getNumArgs() != 1)
2270         return false;
2271       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
2272       if (!DRE)
2273         return false;
2274       auto *D = DRE->getDecl();
2275       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
2276         return false;
2277       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
2278              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2279     };
2280     if (!Check(TheCall)) {
2281       Diag(TheCall->getBeginLoc(),
2282            diag::err_hip_invalid_args_builtin_mangled_name);
2283       return ExprError();
2284     }
2285   }
2286   }
2287 
2288   // Since the target specific builtins for each arch overlap, only check those
2289   // of the arch we are compiling for.
2290   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2291     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2292       assert(Context.getAuxTargetInfo() &&
2293              "Aux Target Builtin, but not an aux target?");
2294 
2295       if (CheckTSBuiltinFunctionCall(
2296               *Context.getAuxTargetInfo(),
2297               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2298         return ExprError();
2299     } else {
2300       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2301                                      TheCall))
2302         return ExprError();
2303     }
2304   }
2305 
2306   return TheCallResult;
2307 }
2308 
2309 // Get the valid immediate range for the specified NEON type code.
2310 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2311   NeonTypeFlags Type(t);
2312   int IsQuad = ForceQuad ? true : Type.isQuad();
2313   switch (Type.getEltType()) {
2314   case NeonTypeFlags::Int8:
2315   case NeonTypeFlags::Poly8:
2316     return shift ? 7 : (8 << IsQuad) - 1;
2317   case NeonTypeFlags::Int16:
2318   case NeonTypeFlags::Poly16:
2319     return shift ? 15 : (4 << IsQuad) - 1;
2320   case NeonTypeFlags::Int32:
2321     return shift ? 31 : (2 << IsQuad) - 1;
2322   case NeonTypeFlags::Int64:
2323   case NeonTypeFlags::Poly64:
2324     return shift ? 63 : (1 << IsQuad) - 1;
2325   case NeonTypeFlags::Poly128:
2326     return shift ? 127 : (1 << IsQuad) - 1;
2327   case NeonTypeFlags::Float16:
2328     assert(!shift && "cannot shift float types!");
2329     return (4 << IsQuad) - 1;
2330   case NeonTypeFlags::Float32:
2331     assert(!shift && "cannot shift float types!");
2332     return (2 << IsQuad) - 1;
2333   case NeonTypeFlags::Float64:
2334     assert(!shift && "cannot shift float types!");
2335     return (1 << IsQuad) - 1;
2336   case NeonTypeFlags::BFloat16:
2337     assert(!shift && "cannot shift float types!");
2338     return (4 << IsQuad) - 1;
2339   }
2340   llvm_unreachable("Invalid NeonTypeFlag!");
2341 }
2342 
2343 /// getNeonEltType - Return the QualType corresponding to the elements of
2344 /// the vector type specified by the NeonTypeFlags.  This is used to check
2345 /// the pointer arguments for Neon load/store intrinsics.
2346 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2347                                bool IsPolyUnsigned, bool IsInt64Long) {
2348   switch (Flags.getEltType()) {
2349   case NeonTypeFlags::Int8:
2350     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2351   case NeonTypeFlags::Int16:
2352     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2353   case NeonTypeFlags::Int32:
2354     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2355   case NeonTypeFlags::Int64:
2356     if (IsInt64Long)
2357       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2358     else
2359       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2360                                 : Context.LongLongTy;
2361   case NeonTypeFlags::Poly8:
2362     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2363   case NeonTypeFlags::Poly16:
2364     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2365   case NeonTypeFlags::Poly64:
2366     if (IsInt64Long)
2367       return Context.UnsignedLongTy;
2368     else
2369       return Context.UnsignedLongLongTy;
2370   case NeonTypeFlags::Poly128:
2371     break;
2372   case NeonTypeFlags::Float16:
2373     return Context.HalfTy;
2374   case NeonTypeFlags::Float32:
2375     return Context.FloatTy;
2376   case NeonTypeFlags::Float64:
2377     return Context.DoubleTy;
2378   case NeonTypeFlags::BFloat16:
2379     return Context.BFloat16Ty;
2380   }
2381   llvm_unreachable("Invalid NeonTypeFlag!");
2382 }
2383 
2384 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2385   // Range check SVE intrinsics that take immediate values.
2386   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2387 
2388   switch (BuiltinID) {
2389   default:
2390     return false;
2391 #define GET_SVE_IMMEDIATE_CHECK
2392 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2393 #undef GET_SVE_IMMEDIATE_CHECK
2394   }
2395 
2396   // Perform all the immediate checks for this builtin call.
2397   bool HasError = false;
2398   for (auto &I : ImmChecks) {
2399     int ArgNum, CheckTy, ElementSizeInBits;
2400     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2401 
2402     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2403 
2404     // Function that checks whether the operand (ArgNum) is an immediate
2405     // that is one of the predefined values.
2406     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2407                                    int ErrDiag) -> bool {
2408       // We can't check the value of a dependent argument.
2409       Expr *Arg = TheCall->getArg(ArgNum);
2410       if (Arg->isTypeDependent() || Arg->isValueDependent())
2411         return false;
2412 
2413       // Check constant-ness first.
2414       llvm::APSInt Imm;
2415       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2416         return true;
2417 
2418       if (!CheckImm(Imm.getSExtValue()))
2419         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2420       return false;
2421     };
2422 
2423     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2424     case SVETypeFlags::ImmCheck0_31:
2425       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2426         HasError = true;
2427       break;
2428     case SVETypeFlags::ImmCheck0_13:
2429       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2430         HasError = true;
2431       break;
2432     case SVETypeFlags::ImmCheck1_16:
2433       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2434         HasError = true;
2435       break;
2436     case SVETypeFlags::ImmCheck0_7:
2437       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2438         HasError = true;
2439       break;
2440     case SVETypeFlags::ImmCheckExtract:
2441       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2442                                       (2048 / ElementSizeInBits) - 1))
2443         HasError = true;
2444       break;
2445     case SVETypeFlags::ImmCheckShiftRight:
2446       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2447         HasError = true;
2448       break;
2449     case SVETypeFlags::ImmCheckShiftRightNarrow:
2450       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2451                                       ElementSizeInBits / 2))
2452         HasError = true;
2453       break;
2454     case SVETypeFlags::ImmCheckShiftLeft:
2455       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2456                                       ElementSizeInBits - 1))
2457         HasError = true;
2458       break;
2459     case SVETypeFlags::ImmCheckLaneIndex:
2460       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2461                                       (128 / (1 * ElementSizeInBits)) - 1))
2462         HasError = true;
2463       break;
2464     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2465       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2466                                       (128 / (2 * ElementSizeInBits)) - 1))
2467         HasError = true;
2468       break;
2469     case SVETypeFlags::ImmCheckLaneIndexDot:
2470       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2471                                       (128 / (4 * ElementSizeInBits)) - 1))
2472         HasError = true;
2473       break;
2474     case SVETypeFlags::ImmCheckComplexRot90_270:
2475       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2476                               diag::err_rotation_argument_to_cadd))
2477         HasError = true;
2478       break;
2479     case SVETypeFlags::ImmCheckComplexRotAll90:
2480       if (CheckImmediateInSet(
2481               [](int64_t V) {
2482                 return V == 0 || V == 90 || V == 180 || V == 270;
2483               },
2484               diag::err_rotation_argument_to_cmla))
2485         HasError = true;
2486       break;
2487     case SVETypeFlags::ImmCheck0_1:
2488       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2489         HasError = true;
2490       break;
2491     case SVETypeFlags::ImmCheck0_2:
2492       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2493         HasError = true;
2494       break;
2495     case SVETypeFlags::ImmCheck0_3:
2496       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2497         HasError = true;
2498       break;
2499     }
2500   }
2501 
2502   return HasError;
2503 }
2504 
2505 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2506                                         unsigned BuiltinID, CallExpr *TheCall) {
2507   llvm::APSInt Result;
2508   uint64_t mask = 0;
2509   unsigned TV = 0;
2510   int PtrArgNum = -1;
2511   bool HasConstPtr = false;
2512   switch (BuiltinID) {
2513 #define GET_NEON_OVERLOAD_CHECK
2514 #include "clang/Basic/arm_neon.inc"
2515 #include "clang/Basic/arm_fp16.inc"
2516 #undef GET_NEON_OVERLOAD_CHECK
2517   }
2518 
2519   // For NEON intrinsics which are overloaded on vector element type, validate
2520   // the immediate which specifies which variant to emit.
2521   unsigned ImmArg = TheCall->getNumArgs()-1;
2522   if (mask) {
2523     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2524       return true;
2525 
2526     TV = Result.getLimitedValue(64);
2527     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2528       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2529              << TheCall->getArg(ImmArg)->getSourceRange();
2530   }
2531 
2532   if (PtrArgNum >= 0) {
2533     // Check that pointer arguments have the specified type.
2534     Expr *Arg = TheCall->getArg(PtrArgNum);
2535     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2536       Arg = ICE->getSubExpr();
2537     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2538     QualType RHSTy = RHS.get()->getType();
2539 
2540     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2541     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2542                           Arch == llvm::Triple::aarch64_32 ||
2543                           Arch == llvm::Triple::aarch64_be;
2544     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2545     QualType EltTy =
2546         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2547     if (HasConstPtr)
2548       EltTy = EltTy.withConst();
2549     QualType LHSTy = Context.getPointerType(EltTy);
2550     AssignConvertType ConvTy;
2551     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2552     if (RHS.isInvalid())
2553       return true;
2554     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2555                                  RHS.get(), AA_Assigning))
2556       return true;
2557   }
2558 
2559   // For NEON intrinsics which take an immediate value as part of the
2560   // instruction, range check them here.
2561   unsigned i = 0, l = 0, u = 0;
2562   switch (BuiltinID) {
2563   default:
2564     return false;
2565   #define GET_NEON_IMMEDIATE_CHECK
2566   #include "clang/Basic/arm_neon.inc"
2567   #include "clang/Basic/arm_fp16.inc"
2568   #undef GET_NEON_IMMEDIATE_CHECK
2569   }
2570 
2571   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2572 }
2573 
2574 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2575   switch (BuiltinID) {
2576   default:
2577     return false;
2578   #include "clang/Basic/arm_mve_builtin_sema.inc"
2579   }
2580 }
2581 
2582 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2583                                        CallExpr *TheCall) {
2584   bool Err = false;
2585   switch (BuiltinID) {
2586   default:
2587     return false;
2588 #include "clang/Basic/arm_cde_builtin_sema.inc"
2589   }
2590 
2591   if (Err)
2592     return true;
2593 
2594   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2595 }
2596 
2597 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2598                                         const Expr *CoprocArg, bool WantCDE) {
2599   if (isConstantEvaluated())
2600     return false;
2601 
2602   // We can't check the value of a dependent argument.
2603   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2604     return false;
2605 
2606   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2607   int64_t CoprocNo = CoprocNoAP.getExtValue();
2608   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2609 
2610   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2611   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2612 
2613   if (IsCDECoproc != WantCDE)
2614     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2615            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2616 
2617   return false;
2618 }
2619 
2620 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2621                                         unsigned MaxWidth) {
2622   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2623           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2624           BuiltinID == ARM::BI__builtin_arm_strex ||
2625           BuiltinID == ARM::BI__builtin_arm_stlex ||
2626           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2627           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2628           BuiltinID == AArch64::BI__builtin_arm_strex ||
2629           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2630          "unexpected ARM builtin");
2631   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2632                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2633                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2634                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2635 
2636   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2637 
2638   // Ensure that we have the proper number of arguments.
2639   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2640     return true;
2641 
2642   // Inspect the pointer argument of the atomic builtin.  This should always be
2643   // a pointer type, whose element is an integral scalar or pointer type.
2644   // Because it is a pointer type, we don't have to worry about any implicit
2645   // casts here.
2646   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2647   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2648   if (PointerArgRes.isInvalid())
2649     return true;
2650   PointerArg = PointerArgRes.get();
2651 
2652   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2653   if (!pointerType) {
2654     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2655         << PointerArg->getType() << PointerArg->getSourceRange();
2656     return true;
2657   }
2658 
2659   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2660   // task is to insert the appropriate casts into the AST. First work out just
2661   // what the appropriate type is.
2662   QualType ValType = pointerType->getPointeeType();
2663   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2664   if (IsLdrex)
2665     AddrType.addConst();
2666 
2667   // Issue a warning if the cast is dodgy.
2668   CastKind CastNeeded = CK_NoOp;
2669   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2670     CastNeeded = CK_BitCast;
2671     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2672         << PointerArg->getType() << Context.getPointerType(AddrType)
2673         << AA_Passing << PointerArg->getSourceRange();
2674   }
2675 
2676   // Finally, do the cast and replace the argument with the corrected version.
2677   AddrType = Context.getPointerType(AddrType);
2678   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2679   if (PointerArgRes.isInvalid())
2680     return true;
2681   PointerArg = PointerArgRes.get();
2682 
2683   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2684 
2685   // In general, we allow ints, floats and pointers to be loaded and stored.
2686   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2687       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2688     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2689         << PointerArg->getType() << PointerArg->getSourceRange();
2690     return true;
2691   }
2692 
2693   // But ARM doesn't have instructions to deal with 128-bit versions.
2694   if (Context.getTypeSize(ValType) > MaxWidth) {
2695     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2696     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2697         << PointerArg->getType() << PointerArg->getSourceRange();
2698     return true;
2699   }
2700 
2701   switch (ValType.getObjCLifetime()) {
2702   case Qualifiers::OCL_None:
2703   case Qualifiers::OCL_ExplicitNone:
2704     // okay
2705     break;
2706 
2707   case Qualifiers::OCL_Weak:
2708   case Qualifiers::OCL_Strong:
2709   case Qualifiers::OCL_Autoreleasing:
2710     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2711         << ValType << PointerArg->getSourceRange();
2712     return true;
2713   }
2714 
2715   if (IsLdrex) {
2716     TheCall->setType(ValType);
2717     return false;
2718   }
2719 
2720   // Initialize the argument to be stored.
2721   ExprResult ValArg = TheCall->getArg(0);
2722   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2723       Context, ValType, /*consume*/ false);
2724   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2725   if (ValArg.isInvalid())
2726     return true;
2727   TheCall->setArg(0, ValArg.get());
2728 
2729   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2730   // but the custom checker bypasses all default analysis.
2731   TheCall->setType(Context.IntTy);
2732   return false;
2733 }
2734 
2735 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2736                                        CallExpr *TheCall) {
2737   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2738       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2739       BuiltinID == ARM::BI__builtin_arm_strex ||
2740       BuiltinID == ARM::BI__builtin_arm_stlex) {
2741     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2742   }
2743 
2744   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2745     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2746       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2747   }
2748 
2749   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2750       BuiltinID == ARM::BI__builtin_arm_wsr64)
2751     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2752 
2753   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2754       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2755       BuiltinID == ARM::BI__builtin_arm_wsr ||
2756       BuiltinID == ARM::BI__builtin_arm_wsrp)
2757     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2758 
2759   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2760     return true;
2761   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2762     return true;
2763   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2764     return true;
2765 
2766   // For intrinsics which take an immediate value as part of the instruction,
2767   // range check them here.
2768   // FIXME: VFP Intrinsics should error if VFP not present.
2769   switch (BuiltinID) {
2770   default: return false;
2771   case ARM::BI__builtin_arm_ssat:
2772     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2773   case ARM::BI__builtin_arm_usat:
2774     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2775   case ARM::BI__builtin_arm_ssat16:
2776     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2777   case ARM::BI__builtin_arm_usat16:
2778     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2779   case ARM::BI__builtin_arm_vcvtr_f:
2780   case ARM::BI__builtin_arm_vcvtr_d:
2781     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2782   case ARM::BI__builtin_arm_dmb:
2783   case ARM::BI__builtin_arm_dsb:
2784   case ARM::BI__builtin_arm_isb:
2785   case ARM::BI__builtin_arm_dbg:
2786     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2787   case ARM::BI__builtin_arm_cdp:
2788   case ARM::BI__builtin_arm_cdp2:
2789   case ARM::BI__builtin_arm_mcr:
2790   case ARM::BI__builtin_arm_mcr2:
2791   case ARM::BI__builtin_arm_mrc:
2792   case ARM::BI__builtin_arm_mrc2:
2793   case ARM::BI__builtin_arm_mcrr:
2794   case ARM::BI__builtin_arm_mcrr2:
2795   case ARM::BI__builtin_arm_mrrc:
2796   case ARM::BI__builtin_arm_mrrc2:
2797   case ARM::BI__builtin_arm_ldc:
2798   case ARM::BI__builtin_arm_ldcl:
2799   case ARM::BI__builtin_arm_ldc2:
2800   case ARM::BI__builtin_arm_ldc2l:
2801   case ARM::BI__builtin_arm_stc:
2802   case ARM::BI__builtin_arm_stcl:
2803   case ARM::BI__builtin_arm_stc2:
2804   case ARM::BI__builtin_arm_stc2l:
2805     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2806            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2807                                         /*WantCDE*/ false);
2808   }
2809 }
2810 
2811 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2812                                            unsigned BuiltinID,
2813                                            CallExpr *TheCall) {
2814   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2815       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2816       BuiltinID == AArch64::BI__builtin_arm_strex ||
2817       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2818     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2819   }
2820 
2821   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2822     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2823       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2824       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2825       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2826   }
2827 
2828   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2829       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2830     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2831 
2832   // Memory Tagging Extensions (MTE) Intrinsics
2833   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2834       BuiltinID == AArch64::BI__builtin_arm_addg ||
2835       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2836       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2837       BuiltinID == AArch64::BI__builtin_arm_stg ||
2838       BuiltinID == AArch64::BI__builtin_arm_subp) {
2839     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2840   }
2841 
2842   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2843       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2844       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2845       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2846     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2847 
2848   // Only check the valid encoding range. Any constant in this range would be
2849   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2850   // an exception for incorrect registers. This matches MSVC behavior.
2851   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2852       BuiltinID == AArch64::BI_WriteStatusReg)
2853     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2854 
2855   if (BuiltinID == AArch64::BI__getReg)
2856     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2857 
2858   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2859     return true;
2860 
2861   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2862     return true;
2863 
2864   // For intrinsics which take an immediate value as part of the instruction,
2865   // range check them here.
2866   unsigned i = 0, l = 0, u = 0;
2867   switch (BuiltinID) {
2868   default: return false;
2869   case AArch64::BI__builtin_arm_dmb:
2870   case AArch64::BI__builtin_arm_dsb:
2871   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2872   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2873   }
2874 
2875   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2876 }
2877 
2878 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2879   if (Arg->getType()->getAsPlaceholderType())
2880     return false;
2881 
2882   // The first argument needs to be a record field access.
2883   // If it is an array element access, we delay decision
2884   // to BPF backend to check whether the access is a
2885   // field access or not.
2886   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2887           isa<MemberExpr>(Arg->IgnoreParens()) ||
2888           isa<ArraySubscriptExpr>(Arg->IgnoreParens()));
2889 }
2890 
2891 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2892                             QualType VectorTy, QualType EltTy) {
2893   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2894   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2895     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2896         << Call->getSourceRange() << VectorEltTy << EltTy;
2897     return false;
2898   }
2899   return true;
2900 }
2901 
2902 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2903   QualType ArgType = Arg->getType();
2904   if (ArgType->getAsPlaceholderType())
2905     return false;
2906 
2907   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2908   // format:
2909   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2910   //   2. <type> var;
2911   //      __builtin_preserve_type_info(var, flag);
2912   if (!isa<DeclRefExpr>(Arg->IgnoreParens()) &&
2913       !isa<UnaryOperator>(Arg->IgnoreParens()))
2914     return false;
2915 
2916   // Typedef type.
2917   if (ArgType->getAs<TypedefType>())
2918     return true;
2919 
2920   // Record type or Enum type.
2921   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2922   if (const auto *RT = Ty->getAs<RecordType>()) {
2923     if (!RT->getDecl()->getDeclName().isEmpty())
2924       return true;
2925   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2926     if (!ET->getDecl()->getDeclName().isEmpty())
2927       return true;
2928   }
2929 
2930   return false;
2931 }
2932 
2933 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2934   QualType ArgType = Arg->getType();
2935   if (ArgType->getAsPlaceholderType())
2936     return false;
2937 
2938   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2939   // format:
2940   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2941   //                                 flag);
2942   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2943   if (!UO)
2944     return false;
2945 
2946   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2947   if (!CE)
2948     return false;
2949   if (CE->getCastKind() != CK_IntegralToPointer &&
2950       CE->getCastKind() != CK_NullToPointer)
2951     return false;
2952 
2953   // The integer must be from an EnumConstantDecl.
2954   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2955   if (!DR)
2956     return false;
2957 
2958   const EnumConstantDecl *Enumerator =
2959       dyn_cast<EnumConstantDecl>(DR->getDecl());
2960   if (!Enumerator)
2961     return false;
2962 
2963   // The type must be EnumType.
2964   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2965   const auto *ET = Ty->getAs<EnumType>();
2966   if (!ET)
2967     return false;
2968 
2969   // The enum value must be supported.
2970   return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
2971 }
2972 
2973 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2974                                        CallExpr *TheCall) {
2975   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2976           BuiltinID == BPF::BI__builtin_btf_type_id ||
2977           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2978           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2979          "unexpected BPF builtin");
2980 
2981   if (checkArgCount(*this, TheCall, 2))
2982     return true;
2983 
2984   // The second argument needs to be a constant int
2985   Expr *Arg = TheCall->getArg(1);
2986   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2987   diag::kind kind;
2988   if (!Value) {
2989     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2990       kind = diag::err_preserve_field_info_not_const;
2991     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2992       kind = diag::err_btf_type_id_not_const;
2993     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2994       kind = diag::err_preserve_type_info_not_const;
2995     else
2996       kind = diag::err_preserve_enum_value_not_const;
2997     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2998     return true;
2999   }
3000 
3001   // The first argument
3002   Arg = TheCall->getArg(0);
3003   bool InvalidArg = false;
3004   bool ReturnUnsignedInt = true;
3005   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
3006     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
3007       InvalidArg = true;
3008       kind = diag::err_preserve_field_info_not_field;
3009     }
3010   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
3011     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
3012       InvalidArg = true;
3013       kind = diag::err_preserve_type_info_invalid;
3014     }
3015   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
3016     if (!isValidBPFPreserveEnumValueArg(Arg)) {
3017       InvalidArg = true;
3018       kind = diag::err_preserve_enum_value_invalid;
3019     }
3020     ReturnUnsignedInt = false;
3021   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
3022     ReturnUnsignedInt = false;
3023   }
3024 
3025   if (InvalidArg) {
3026     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
3027     return true;
3028   }
3029 
3030   if (ReturnUnsignedInt)
3031     TheCall->setType(Context.UnsignedIntTy);
3032   else
3033     TheCall->setType(Context.UnsignedLongTy);
3034   return false;
3035 }
3036 
3037 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3038   struct ArgInfo {
3039     uint8_t OpNum;
3040     bool IsSigned;
3041     uint8_t BitWidth;
3042     uint8_t Align;
3043   };
3044   struct BuiltinInfo {
3045     unsigned BuiltinID;
3046     ArgInfo Infos[2];
3047   };
3048 
3049   static BuiltinInfo Infos[] = {
3050     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
3051     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
3052     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
3053     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
3054     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
3055     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
3056     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
3057     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
3058     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
3059     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
3060     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
3061 
3062     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
3063     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
3064     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
3065     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
3066     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
3067     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
3068     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
3069     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
3070     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
3071     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
3072     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
3073 
3074     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
3075     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
3076     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
3077     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
3078     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
3079     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
3080     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
3081     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
3082     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
3083     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
3084     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
3085     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
3086     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
3087     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
3088     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
3089     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
3090     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
3091     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
3092     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
3093     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
3094     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
3095     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
3096     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
3097     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
3098     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
3099     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
3100     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
3101     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
3102     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
3103     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
3104     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
3105     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
3106     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
3107     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
3108     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
3109     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
3110     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
3111     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
3112     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
3113     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
3114     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
3115     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
3116     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
3117     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
3118     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
3119     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
3120     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
3121     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
3122     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
3123     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
3124     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
3125     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
3126                                                       {{ 1, false, 6,  0 }} },
3127     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
3128     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
3129     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
3130     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
3131     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
3132     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
3133     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
3134                                                       {{ 1, false, 5,  0 }} },
3135     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
3136     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
3137     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
3138     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
3139     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
3140     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
3141                                                        { 2, false, 5,  0 }} },
3142     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
3143                                                        { 2, false, 6,  0 }} },
3144     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
3145                                                        { 3, false, 5,  0 }} },
3146     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
3147                                                        { 3, false, 6,  0 }} },
3148     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
3149     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
3150     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
3151     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
3152     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
3153     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
3154     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
3155     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
3156     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
3157     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
3158     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
3159     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
3160     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
3161     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
3162     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
3163     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
3164                                                       {{ 2, false, 4,  0 },
3165                                                        { 3, false, 5,  0 }} },
3166     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
3167                                                       {{ 2, false, 4,  0 },
3168                                                        { 3, false, 5,  0 }} },
3169     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
3170                                                       {{ 2, false, 4,  0 },
3171                                                        { 3, false, 5,  0 }} },
3172     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
3173                                                       {{ 2, false, 4,  0 },
3174                                                        { 3, false, 5,  0 }} },
3175     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
3176     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
3177     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
3178     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
3179     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
3180     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
3181     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
3182     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
3183     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
3184     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
3185     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
3186                                                        { 2, false, 5,  0 }} },
3187     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
3188                                                        { 2, false, 6,  0 }} },
3189     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
3190     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
3191     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
3192     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
3193     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
3194     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
3195     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
3196     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
3197     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
3198                                                       {{ 1, false, 4,  0 }} },
3199     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
3200     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
3201                                                       {{ 1, false, 4,  0 }} },
3202     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
3203     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
3204     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
3205     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
3206     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
3207     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
3208     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
3209     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
3210     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
3211     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
3212     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
3213     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
3214     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
3215     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
3216     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
3217     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
3218     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
3219     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
3220     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
3221     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
3222                                                       {{ 3, false, 1,  0 }} },
3223     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
3224     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
3225     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
3226     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
3227                                                       {{ 3, false, 1,  0 }} },
3228     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
3229     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
3230     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
3231     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
3232                                                       {{ 3, false, 1,  0 }} },
3233   };
3234 
3235   // Use a dynamically initialized static to sort the table exactly once on
3236   // first run.
3237   static const bool SortOnce =
3238       (llvm::sort(Infos,
3239                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
3240                    return LHS.BuiltinID < RHS.BuiltinID;
3241                  }),
3242        true);
3243   (void)SortOnce;
3244 
3245   const BuiltinInfo *F = llvm::partition_point(
3246       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
3247   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
3248     return false;
3249 
3250   bool Error = false;
3251 
3252   for (const ArgInfo &A : F->Infos) {
3253     // Ignore empty ArgInfo elements.
3254     if (A.BitWidth == 0)
3255       continue;
3256 
3257     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
3258     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
3259     if (!A.Align) {
3260       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3261     } else {
3262       unsigned M = 1 << A.Align;
3263       Min *= M;
3264       Max *= M;
3265       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3266       Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
3267     }
3268   }
3269   return Error;
3270 }
3271 
3272 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
3273                                            CallExpr *TheCall) {
3274   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3275 }
3276 
3277 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
3278                                         unsigned BuiltinID, CallExpr *TheCall) {
3279   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
3280          CheckMipsBuiltinArgument(BuiltinID, TheCall);
3281 }
3282 
3283 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
3284                                CallExpr *TheCall) {
3285 
3286   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3287       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3288     if (!TI.hasFeature("dsp"))
3289       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3290   }
3291 
3292   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3293       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3294     if (!TI.hasFeature("dspr2"))
3295       return Diag(TheCall->getBeginLoc(),
3296                   diag::err_mips_builtin_requires_dspr2);
3297   }
3298 
3299   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3300       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3301     if (!TI.hasFeature("msa"))
3302       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3303   }
3304 
3305   return false;
3306 }
3307 
3308 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3309 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3310 // ordering for DSP is unspecified. MSA is ordered by the data format used
3311 // by the underlying instruction i.e., df/m, df/n and then by size.
3312 //
3313 // FIXME: The size tests here should instead be tablegen'd along with the
3314 //        definitions from include/clang/Basic/BuiltinsMips.def.
3315 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3316 //        be too.
3317 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3318   unsigned i = 0, l = 0, u = 0, m = 0;
3319   switch (BuiltinID) {
3320   default: return false;
3321   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3322   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3323   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3324   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3325   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3326   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3327   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3328   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3329   // df/m field.
3330   // These intrinsics take an unsigned 3 bit immediate.
3331   case Mips::BI__builtin_msa_bclri_b:
3332   case Mips::BI__builtin_msa_bnegi_b:
3333   case Mips::BI__builtin_msa_bseti_b:
3334   case Mips::BI__builtin_msa_sat_s_b:
3335   case Mips::BI__builtin_msa_sat_u_b:
3336   case Mips::BI__builtin_msa_slli_b:
3337   case Mips::BI__builtin_msa_srai_b:
3338   case Mips::BI__builtin_msa_srari_b:
3339   case Mips::BI__builtin_msa_srli_b:
3340   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3341   case Mips::BI__builtin_msa_binsli_b:
3342   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3343   // These intrinsics take an unsigned 4 bit immediate.
3344   case Mips::BI__builtin_msa_bclri_h:
3345   case Mips::BI__builtin_msa_bnegi_h:
3346   case Mips::BI__builtin_msa_bseti_h:
3347   case Mips::BI__builtin_msa_sat_s_h:
3348   case Mips::BI__builtin_msa_sat_u_h:
3349   case Mips::BI__builtin_msa_slli_h:
3350   case Mips::BI__builtin_msa_srai_h:
3351   case Mips::BI__builtin_msa_srari_h:
3352   case Mips::BI__builtin_msa_srli_h:
3353   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3354   case Mips::BI__builtin_msa_binsli_h:
3355   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3356   // These intrinsics take an unsigned 5 bit immediate.
3357   // The first block of intrinsics actually have an unsigned 5 bit field,
3358   // not a df/n field.
3359   case Mips::BI__builtin_msa_cfcmsa:
3360   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3361   case Mips::BI__builtin_msa_clei_u_b:
3362   case Mips::BI__builtin_msa_clei_u_h:
3363   case Mips::BI__builtin_msa_clei_u_w:
3364   case Mips::BI__builtin_msa_clei_u_d:
3365   case Mips::BI__builtin_msa_clti_u_b:
3366   case Mips::BI__builtin_msa_clti_u_h:
3367   case Mips::BI__builtin_msa_clti_u_w:
3368   case Mips::BI__builtin_msa_clti_u_d:
3369   case Mips::BI__builtin_msa_maxi_u_b:
3370   case Mips::BI__builtin_msa_maxi_u_h:
3371   case Mips::BI__builtin_msa_maxi_u_w:
3372   case Mips::BI__builtin_msa_maxi_u_d:
3373   case Mips::BI__builtin_msa_mini_u_b:
3374   case Mips::BI__builtin_msa_mini_u_h:
3375   case Mips::BI__builtin_msa_mini_u_w:
3376   case Mips::BI__builtin_msa_mini_u_d:
3377   case Mips::BI__builtin_msa_addvi_b:
3378   case Mips::BI__builtin_msa_addvi_h:
3379   case Mips::BI__builtin_msa_addvi_w:
3380   case Mips::BI__builtin_msa_addvi_d:
3381   case Mips::BI__builtin_msa_bclri_w:
3382   case Mips::BI__builtin_msa_bnegi_w:
3383   case Mips::BI__builtin_msa_bseti_w:
3384   case Mips::BI__builtin_msa_sat_s_w:
3385   case Mips::BI__builtin_msa_sat_u_w:
3386   case Mips::BI__builtin_msa_slli_w:
3387   case Mips::BI__builtin_msa_srai_w:
3388   case Mips::BI__builtin_msa_srari_w:
3389   case Mips::BI__builtin_msa_srli_w:
3390   case Mips::BI__builtin_msa_srlri_w:
3391   case Mips::BI__builtin_msa_subvi_b:
3392   case Mips::BI__builtin_msa_subvi_h:
3393   case Mips::BI__builtin_msa_subvi_w:
3394   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3395   case Mips::BI__builtin_msa_binsli_w:
3396   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3397   // These intrinsics take an unsigned 6 bit immediate.
3398   case Mips::BI__builtin_msa_bclri_d:
3399   case Mips::BI__builtin_msa_bnegi_d:
3400   case Mips::BI__builtin_msa_bseti_d:
3401   case Mips::BI__builtin_msa_sat_s_d:
3402   case Mips::BI__builtin_msa_sat_u_d:
3403   case Mips::BI__builtin_msa_slli_d:
3404   case Mips::BI__builtin_msa_srai_d:
3405   case Mips::BI__builtin_msa_srari_d:
3406   case Mips::BI__builtin_msa_srli_d:
3407   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3408   case Mips::BI__builtin_msa_binsli_d:
3409   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3410   // These intrinsics take a signed 5 bit immediate.
3411   case Mips::BI__builtin_msa_ceqi_b:
3412   case Mips::BI__builtin_msa_ceqi_h:
3413   case Mips::BI__builtin_msa_ceqi_w:
3414   case Mips::BI__builtin_msa_ceqi_d:
3415   case Mips::BI__builtin_msa_clti_s_b:
3416   case Mips::BI__builtin_msa_clti_s_h:
3417   case Mips::BI__builtin_msa_clti_s_w:
3418   case Mips::BI__builtin_msa_clti_s_d:
3419   case Mips::BI__builtin_msa_clei_s_b:
3420   case Mips::BI__builtin_msa_clei_s_h:
3421   case Mips::BI__builtin_msa_clei_s_w:
3422   case Mips::BI__builtin_msa_clei_s_d:
3423   case Mips::BI__builtin_msa_maxi_s_b:
3424   case Mips::BI__builtin_msa_maxi_s_h:
3425   case Mips::BI__builtin_msa_maxi_s_w:
3426   case Mips::BI__builtin_msa_maxi_s_d:
3427   case Mips::BI__builtin_msa_mini_s_b:
3428   case Mips::BI__builtin_msa_mini_s_h:
3429   case Mips::BI__builtin_msa_mini_s_w:
3430   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3431   // These intrinsics take an unsigned 8 bit immediate.
3432   case Mips::BI__builtin_msa_andi_b:
3433   case Mips::BI__builtin_msa_nori_b:
3434   case Mips::BI__builtin_msa_ori_b:
3435   case Mips::BI__builtin_msa_shf_b:
3436   case Mips::BI__builtin_msa_shf_h:
3437   case Mips::BI__builtin_msa_shf_w:
3438   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3439   case Mips::BI__builtin_msa_bseli_b:
3440   case Mips::BI__builtin_msa_bmnzi_b:
3441   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3442   // df/n format
3443   // These intrinsics take an unsigned 4 bit immediate.
3444   case Mips::BI__builtin_msa_copy_s_b:
3445   case Mips::BI__builtin_msa_copy_u_b:
3446   case Mips::BI__builtin_msa_insve_b:
3447   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3448   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3449   // These intrinsics take an unsigned 3 bit immediate.
3450   case Mips::BI__builtin_msa_copy_s_h:
3451   case Mips::BI__builtin_msa_copy_u_h:
3452   case Mips::BI__builtin_msa_insve_h:
3453   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3454   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3455   // These intrinsics take an unsigned 2 bit immediate.
3456   case Mips::BI__builtin_msa_copy_s_w:
3457   case Mips::BI__builtin_msa_copy_u_w:
3458   case Mips::BI__builtin_msa_insve_w:
3459   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3460   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3461   // These intrinsics take an unsigned 1 bit immediate.
3462   case Mips::BI__builtin_msa_copy_s_d:
3463   case Mips::BI__builtin_msa_copy_u_d:
3464   case Mips::BI__builtin_msa_insve_d:
3465   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3466   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3467   // Memory offsets and immediate loads.
3468   // These intrinsics take a signed 10 bit immediate.
3469   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3470   case Mips::BI__builtin_msa_ldi_h:
3471   case Mips::BI__builtin_msa_ldi_w:
3472   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3473   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3474   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3475   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3476   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3477   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3478   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3479   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3480   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3481   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3482   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3483   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3484   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3485   }
3486 
3487   if (!m)
3488     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3489 
3490   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3491          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3492 }
3493 
3494 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3495 /// advancing the pointer over the consumed characters. The decoded type is
3496 /// returned. If the decoded type represents a constant integer with a
3497 /// constraint on its value then Mask is set to that value. The type descriptors
3498 /// used in Str are specific to PPC MMA builtins and are documented in the file
3499 /// defining the PPC builtins.
3500 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3501                                         unsigned &Mask) {
3502   bool RequireICE = false;
3503   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3504   switch (*Str++) {
3505   case 'V':
3506     return Context.getVectorType(Context.UnsignedCharTy, 16,
3507                                  VectorType::VectorKind::AltiVecVector);
3508   case 'i': {
3509     char *End;
3510     unsigned size = strtoul(Str, &End, 10);
3511     assert(End != Str && "Missing constant parameter constraint");
3512     Str = End;
3513     Mask = size;
3514     return Context.IntTy;
3515   }
3516   case 'W': {
3517     char *End;
3518     unsigned size = strtoul(Str, &End, 10);
3519     assert(End != Str && "Missing PowerPC MMA type size");
3520     Str = End;
3521     QualType Type;
3522     switch (size) {
3523   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3524     case size: Type = Context.Id##Ty; break;
3525   #include "clang/Basic/PPCTypes.def"
3526     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3527     }
3528     bool CheckVectorArgs = false;
3529     while (!CheckVectorArgs) {
3530       switch (*Str++) {
3531       case '*':
3532         Type = Context.getPointerType(Type);
3533         break;
3534       case 'C':
3535         Type = Type.withConst();
3536         break;
3537       default:
3538         CheckVectorArgs = true;
3539         --Str;
3540         break;
3541       }
3542     }
3543     return Type;
3544   }
3545   default:
3546     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3547   }
3548 }
3549 
3550 static bool isPPC_64Builtin(unsigned BuiltinID) {
3551   // These builtins only work on PPC 64bit targets.
3552   switch (BuiltinID) {
3553   case PPC::BI__builtin_divde:
3554   case PPC::BI__builtin_divdeu:
3555   case PPC::BI__builtin_bpermd:
3556   case PPC::BI__builtin_ppc_ldarx:
3557   case PPC::BI__builtin_ppc_stdcx:
3558   case PPC::BI__builtin_ppc_tdw:
3559   case PPC::BI__builtin_ppc_trapd:
3560   case PPC::BI__builtin_ppc_cmpeqb:
3561   case PPC::BI__builtin_ppc_setb:
3562   case PPC::BI__builtin_ppc_mulhd:
3563   case PPC::BI__builtin_ppc_mulhdu:
3564   case PPC::BI__builtin_ppc_maddhd:
3565   case PPC::BI__builtin_ppc_maddhdu:
3566   case PPC::BI__builtin_ppc_maddld:
3567   case PPC::BI__builtin_ppc_load8r:
3568   case PPC::BI__builtin_ppc_store8r:
3569   case PPC::BI__builtin_ppc_insert_exp:
3570   case PPC::BI__builtin_ppc_extract_sig:
3571   case PPC::BI__builtin_ppc_addex:
3572   case PPC::BI__builtin_darn:
3573   case PPC::BI__builtin_darn_raw:
3574   case PPC::BI__builtin_ppc_compare_and_swaplp:
3575   case PPC::BI__builtin_ppc_fetch_and_addlp:
3576   case PPC::BI__builtin_ppc_fetch_and_andlp:
3577   case PPC::BI__builtin_ppc_fetch_and_orlp:
3578   case PPC::BI__builtin_ppc_fetch_and_swaplp:
3579     return true;
3580   }
3581   return false;
3582 }
3583 
3584 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3585                              StringRef FeatureToCheck, unsigned DiagID,
3586                              StringRef DiagArg = "") {
3587   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3588     return false;
3589 
3590   if (DiagArg.empty())
3591     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3592   else
3593     S.Diag(TheCall->getBeginLoc(), DiagID)
3594         << DiagArg << TheCall->getSourceRange();
3595 
3596   return true;
3597 }
3598 
3599 /// Returns true if the argument consists of one contiguous run of 1s with any
3600 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3601 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3602 /// since all 1s are not contiguous.
3603 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3604   llvm::APSInt Result;
3605   // We can't check the value of a dependent argument.
3606   Expr *Arg = TheCall->getArg(ArgNum);
3607   if (Arg->isTypeDependent() || Arg->isValueDependent())
3608     return false;
3609 
3610   // Check constant-ness first.
3611   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3612     return true;
3613 
3614   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3615   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3616     return false;
3617 
3618   return Diag(TheCall->getBeginLoc(),
3619               diag::err_argument_not_contiguous_bit_field)
3620          << ArgNum << Arg->getSourceRange();
3621 }
3622 
3623 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3624                                        CallExpr *TheCall) {
3625   unsigned i = 0, l = 0, u = 0;
3626   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3627   llvm::APSInt Result;
3628 
3629   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3630     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3631            << TheCall->getSourceRange();
3632 
3633   switch (BuiltinID) {
3634   default: return false;
3635   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3636   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3637     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3638            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3639   case PPC::BI__builtin_altivec_dss:
3640     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3641   case PPC::BI__builtin_tbegin:
3642   case PPC::BI__builtin_tend:
3643     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 1) ||
3644            SemaFeatureCheck(*this, TheCall, "htm",
3645                             diag::err_ppc_builtin_requires_htm);
3646   case PPC::BI__builtin_tsr:
3647     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3648            SemaFeatureCheck(*this, TheCall, "htm",
3649                             diag::err_ppc_builtin_requires_htm);
3650   case PPC::BI__builtin_tabortwc:
3651   case PPC::BI__builtin_tabortdc:
3652     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3653            SemaFeatureCheck(*this, TheCall, "htm",
3654                             diag::err_ppc_builtin_requires_htm);
3655   case PPC::BI__builtin_tabortwci:
3656   case PPC::BI__builtin_tabortdci:
3657     return SemaFeatureCheck(*this, TheCall, "htm",
3658                             diag::err_ppc_builtin_requires_htm) ||
3659            (SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3660             SemaBuiltinConstantArgRange(TheCall, 2, 0, 31));
3661   case PPC::BI__builtin_tabort:
3662   case PPC::BI__builtin_tcheck:
3663   case PPC::BI__builtin_treclaim:
3664   case PPC::BI__builtin_trechkpt:
3665   case PPC::BI__builtin_tendall:
3666   case PPC::BI__builtin_tresume:
3667   case PPC::BI__builtin_tsuspend:
3668   case PPC::BI__builtin_get_texasr:
3669   case PPC::BI__builtin_get_texasru:
3670   case PPC::BI__builtin_get_tfhar:
3671   case PPC::BI__builtin_get_tfiar:
3672   case PPC::BI__builtin_set_texasr:
3673   case PPC::BI__builtin_set_texasru:
3674   case PPC::BI__builtin_set_tfhar:
3675   case PPC::BI__builtin_set_tfiar:
3676   case PPC::BI__builtin_ttest:
3677     return SemaFeatureCheck(*this, TheCall, "htm",
3678                             diag::err_ppc_builtin_requires_htm);
3679   // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05',
3680   // __builtin_(un)pack_longdouble are available only if long double uses IBM
3681   // extended double representation.
3682   case PPC::BI__builtin_unpack_longdouble:
3683     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1))
3684       return true;
3685     LLVM_FALLTHROUGH;
3686   case PPC::BI__builtin_pack_longdouble:
3687     if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble())
3688       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi)
3689              << "ibmlongdouble";
3690     return false;
3691   case PPC::BI__builtin_altivec_dst:
3692   case PPC::BI__builtin_altivec_dstt:
3693   case PPC::BI__builtin_altivec_dstst:
3694   case PPC::BI__builtin_altivec_dststt:
3695     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3696   case PPC::BI__builtin_vsx_xxpermdi:
3697   case PPC::BI__builtin_vsx_xxsldwi:
3698     return SemaBuiltinVSX(TheCall);
3699   case PPC::BI__builtin_divwe:
3700   case PPC::BI__builtin_divweu:
3701   case PPC::BI__builtin_divde:
3702   case PPC::BI__builtin_divdeu:
3703     return SemaFeatureCheck(*this, TheCall, "extdiv",
3704                             diag::err_ppc_builtin_only_on_arch, "7");
3705   case PPC::BI__builtin_bpermd:
3706     return SemaFeatureCheck(*this, TheCall, "bpermd",
3707                             diag::err_ppc_builtin_only_on_arch, "7");
3708   case PPC::BI__builtin_unpack_vector_int128:
3709     return SemaFeatureCheck(*this, TheCall, "vsx",
3710                             diag::err_ppc_builtin_only_on_arch, "7") ||
3711            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3712   case PPC::BI__builtin_pack_vector_int128:
3713     return SemaFeatureCheck(*this, TheCall, "vsx",
3714                             diag::err_ppc_builtin_only_on_arch, "7");
3715   case PPC::BI__builtin_altivec_vgnb:
3716      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3717   case PPC::BI__builtin_altivec_vec_replace_elt:
3718   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3719     QualType VecTy = TheCall->getArg(0)->getType();
3720     QualType EltTy = TheCall->getArg(1)->getType();
3721     unsigned Width = Context.getIntWidth(EltTy);
3722     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3723            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3724   }
3725   case PPC::BI__builtin_vsx_xxeval:
3726      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3727   case PPC::BI__builtin_altivec_vsldbi:
3728      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3729   case PPC::BI__builtin_altivec_vsrdbi:
3730      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3731   case PPC::BI__builtin_vsx_xxpermx:
3732      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3733   case PPC::BI__builtin_ppc_tw:
3734   case PPC::BI__builtin_ppc_tdw:
3735     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3736   case PPC::BI__builtin_ppc_cmpeqb:
3737   case PPC::BI__builtin_ppc_setb:
3738   case PPC::BI__builtin_ppc_maddhd:
3739   case PPC::BI__builtin_ppc_maddhdu:
3740   case PPC::BI__builtin_ppc_maddld:
3741     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3742                             diag::err_ppc_builtin_only_on_arch, "9");
3743   case PPC::BI__builtin_ppc_cmprb:
3744     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3745                             diag::err_ppc_builtin_only_on_arch, "9") ||
3746            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3747   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3748   // be a constant that represents a contiguous bit field.
3749   case PPC::BI__builtin_ppc_rlwnm:
3750     return SemaValueIsRunOfOnes(TheCall, 2);
3751   case PPC::BI__builtin_ppc_rlwimi:
3752   case PPC::BI__builtin_ppc_rldimi:
3753     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3754            SemaValueIsRunOfOnes(TheCall, 3);
3755   case PPC::BI__builtin_ppc_extract_exp:
3756   case PPC::BI__builtin_ppc_extract_sig:
3757   case PPC::BI__builtin_ppc_insert_exp:
3758     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3759                             diag::err_ppc_builtin_only_on_arch, "9");
3760   case PPC::BI__builtin_ppc_addex: {
3761     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3762                          diag::err_ppc_builtin_only_on_arch, "9") ||
3763         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
3764       return true;
3765     // Output warning for reserved values 1 to 3.
3766     int ArgValue =
3767         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
3768     if (ArgValue != 0)
3769       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
3770           << ArgValue;
3771     return false;
3772   }
3773   case PPC::BI__builtin_ppc_mtfsb0:
3774   case PPC::BI__builtin_ppc_mtfsb1:
3775     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3776   case PPC::BI__builtin_ppc_mtfsf:
3777     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3778   case PPC::BI__builtin_ppc_mtfsfi:
3779     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3780            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3781   case PPC::BI__builtin_ppc_alignx:
3782     return SemaBuiltinConstantArgPower2(TheCall, 0);
3783   case PPC::BI__builtin_ppc_rdlam:
3784     return SemaValueIsRunOfOnes(TheCall, 2);
3785   case PPC::BI__builtin_ppc_icbt:
3786   case PPC::BI__builtin_ppc_sthcx:
3787   case PPC::BI__builtin_ppc_stbcx:
3788   case PPC::BI__builtin_ppc_lharx:
3789   case PPC::BI__builtin_ppc_lbarx:
3790     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3791                             diag::err_ppc_builtin_only_on_arch, "8");
3792   case PPC::BI__builtin_vsx_ldrmb:
3793   case PPC::BI__builtin_vsx_strmb:
3794     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3795                             diag::err_ppc_builtin_only_on_arch, "8") ||
3796            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3797   case PPC::BI__builtin_altivec_vcntmbb:
3798   case PPC::BI__builtin_altivec_vcntmbh:
3799   case PPC::BI__builtin_altivec_vcntmbw:
3800   case PPC::BI__builtin_altivec_vcntmbd:
3801     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3802   case PPC::BI__builtin_darn:
3803   case PPC::BI__builtin_darn_raw:
3804   case PPC::BI__builtin_darn_32:
3805     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3806                             diag::err_ppc_builtin_only_on_arch, "9");
3807   case PPC::BI__builtin_vsx_xxgenpcvbm:
3808   case PPC::BI__builtin_vsx_xxgenpcvhm:
3809   case PPC::BI__builtin_vsx_xxgenpcvwm:
3810   case PPC::BI__builtin_vsx_xxgenpcvdm:
3811     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3812   case PPC::BI__builtin_ppc_compare_exp_uo:
3813   case PPC::BI__builtin_ppc_compare_exp_lt:
3814   case PPC::BI__builtin_ppc_compare_exp_gt:
3815   case PPC::BI__builtin_ppc_compare_exp_eq:
3816     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3817                             diag::err_ppc_builtin_only_on_arch, "9") ||
3818            SemaFeatureCheck(*this, TheCall, "vsx",
3819                             diag::err_ppc_builtin_requires_vsx);
3820   case PPC::BI__builtin_ppc_test_data_class: {
3821     // Check if the first argument of the __builtin_ppc_test_data_class call is
3822     // valid. The argument must be either a 'float' or a 'double'.
3823     QualType ArgType = TheCall->getArg(0)->getType();
3824     if (ArgType != QualType(Context.FloatTy) &&
3825         ArgType != QualType(Context.DoubleTy))
3826       return Diag(TheCall->getBeginLoc(),
3827                   diag::err_ppc_invalid_test_data_class_type);
3828     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3829                             diag::err_ppc_builtin_only_on_arch, "9") ||
3830            SemaFeatureCheck(*this, TheCall, "vsx",
3831                             diag::err_ppc_builtin_requires_vsx) ||
3832            SemaBuiltinConstantArgRange(TheCall, 1, 0, 127);
3833   }
3834   case PPC::BI__builtin_ppc_load8r:
3835   case PPC::BI__builtin_ppc_store8r:
3836     return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions",
3837                             diag::err_ppc_builtin_only_on_arch, "7");
3838 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc)                                 \
3839   case PPC::BI__builtin_##Name:                                                \
3840     return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types);
3841 #include "clang/Basic/BuiltinsPPC.def"
3842   }
3843   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3844 }
3845 
3846 // Check if the given type is a non-pointer PPC MMA type. This function is used
3847 // in Sema to prevent invalid uses of restricted PPC MMA types.
3848 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3849   if (Type->isPointerType() || Type->isArrayType())
3850     return false;
3851 
3852   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3853 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3854   if (false
3855 #include "clang/Basic/PPCTypes.def"
3856      ) {
3857     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3858     return true;
3859   }
3860   return false;
3861 }
3862 
3863 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3864                                           CallExpr *TheCall) {
3865   // position of memory order and scope arguments in the builtin
3866   unsigned OrderIndex, ScopeIndex;
3867   switch (BuiltinID) {
3868   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3869   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3870   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3871   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3872     OrderIndex = 2;
3873     ScopeIndex = 3;
3874     break;
3875   case AMDGPU::BI__builtin_amdgcn_fence:
3876     OrderIndex = 0;
3877     ScopeIndex = 1;
3878     break;
3879   default:
3880     return false;
3881   }
3882 
3883   ExprResult Arg = TheCall->getArg(OrderIndex);
3884   auto ArgExpr = Arg.get();
3885   Expr::EvalResult ArgResult;
3886 
3887   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3888     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3889            << ArgExpr->getType();
3890   auto Ord = ArgResult.Val.getInt().getZExtValue();
3891 
3892   // Check validity of memory ordering as per C11 / C++11's memody model.
3893   // Only fence needs check. Atomic dec/inc allow all memory orders.
3894   if (!llvm::isValidAtomicOrderingCABI(Ord))
3895     return Diag(ArgExpr->getBeginLoc(),
3896                 diag::warn_atomic_op_has_invalid_memory_order)
3897            << ArgExpr->getSourceRange();
3898   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3899   case llvm::AtomicOrderingCABI::relaxed:
3900   case llvm::AtomicOrderingCABI::consume:
3901     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3902       return Diag(ArgExpr->getBeginLoc(),
3903                   diag::warn_atomic_op_has_invalid_memory_order)
3904              << ArgExpr->getSourceRange();
3905     break;
3906   case llvm::AtomicOrderingCABI::acquire:
3907   case llvm::AtomicOrderingCABI::release:
3908   case llvm::AtomicOrderingCABI::acq_rel:
3909   case llvm::AtomicOrderingCABI::seq_cst:
3910     break;
3911   }
3912 
3913   Arg = TheCall->getArg(ScopeIndex);
3914   ArgExpr = Arg.get();
3915   Expr::EvalResult ArgResult1;
3916   // Check that sync scope is a constant literal
3917   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3918     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3919            << ArgExpr->getType();
3920 
3921   return false;
3922 }
3923 
3924 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3925   llvm::APSInt Result;
3926 
3927   // We can't check the value of a dependent argument.
3928   Expr *Arg = TheCall->getArg(ArgNum);
3929   if (Arg->isTypeDependent() || Arg->isValueDependent())
3930     return false;
3931 
3932   // Check constant-ness first.
3933   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3934     return true;
3935 
3936   int64_t Val = Result.getSExtValue();
3937   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3938     return false;
3939 
3940   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3941          << Arg->getSourceRange();
3942 }
3943 
3944 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3945                                          unsigned BuiltinID,
3946                                          CallExpr *TheCall) {
3947   // CodeGenFunction can also detect this, but this gives a better error
3948   // message.
3949   bool FeatureMissing = false;
3950   SmallVector<StringRef> ReqFeatures;
3951   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3952   Features.split(ReqFeatures, ',');
3953 
3954   // Check if each required feature is included
3955   for (StringRef F : ReqFeatures) {
3956     if (TI.hasFeature(F))
3957       continue;
3958 
3959     // If the feature is 64bit, alter the string so it will print better in
3960     // the diagnostic.
3961     if (F == "64bit")
3962       F = "RV64";
3963 
3964     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3965     F.consume_front("experimental-");
3966     std::string FeatureStr = F.str();
3967     FeatureStr[0] = std::toupper(FeatureStr[0]);
3968 
3969     // Error message
3970     FeatureMissing = true;
3971     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3972         << TheCall->getSourceRange() << StringRef(FeatureStr);
3973   }
3974 
3975   if (FeatureMissing)
3976     return true;
3977 
3978   switch (BuiltinID) {
3979   case RISCVVector::BI__builtin_rvv_vsetvli:
3980     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3981            CheckRISCVLMUL(TheCall, 2);
3982   case RISCVVector::BI__builtin_rvv_vsetvlimax:
3983     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3984            CheckRISCVLMUL(TheCall, 1);
3985   }
3986 
3987   return false;
3988 }
3989 
3990 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3991                                            CallExpr *TheCall) {
3992   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3993     Expr *Arg = TheCall->getArg(0);
3994     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3995       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3996         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3997                << Arg->getSourceRange();
3998   }
3999 
4000   // For intrinsics which take an immediate value as part of the instruction,
4001   // range check them here.
4002   unsigned i = 0, l = 0, u = 0;
4003   switch (BuiltinID) {
4004   default: return false;
4005   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
4006   case SystemZ::BI__builtin_s390_verimb:
4007   case SystemZ::BI__builtin_s390_verimh:
4008   case SystemZ::BI__builtin_s390_verimf:
4009   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
4010   case SystemZ::BI__builtin_s390_vfaeb:
4011   case SystemZ::BI__builtin_s390_vfaeh:
4012   case SystemZ::BI__builtin_s390_vfaef:
4013   case SystemZ::BI__builtin_s390_vfaebs:
4014   case SystemZ::BI__builtin_s390_vfaehs:
4015   case SystemZ::BI__builtin_s390_vfaefs:
4016   case SystemZ::BI__builtin_s390_vfaezb:
4017   case SystemZ::BI__builtin_s390_vfaezh:
4018   case SystemZ::BI__builtin_s390_vfaezf:
4019   case SystemZ::BI__builtin_s390_vfaezbs:
4020   case SystemZ::BI__builtin_s390_vfaezhs:
4021   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
4022   case SystemZ::BI__builtin_s390_vfisb:
4023   case SystemZ::BI__builtin_s390_vfidb:
4024     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
4025            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
4026   case SystemZ::BI__builtin_s390_vftcisb:
4027   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
4028   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
4029   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
4030   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
4031   case SystemZ::BI__builtin_s390_vstrcb:
4032   case SystemZ::BI__builtin_s390_vstrch:
4033   case SystemZ::BI__builtin_s390_vstrcf:
4034   case SystemZ::BI__builtin_s390_vstrczb:
4035   case SystemZ::BI__builtin_s390_vstrczh:
4036   case SystemZ::BI__builtin_s390_vstrczf:
4037   case SystemZ::BI__builtin_s390_vstrcbs:
4038   case SystemZ::BI__builtin_s390_vstrchs:
4039   case SystemZ::BI__builtin_s390_vstrcfs:
4040   case SystemZ::BI__builtin_s390_vstrczbs:
4041   case SystemZ::BI__builtin_s390_vstrczhs:
4042   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
4043   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
4044   case SystemZ::BI__builtin_s390_vfminsb:
4045   case SystemZ::BI__builtin_s390_vfmaxsb:
4046   case SystemZ::BI__builtin_s390_vfmindb:
4047   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
4048   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
4049   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
4050   case SystemZ::BI__builtin_s390_vclfnhs:
4051   case SystemZ::BI__builtin_s390_vclfnls:
4052   case SystemZ::BI__builtin_s390_vcfn:
4053   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
4054   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
4055   }
4056   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
4057 }
4058 
4059 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
4060 /// This checks that the target supports __builtin_cpu_supports and
4061 /// that the string argument is constant and valid.
4062 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
4063                                    CallExpr *TheCall) {
4064   Expr *Arg = TheCall->getArg(0);
4065 
4066   // Check if the argument is a string literal.
4067   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4068     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4069            << Arg->getSourceRange();
4070 
4071   // Check the contents of the string.
4072   StringRef Feature =
4073       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4074   if (!TI.validateCpuSupports(Feature))
4075     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
4076            << Arg->getSourceRange();
4077   return false;
4078 }
4079 
4080 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
4081 /// This checks that the target supports __builtin_cpu_is and
4082 /// that the string argument is constant and valid.
4083 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
4084   Expr *Arg = TheCall->getArg(0);
4085 
4086   // Check if the argument is a string literal.
4087   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4088     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4089            << Arg->getSourceRange();
4090 
4091   // Check the contents of the string.
4092   StringRef Feature =
4093       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4094   if (!TI.validateCpuIs(Feature))
4095     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
4096            << Arg->getSourceRange();
4097   return false;
4098 }
4099 
4100 // Check if the rounding mode is legal.
4101 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
4102   // Indicates if this instruction has rounding control or just SAE.
4103   bool HasRC = false;
4104 
4105   unsigned ArgNum = 0;
4106   switch (BuiltinID) {
4107   default:
4108     return false;
4109   case X86::BI__builtin_ia32_vcvttsd2si32:
4110   case X86::BI__builtin_ia32_vcvttsd2si64:
4111   case X86::BI__builtin_ia32_vcvttsd2usi32:
4112   case X86::BI__builtin_ia32_vcvttsd2usi64:
4113   case X86::BI__builtin_ia32_vcvttss2si32:
4114   case X86::BI__builtin_ia32_vcvttss2si64:
4115   case X86::BI__builtin_ia32_vcvttss2usi32:
4116   case X86::BI__builtin_ia32_vcvttss2usi64:
4117   case X86::BI__builtin_ia32_vcvttsh2si32:
4118   case X86::BI__builtin_ia32_vcvttsh2si64:
4119   case X86::BI__builtin_ia32_vcvttsh2usi32:
4120   case X86::BI__builtin_ia32_vcvttsh2usi64:
4121     ArgNum = 1;
4122     break;
4123   case X86::BI__builtin_ia32_maxpd512:
4124   case X86::BI__builtin_ia32_maxps512:
4125   case X86::BI__builtin_ia32_minpd512:
4126   case X86::BI__builtin_ia32_minps512:
4127   case X86::BI__builtin_ia32_maxph512:
4128   case X86::BI__builtin_ia32_minph512:
4129     ArgNum = 2;
4130     break;
4131   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
4132   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
4133   case X86::BI__builtin_ia32_cvtps2pd512_mask:
4134   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
4135   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
4136   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
4137   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
4138   case X86::BI__builtin_ia32_cvttps2dq512_mask:
4139   case X86::BI__builtin_ia32_cvttps2qq512_mask:
4140   case X86::BI__builtin_ia32_cvttps2udq512_mask:
4141   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
4142   case X86::BI__builtin_ia32_vcvttph2w512_mask:
4143   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
4144   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
4145   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
4146   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
4147   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
4148   case X86::BI__builtin_ia32_exp2pd_mask:
4149   case X86::BI__builtin_ia32_exp2ps_mask:
4150   case X86::BI__builtin_ia32_getexppd512_mask:
4151   case X86::BI__builtin_ia32_getexpps512_mask:
4152   case X86::BI__builtin_ia32_getexpph512_mask:
4153   case X86::BI__builtin_ia32_rcp28pd_mask:
4154   case X86::BI__builtin_ia32_rcp28ps_mask:
4155   case X86::BI__builtin_ia32_rsqrt28pd_mask:
4156   case X86::BI__builtin_ia32_rsqrt28ps_mask:
4157   case X86::BI__builtin_ia32_vcomisd:
4158   case X86::BI__builtin_ia32_vcomiss:
4159   case X86::BI__builtin_ia32_vcomish:
4160   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
4161     ArgNum = 3;
4162     break;
4163   case X86::BI__builtin_ia32_cmppd512_mask:
4164   case X86::BI__builtin_ia32_cmpps512_mask:
4165   case X86::BI__builtin_ia32_cmpsd_mask:
4166   case X86::BI__builtin_ia32_cmpss_mask:
4167   case X86::BI__builtin_ia32_cmpsh_mask:
4168   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
4169   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
4170   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
4171   case X86::BI__builtin_ia32_getexpsd128_round_mask:
4172   case X86::BI__builtin_ia32_getexpss128_round_mask:
4173   case X86::BI__builtin_ia32_getexpsh128_round_mask:
4174   case X86::BI__builtin_ia32_getmantpd512_mask:
4175   case X86::BI__builtin_ia32_getmantps512_mask:
4176   case X86::BI__builtin_ia32_getmantph512_mask:
4177   case X86::BI__builtin_ia32_maxsd_round_mask:
4178   case X86::BI__builtin_ia32_maxss_round_mask:
4179   case X86::BI__builtin_ia32_maxsh_round_mask:
4180   case X86::BI__builtin_ia32_minsd_round_mask:
4181   case X86::BI__builtin_ia32_minss_round_mask:
4182   case X86::BI__builtin_ia32_minsh_round_mask:
4183   case X86::BI__builtin_ia32_rcp28sd_round_mask:
4184   case X86::BI__builtin_ia32_rcp28ss_round_mask:
4185   case X86::BI__builtin_ia32_reducepd512_mask:
4186   case X86::BI__builtin_ia32_reduceps512_mask:
4187   case X86::BI__builtin_ia32_reduceph512_mask:
4188   case X86::BI__builtin_ia32_rndscalepd_mask:
4189   case X86::BI__builtin_ia32_rndscaleps_mask:
4190   case X86::BI__builtin_ia32_rndscaleph_mask:
4191   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
4192   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
4193     ArgNum = 4;
4194     break;
4195   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4196   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4197   case X86::BI__builtin_ia32_fixupimmps512_mask:
4198   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4199   case X86::BI__builtin_ia32_fixupimmsd_mask:
4200   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4201   case X86::BI__builtin_ia32_fixupimmss_mask:
4202   case X86::BI__builtin_ia32_fixupimmss_maskz:
4203   case X86::BI__builtin_ia32_getmantsd_round_mask:
4204   case X86::BI__builtin_ia32_getmantss_round_mask:
4205   case X86::BI__builtin_ia32_getmantsh_round_mask:
4206   case X86::BI__builtin_ia32_rangepd512_mask:
4207   case X86::BI__builtin_ia32_rangeps512_mask:
4208   case X86::BI__builtin_ia32_rangesd128_round_mask:
4209   case X86::BI__builtin_ia32_rangess128_round_mask:
4210   case X86::BI__builtin_ia32_reducesd_mask:
4211   case X86::BI__builtin_ia32_reducess_mask:
4212   case X86::BI__builtin_ia32_reducesh_mask:
4213   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4214   case X86::BI__builtin_ia32_rndscaless_round_mask:
4215   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4216     ArgNum = 5;
4217     break;
4218   case X86::BI__builtin_ia32_vcvtsd2si64:
4219   case X86::BI__builtin_ia32_vcvtsd2si32:
4220   case X86::BI__builtin_ia32_vcvtsd2usi32:
4221   case X86::BI__builtin_ia32_vcvtsd2usi64:
4222   case X86::BI__builtin_ia32_vcvtss2si32:
4223   case X86::BI__builtin_ia32_vcvtss2si64:
4224   case X86::BI__builtin_ia32_vcvtss2usi32:
4225   case X86::BI__builtin_ia32_vcvtss2usi64:
4226   case X86::BI__builtin_ia32_vcvtsh2si32:
4227   case X86::BI__builtin_ia32_vcvtsh2si64:
4228   case X86::BI__builtin_ia32_vcvtsh2usi32:
4229   case X86::BI__builtin_ia32_vcvtsh2usi64:
4230   case X86::BI__builtin_ia32_sqrtpd512:
4231   case X86::BI__builtin_ia32_sqrtps512:
4232   case X86::BI__builtin_ia32_sqrtph512:
4233     ArgNum = 1;
4234     HasRC = true;
4235     break;
4236   case X86::BI__builtin_ia32_addph512:
4237   case X86::BI__builtin_ia32_divph512:
4238   case X86::BI__builtin_ia32_mulph512:
4239   case X86::BI__builtin_ia32_subph512:
4240   case X86::BI__builtin_ia32_addpd512:
4241   case X86::BI__builtin_ia32_addps512:
4242   case X86::BI__builtin_ia32_divpd512:
4243   case X86::BI__builtin_ia32_divps512:
4244   case X86::BI__builtin_ia32_mulpd512:
4245   case X86::BI__builtin_ia32_mulps512:
4246   case X86::BI__builtin_ia32_subpd512:
4247   case X86::BI__builtin_ia32_subps512:
4248   case X86::BI__builtin_ia32_cvtsi2sd64:
4249   case X86::BI__builtin_ia32_cvtsi2ss32:
4250   case X86::BI__builtin_ia32_cvtsi2ss64:
4251   case X86::BI__builtin_ia32_cvtusi2sd64:
4252   case X86::BI__builtin_ia32_cvtusi2ss32:
4253   case X86::BI__builtin_ia32_cvtusi2ss64:
4254   case X86::BI__builtin_ia32_vcvtusi2sh:
4255   case X86::BI__builtin_ia32_vcvtusi642sh:
4256   case X86::BI__builtin_ia32_vcvtsi2sh:
4257   case X86::BI__builtin_ia32_vcvtsi642sh:
4258     ArgNum = 2;
4259     HasRC = true;
4260     break;
4261   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
4262   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
4263   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
4264   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
4265   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
4266   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
4267   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
4268   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
4269   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
4270   case X86::BI__builtin_ia32_cvtps2dq512_mask:
4271   case X86::BI__builtin_ia32_cvtps2qq512_mask:
4272   case X86::BI__builtin_ia32_cvtps2udq512_mask:
4273   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
4274   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
4275   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
4276   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
4277   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
4278   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
4279   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
4280   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
4281   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
4282   case X86::BI__builtin_ia32_vcvtph2w512_mask:
4283   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
4284   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
4285   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
4286   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
4287   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
4288   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
4289   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
4290     ArgNum = 3;
4291     HasRC = true;
4292     break;
4293   case X86::BI__builtin_ia32_addsh_round_mask:
4294   case X86::BI__builtin_ia32_addss_round_mask:
4295   case X86::BI__builtin_ia32_addsd_round_mask:
4296   case X86::BI__builtin_ia32_divsh_round_mask:
4297   case X86::BI__builtin_ia32_divss_round_mask:
4298   case X86::BI__builtin_ia32_divsd_round_mask:
4299   case X86::BI__builtin_ia32_mulsh_round_mask:
4300   case X86::BI__builtin_ia32_mulss_round_mask:
4301   case X86::BI__builtin_ia32_mulsd_round_mask:
4302   case X86::BI__builtin_ia32_subsh_round_mask:
4303   case X86::BI__builtin_ia32_subss_round_mask:
4304   case X86::BI__builtin_ia32_subsd_round_mask:
4305   case X86::BI__builtin_ia32_scalefph512_mask:
4306   case X86::BI__builtin_ia32_scalefpd512_mask:
4307   case X86::BI__builtin_ia32_scalefps512_mask:
4308   case X86::BI__builtin_ia32_scalefsd_round_mask:
4309   case X86::BI__builtin_ia32_scalefss_round_mask:
4310   case X86::BI__builtin_ia32_scalefsh_round_mask:
4311   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4312   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4313   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4314   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4315   case X86::BI__builtin_ia32_sqrtss_round_mask:
4316   case X86::BI__builtin_ia32_sqrtsh_round_mask:
4317   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4318   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4319   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4320   case X86::BI__builtin_ia32_vfmaddss3_mask:
4321   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4322   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4323   case X86::BI__builtin_ia32_vfmaddsh3_mask:
4324   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4325   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4326   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4327   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4328   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4329   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4330   case X86::BI__builtin_ia32_vfmaddps512_mask:
4331   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4332   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4333   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4334   case X86::BI__builtin_ia32_vfmaddph512_mask:
4335   case X86::BI__builtin_ia32_vfmaddph512_maskz:
4336   case X86::BI__builtin_ia32_vfmaddph512_mask3:
4337   case X86::BI__builtin_ia32_vfmsubph512_mask3:
4338   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4339   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4340   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4341   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4342   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4343   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4344   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4345   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4346   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4347   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4348   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4349   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4350   case X86::BI__builtin_ia32_vfmaddcsh_mask:
4351   case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
4352   case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
4353   case X86::BI__builtin_ia32_vfmaddcph512_mask:
4354   case X86::BI__builtin_ia32_vfmaddcph512_maskz:
4355   case X86::BI__builtin_ia32_vfmaddcph512_mask3:
4356   case X86::BI__builtin_ia32_vfcmaddcsh_mask:
4357   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
4358   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
4359   case X86::BI__builtin_ia32_vfcmaddcph512_mask:
4360   case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
4361   case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
4362   case X86::BI__builtin_ia32_vfmulcsh_mask:
4363   case X86::BI__builtin_ia32_vfmulcph512_mask:
4364   case X86::BI__builtin_ia32_vfcmulcsh_mask:
4365   case X86::BI__builtin_ia32_vfcmulcph512_mask:
4366     ArgNum = 4;
4367     HasRC = true;
4368     break;
4369   }
4370 
4371   llvm::APSInt Result;
4372 
4373   // We can't check the value of a dependent argument.
4374   Expr *Arg = TheCall->getArg(ArgNum);
4375   if (Arg->isTypeDependent() || Arg->isValueDependent())
4376     return false;
4377 
4378   // Check constant-ness first.
4379   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4380     return true;
4381 
4382   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4383   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4384   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4385   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4386   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4387       Result == 8/*ROUND_NO_EXC*/ ||
4388       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4389       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4390     return false;
4391 
4392   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4393          << Arg->getSourceRange();
4394 }
4395 
4396 // Check if the gather/scatter scale is legal.
4397 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4398                                              CallExpr *TheCall) {
4399   unsigned ArgNum = 0;
4400   switch (BuiltinID) {
4401   default:
4402     return false;
4403   case X86::BI__builtin_ia32_gatherpfdpd:
4404   case X86::BI__builtin_ia32_gatherpfdps:
4405   case X86::BI__builtin_ia32_gatherpfqpd:
4406   case X86::BI__builtin_ia32_gatherpfqps:
4407   case X86::BI__builtin_ia32_scatterpfdpd:
4408   case X86::BI__builtin_ia32_scatterpfdps:
4409   case X86::BI__builtin_ia32_scatterpfqpd:
4410   case X86::BI__builtin_ia32_scatterpfqps:
4411     ArgNum = 3;
4412     break;
4413   case X86::BI__builtin_ia32_gatherd_pd:
4414   case X86::BI__builtin_ia32_gatherd_pd256:
4415   case X86::BI__builtin_ia32_gatherq_pd:
4416   case X86::BI__builtin_ia32_gatherq_pd256:
4417   case X86::BI__builtin_ia32_gatherd_ps:
4418   case X86::BI__builtin_ia32_gatherd_ps256:
4419   case X86::BI__builtin_ia32_gatherq_ps:
4420   case X86::BI__builtin_ia32_gatherq_ps256:
4421   case X86::BI__builtin_ia32_gatherd_q:
4422   case X86::BI__builtin_ia32_gatherd_q256:
4423   case X86::BI__builtin_ia32_gatherq_q:
4424   case X86::BI__builtin_ia32_gatherq_q256:
4425   case X86::BI__builtin_ia32_gatherd_d:
4426   case X86::BI__builtin_ia32_gatherd_d256:
4427   case X86::BI__builtin_ia32_gatherq_d:
4428   case X86::BI__builtin_ia32_gatherq_d256:
4429   case X86::BI__builtin_ia32_gather3div2df:
4430   case X86::BI__builtin_ia32_gather3div2di:
4431   case X86::BI__builtin_ia32_gather3div4df:
4432   case X86::BI__builtin_ia32_gather3div4di:
4433   case X86::BI__builtin_ia32_gather3div4sf:
4434   case X86::BI__builtin_ia32_gather3div4si:
4435   case X86::BI__builtin_ia32_gather3div8sf:
4436   case X86::BI__builtin_ia32_gather3div8si:
4437   case X86::BI__builtin_ia32_gather3siv2df:
4438   case X86::BI__builtin_ia32_gather3siv2di:
4439   case X86::BI__builtin_ia32_gather3siv4df:
4440   case X86::BI__builtin_ia32_gather3siv4di:
4441   case X86::BI__builtin_ia32_gather3siv4sf:
4442   case X86::BI__builtin_ia32_gather3siv4si:
4443   case X86::BI__builtin_ia32_gather3siv8sf:
4444   case X86::BI__builtin_ia32_gather3siv8si:
4445   case X86::BI__builtin_ia32_gathersiv8df:
4446   case X86::BI__builtin_ia32_gathersiv16sf:
4447   case X86::BI__builtin_ia32_gatherdiv8df:
4448   case X86::BI__builtin_ia32_gatherdiv16sf:
4449   case X86::BI__builtin_ia32_gathersiv8di:
4450   case X86::BI__builtin_ia32_gathersiv16si:
4451   case X86::BI__builtin_ia32_gatherdiv8di:
4452   case X86::BI__builtin_ia32_gatherdiv16si:
4453   case X86::BI__builtin_ia32_scatterdiv2df:
4454   case X86::BI__builtin_ia32_scatterdiv2di:
4455   case X86::BI__builtin_ia32_scatterdiv4df:
4456   case X86::BI__builtin_ia32_scatterdiv4di:
4457   case X86::BI__builtin_ia32_scatterdiv4sf:
4458   case X86::BI__builtin_ia32_scatterdiv4si:
4459   case X86::BI__builtin_ia32_scatterdiv8sf:
4460   case X86::BI__builtin_ia32_scatterdiv8si:
4461   case X86::BI__builtin_ia32_scattersiv2df:
4462   case X86::BI__builtin_ia32_scattersiv2di:
4463   case X86::BI__builtin_ia32_scattersiv4df:
4464   case X86::BI__builtin_ia32_scattersiv4di:
4465   case X86::BI__builtin_ia32_scattersiv4sf:
4466   case X86::BI__builtin_ia32_scattersiv4si:
4467   case X86::BI__builtin_ia32_scattersiv8sf:
4468   case X86::BI__builtin_ia32_scattersiv8si:
4469   case X86::BI__builtin_ia32_scattersiv8df:
4470   case X86::BI__builtin_ia32_scattersiv16sf:
4471   case X86::BI__builtin_ia32_scatterdiv8df:
4472   case X86::BI__builtin_ia32_scatterdiv16sf:
4473   case X86::BI__builtin_ia32_scattersiv8di:
4474   case X86::BI__builtin_ia32_scattersiv16si:
4475   case X86::BI__builtin_ia32_scatterdiv8di:
4476   case X86::BI__builtin_ia32_scatterdiv16si:
4477     ArgNum = 4;
4478     break;
4479   }
4480 
4481   llvm::APSInt Result;
4482 
4483   // We can't check the value of a dependent argument.
4484   Expr *Arg = TheCall->getArg(ArgNum);
4485   if (Arg->isTypeDependent() || Arg->isValueDependent())
4486     return false;
4487 
4488   // Check constant-ness first.
4489   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4490     return true;
4491 
4492   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4493     return false;
4494 
4495   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4496          << Arg->getSourceRange();
4497 }
4498 
4499 enum { TileRegLow = 0, TileRegHigh = 7 };
4500 
4501 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4502                                              ArrayRef<int> ArgNums) {
4503   for (int ArgNum : ArgNums) {
4504     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4505       return true;
4506   }
4507   return false;
4508 }
4509 
4510 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4511                                         ArrayRef<int> ArgNums) {
4512   // Because the max number of tile register is TileRegHigh + 1, so here we use
4513   // each bit to represent the usage of them in bitset.
4514   std::bitset<TileRegHigh + 1> ArgValues;
4515   for (int ArgNum : ArgNums) {
4516     Expr *Arg = TheCall->getArg(ArgNum);
4517     if (Arg->isTypeDependent() || Arg->isValueDependent())
4518       continue;
4519 
4520     llvm::APSInt Result;
4521     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4522       return true;
4523     int ArgExtValue = Result.getExtValue();
4524     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4525            "Incorrect tile register num.");
4526     if (ArgValues.test(ArgExtValue))
4527       return Diag(TheCall->getBeginLoc(),
4528                   diag::err_x86_builtin_tile_arg_duplicate)
4529              << TheCall->getArg(ArgNum)->getSourceRange();
4530     ArgValues.set(ArgExtValue);
4531   }
4532   return false;
4533 }
4534 
4535 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4536                                                 ArrayRef<int> ArgNums) {
4537   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4538          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4539 }
4540 
4541 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4542   switch (BuiltinID) {
4543   default:
4544     return false;
4545   case X86::BI__builtin_ia32_tileloadd64:
4546   case X86::BI__builtin_ia32_tileloaddt164:
4547   case X86::BI__builtin_ia32_tilestored64:
4548   case X86::BI__builtin_ia32_tilezero:
4549     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4550   case X86::BI__builtin_ia32_tdpbssd:
4551   case X86::BI__builtin_ia32_tdpbsud:
4552   case X86::BI__builtin_ia32_tdpbusd:
4553   case X86::BI__builtin_ia32_tdpbuud:
4554   case X86::BI__builtin_ia32_tdpbf16ps:
4555     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4556   }
4557 }
4558 static bool isX86_32Builtin(unsigned BuiltinID) {
4559   // These builtins only work on x86-32 targets.
4560   switch (BuiltinID) {
4561   case X86::BI__builtin_ia32_readeflags_u32:
4562   case X86::BI__builtin_ia32_writeeflags_u32:
4563     return true;
4564   }
4565 
4566   return false;
4567 }
4568 
4569 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4570                                        CallExpr *TheCall) {
4571   if (BuiltinID == X86::BI__builtin_cpu_supports)
4572     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4573 
4574   if (BuiltinID == X86::BI__builtin_cpu_is)
4575     return SemaBuiltinCpuIs(*this, TI, TheCall);
4576 
4577   // Check for 32-bit only builtins on a 64-bit target.
4578   const llvm::Triple &TT = TI.getTriple();
4579   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4580     return Diag(TheCall->getCallee()->getBeginLoc(),
4581                 diag::err_32_bit_builtin_64_bit_tgt);
4582 
4583   // If the intrinsic has rounding or SAE make sure its valid.
4584   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4585     return true;
4586 
4587   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4588   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4589     return true;
4590 
4591   // If the intrinsic has a tile arguments, make sure they are valid.
4592   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4593     return true;
4594 
4595   // For intrinsics which take an immediate value as part of the instruction,
4596   // range check them here.
4597   int i = 0, l = 0, u = 0;
4598   switch (BuiltinID) {
4599   default:
4600     return false;
4601   case X86::BI__builtin_ia32_vec_ext_v2si:
4602   case X86::BI__builtin_ia32_vec_ext_v2di:
4603   case X86::BI__builtin_ia32_vextractf128_pd256:
4604   case X86::BI__builtin_ia32_vextractf128_ps256:
4605   case X86::BI__builtin_ia32_vextractf128_si256:
4606   case X86::BI__builtin_ia32_extract128i256:
4607   case X86::BI__builtin_ia32_extractf64x4_mask:
4608   case X86::BI__builtin_ia32_extracti64x4_mask:
4609   case X86::BI__builtin_ia32_extractf32x8_mask:
4610   case X86::BI__builtin_ia32_extracti32x8_mask:
4611   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4612   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4613   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4614   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4615     i = 1; l = 0; u = 1;
4616     break;
4617   case X86::BI__builtin_ia32_vec_set_v2di:
4618   case X86::BI__builtin_ia32_vinsertf128_pd256:
4619   case X86::BI__builtin_ia32_vinsertf128_ps256:
4620   case X86::BI__builtin_ia32_vinsertf128_si256:
4621   case X86::BI__builtin_ia32_insert128i256:
4622   case X86::BI__builtin_ia32_insertf32x8:
4623   case X86::BI__builtin_ia32_inserti32x8:
4624   case X86::BI__builtin_ia32_insertf64x4:
4625   case X86::BI__builtin_ia32_inserti64x4:
4626   case X86::BI__builtin_ia32_insertf64x2_256:
4627   case X86::BI__builtin_ia32_inserti64x2_256:
4628   case X86::BI__builtin_ia32_insertf32x4_256:
4629   case X86::BI__builtin_ia32_inserti32x4_256:
4630     i = 2; l = 0; u = 1;
4631     break;
4632   case X86::BI__builtin_ia32_vpermilpd:
4633   case X86::BI__builtin_ia32_vec_ext_v4hi:
4634   case X86::BI__builtin_ia32_vec_ext_v4si:
4635   case X86::BI__builtin_ia32_vec_ext_v4sf:
4636   case X86::BI__builtin_ia32_vec_ext_v4di:
4637   case X86::BI__builtin_ia32_extractf32x4_mask:
4638   case X86::BI__builtin_ia32_extracti32x4_mask:
4639   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4640   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4641     i = 1; l = 0; u = 3;
4642     break;
4643   case X86::BI_mm_prefetch:
4644   case X86::BI__builtin_ia32_vec_ext_v8hi:
4645   case X86::BI__builtin_ia32_vec_ext_v8si:
4646     i = 1; l = 0; u = 7;
4647     break;
4648   case X86::BI__builtin_ia32_sha1rnds4:
4649   case X86::BI__builtin_ia32_blendpd:
4650   case X86::BI__builtin_ia32_shufpd:
4651   case X86::BI__builtin_ia32_vec_set_v4hi:
4652   case X86::BI__builtin_ia32_vec_set_v4si:
4653   case X86::BI__builtin_ia32_vec_set_v4di:
4654   case X86::BI__builtin_ia32_shuf_f32x4_256:
4655   case X86::BI__builtin_ia32_shuf_f64x2_256:
4656   case X86::BI__builtin_ia32_shuf_i32x4_256:
4657   case X86::BI__builtin_ia32_shuf_i64x2_256:
4658   case X86::BI__builtin_ia32_insertf64x2_512:
4659   case X86::BI__builtin_ia32_inserti64x2_512:
4660   case X86::BI__builtin_ia32_insertf32x4:
4661   case X86::BI__builtin_ia32_inserti32x4:
4662     i = 2; l = 0; u = 3;
4663     break;
4664   case X86::BI__builtin_ia32_vpermil2pd:
4665   case X86::BI__builtin_ia32_vpermil2pd256:
4666   case X86::BI__builtin_ia32_vpermil2ps:
4667   case X86::BI__builtin_ia32_vpermil2ps256:
4668     i = 3; l = 0; u = 3;
4669     break;
4670   case X86::BI__builtin_ia32_cmpb128_mask:
4671   case X86::BI__builtin_ia32_cmpw128_mask:
4672   case X86::BI__builtin_ia32_cmpd128_mask:
4673   case X86::BI__builtin_ia32_cmpq128_mask:
4674   case X86::BI__builtin_ia32_cmpb256_mask:
4675   case X86::BI__builtin_ia32_cmpw256_mask:
4676   case X86::BI__builtin_ia32_cmpd256_mask:
4677   case X86::BI__builtin_ia32_cmpq256_mask:
4678   case X86::BI__builtin_ia32_cmpb512_mask:
4679   case X86::BI__builtin_ia32_cmpw512_mask:
4680   case X86::BI__builtin_ia32_cmpd512_mask:
4681   case X86::BI__builtin_ia32_cmpq512_mask:
4682   case X86::BI__builtin_ia32_ucmpb128_mask:
4683   case X86::BI__builtin_ia32_ucmpw128_mask:
4684   case X86::BI__builtin_ia32_ucmpd128_mask:
4685   case X86::BI__builtin_ia32_ucmpq128_mask:
4686   case X86::BI__builtin_ia32_ucmpb256_mask:
4687   case X86::BI__builtin_ia32_ucmpw256_mask:
4688   case X86::BI__builtin_ia32_ucmpd256_mask:
4689   case X86::BI__builtin_ia32_ucmpq256_mask:
4690   case X86::BI__builtin_ia32_ucmpb512_mask:
4691   case X86::BI__builtin_ia32_ucmpw512_mask:
4692   case X86::BI__builtin_ia32_ucmpd512_mask:
4693   case X86::BI__builtin_ia32_ucmpq512_mask:
4694   case X86::BI__builtin_ia32_vpcomub:
4695   case X86::BI__builtin_ia32_vpcomuw:
4696   case X86::BI__builtin_ia32_vpcomud:
4697   case X86::BI__builtin_ia32_vpcomuq:
4698   case X86::BI__builtin_ia32_vpcomb:
4699   case X86::BI__builtin_ia32_vpcomw:
4700   case X86::BI__builtin_ia32_vpcomd:
4701   case X86::BI__builtin_ia32_vpcomq:
4702   case X86::BI__builtin_ia32_vec_set_v8hi:
4703   case X86::BI__builtin_ia32_vec_set_v8si:
4704     i = 2; l = 0; u = 7;
4705     break;
4706   case X86::BI__builtin_ia32_vpermilpd256:
4707   case X86::BI__builtin_ia32_roundps:
4708   case X86::BI__builtin_ia32_roundpd:
4709   case X86::BI__builtin_ia32_roundps256:
4710   case X86::BI__builtin_ia32_roundpd256:
4711   case X86::BI__builtin_ia32_getmantpd128_mask:
4712   case X86::BI__builtin_ia32_getmantpd256_mask:
4713   case X86::BI__builtin_ia32_getmantps128_mask:
4714   case X86::BI__builtin_ia32_getmantps256_mask:
4715   case X86::BI__builtin_ia32_getmantpd512_mask:
4716   case X86::BI__builtin_ia32_getmantps512_mask:
4717   case X86::BI__builtin_ia32_getmantph128_mask:
4718   case X86::BI__builtin_ia32_getmantph256_mask:
4719   case X86::BI__builtin_ia32_getmantph512_mask:
4720   case X86::BI__builtin_ia32_vec_ext_v16qi:
4721   case X86::BI__builtin_ia32_vec_ext_v16hi:
4722     i = 1; l = 0; u = 15;
4723     break;
4724   case X86::BI__builtin_ia32_pblendd128:
4725   case X86::BI__builtin_ia32_blendps:
4726   case X86::BI__builtin_ia32_blendpd256:
4727   case X86::BI__builtin_ia32_shufpd256:
4728   case X86::BI__builtin_ia32_roundss:
4729   case X86::BI__builtin_ia32_roundsd:
4730   case X86::BI__builtin_ia32_rangepd128_mask:
4731   case X86::BI__builtin_ia32_rangepd256_mask:
4732   case X86::BI__builtin_ia32_rangepd512_mask:
4733   case X86::BI__builtin_ia32_rangeps128_mask:
4734   case X86::BI__builtin_ia32_rangeps256_mask:
4735   case X86::BI__builtin_ia32_rangeps512_mask:
4736   case X86::BI__builtin_ia32_getmantsd_round_mask:
4737   case X86::BI__builtin_ia32_getmantss_round_mask:
4738   case X86::BI__builtin_ia32_getmantsh_round_mask:
4739   case X86::BI__builtin_ia32_vec_set_v16qi:
4740   case X86::BI__builtin_ia32_vec_set_v16hi:
4741     i = 2; l = 0; u = 15;
4742     break;
4743   case X86::BI__builtin_ia32_vec_ext_v32qi:
4744     i = 1; l = 0; u = 31;
4745     break;
4746   case X86::BI__builtin_ia32_cmpps:
4747   case X86::BI__builtin_ia32_cmpss:
4748   case X86::BI__builtin_ia32_cmppd:
4749   case X86::BI__builtin_ia32_cmpsd:
4750   case X86::BI__builtin_ia32_cmpps256:
4751   case X86::BI__builtin_ia32_cmppd256:
4752   case X86::BI__builtin_ia32_cmpps128_mask:
4753   case X86::BI__builtin_ia32_cmppd128_mask:
4754   case X86::BI__builtin_ia32_cmpps256_mask:
4755   case X86::BI__builtin_ia32_cmppd256_mask:
4756   case X86::BI__builtin_ia32_cmpps512_mask:
4757   case X86::BI__builtin_ia32_cmppd512_mask:
4758   case X86::BI__builtin_ia32_cmpsd_mask:
4759   case X86::BI__builtin_ia32_cmpss_mask:
4760   case X86::BI__builtin_ia32_vec_set_v32qi:
4761     i = 2; l = 0; u = 31;
4762     break;
4763   case X86::BI__builtin_ia32_permdf256:
4764   case X86::BI__builtin_ia32_permdi256:
4765   case X86::BI__builtin_ia32_permdf512:
4766   case X86::BI__builtin_ia32_permdi512:
4767   case X86::BI__builtin_ia32_vpermilps:
4768   case X86::BI__builtin_ia32_vpermilps256:
4769   case X86::BI__builtin_ia32_vpermilpd512:
4770   case X86::BI__builtin_ia32_vpermilps512:
4771   case X86::BI__builtin_ia32_pshufd:
4772   case X86::BI__builtin_ia32_pshufd256:
4773   case X86::BI__builtin_ia32_pshufd512:
4774   case X86::BI__builtin_ia32_pshufhw:
4775   case X86::BI__builtin_ia32_pshufhw256:
4776   case X86::BI__builtin_ia32_pshufhw512:
4777   case X86::BI__builtin_ia32_pshuflw:
4778   case X86::BI__builtin_ia32_pshuflw256:
4779   case X86::BI__builtin_ia32_pshuflw512:
4780   case X86::BI__builtin_ia32_vcvtps2ph:
4781   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4782   case X86::BI__builtin_ia32_vcvtps2ph256:
4783   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4784   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4785   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4786   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4787   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4788   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4789   case X86::BI__builtin_ia32_rndscaleps_mask:
4790   case X86::BI__builtin_ia32_rndscalepd_mask:
4791   case X86::BI__builtin_ia32_rndscaleph_mask:
4792   case X86::BI__builtin_ia32_reducepd128_mask:
4793   case X86::BI__builtin_ia32_reducepd256_mask:
4794   case X86::BI__builtin_ia32_reducepd512_mask:
4795   case X86::BI__builtin_ia32_reduceps128_mask:
4796   case X86::BI__builtin_ia32_reduceps256_mask:
4797   case X86::BI__builtin_ia32_reduceps512_mask:
4798   case X86::BI__builtin_ia32_reduceph128_mask:
4799   case X86::BI__builtin_ia32_reduceph256_mask:
4800   case X86::BI__builtin_ia32_reduceph512_mask:
4801   case X86::BI__builtin_ia32_prold512:
4802   case X86::BI__builtin_ia32_prolq512:
4803   case X86::BI__builtin_ia32_prold128:
4804   case X86::BI__builtin_ia32_prold256:
4805   case X86::BI__builtin_ia32_prolq128:
4806   case X86::BI__builtin_ia32_prolq256:
4807   case X86::BI__builtin_ia32_prord512:
4808   case X86::BI__builtin_ia32_prorq512:
4809   case X86::BI__builtin_ia32_prord128:
4810   case X86::BI__builtin_ia32_prord256:
4811   case X86::BI__builtin_ia32_prorq128:
4812   case X86::BI__builtin_ia32_prorq256:
4813   case X86::BI__builtin_ia32_fpclasspd128_mask:
4814   case X86::BI__builtin_ia32_fpclasspd256_mask:
4815   case X86::BI__builtin_ia32_fpclassps128_mask:
4816   case X86::BI__builtin_ia32_fpclassps256_mask:
4817   case X86::BI__builtin_ia32_fpclassps512_mask:
4818   case X86::BI__builtin_ia32_fpclasspd512_mask:
4819   case X86::BI__builtin_ia32_fpclassph128_mask:
4820   case X86::BI__builtin_ia32_fpclassph256_mask:
4821   case X86::BI__builtin_ia32_fpclassph512_mask:
4822   case X86::BI__builtin_ia32_fpclasssd_mask:
4823   case X86::BI__builtin_ia32_fpclassss_mask:
4824   case X86::BI__builtin_ia32_fpclasssh_mask:
4825   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4826   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4827   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4828   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4829   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4830   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4831   case X86::BI__builtin_ia32_kshiftliqi:
4832   case X86::BI__builtin_ia32_kshiftlihi:
4833   case X86::BI__builtin_ia32_kshiftlisi:
4834   case X86::BI__builtin_ia32_kshiftlidi:
4835   case X86::BI__builtin_ia32_kshiftriqi:
4836   case X86::BI__builtin_ia32_kshiftrihi:
4837   case X86::BI__builtin_ia32_kshiftrisi:
4838   case X86::BI__builtin_ia32_kshiftridi:
4839     i = 1; l = 0; u = 255;
4840     break;
4841   case X86::BI__builtin_ia32_vperm2f128_pd256:
4842   case X86::BI__builtin_ia32_vperm2f128_ps256:
4843   case X86::BI__builtin_ia32_vperm2f128_si256:
4844   case X86::BI__builtin_ia32_permti256:
4845   case X86::BI__builtin_ia32_pblendw128:
4846   case X86::BI__builtin_ia32_pblendw256:
4847   case X86::BI__builtin_ia32_blendps256:
4848   case X86::BI__builtin_ia32_pblendd256:
4849   case X86::BI__builtin_ia32_palignr128:
4850   case X86::BI__builtin_ia32_palignr256:
4851   case X86::BI__builtin_ia32_palignr512:
4852   case X86::BI__builtin_ia32_alignq512:
4853   case X86::BI__builtin_ia32_alignd512:
4854   case X86::BI__builtin_ia32_alignd128:
4855   case X86::BI__builtin_ia32_alignd256:
4856   case X86::BI__builtin_ia32_alignq128:
4857   case X86::BI__builtin_ia32_alignq256:
4858   case X86::BI__builtin_ia32_vcomisd:
4859   case X86::BI__builtin_ia32_vcomiss:
4860   case X86::BI__builtin_ia32_shuf_f32x4:
4861   case X86::BI__builtin_ia32_shuf_f64x2:
4862   case X86::BI__builtin_ia32_shuf_i32x4:
4863   case X86::BI__builtin_ia32_shuf_i64x2:
4864   case X86::BI__builtin_ia32_shufpd512:
4865   case X86::BI__builtin_ia32_shufps:
4866   case X86::BI__builtin_ia32_shufps256:
4867   case X86::BI__builtin_ia32_shufps512:
4868   case X86::BI__builtin_ia32_dbpsadbw128:
4869   case X86::BI__builtin_ia32_dbpsadbw256:
4870   case X86::BI__builtin_ia32_dbpsadbw512:
4871   case X86::BI__builtin_ia32_vpshldd128:
4872   case X86::BI__builtin_ia32_vpshldd256:
4873   case X86::BI__builtin_ia32_vpshldd512:
4874   case X86::BI__builtin_ia32_vpshldq128:
4875   case X86::BI__builtin_ia32_vpshldq256:
4876   case X86::BI__builtin_ia32_vpshldq512:
4877   case X86::BI__builtin_ia32_vpshldw128:
4878   case X86::BI__builtin_ia32_vpshldw256:
4879   case X86::BI__builtin_ia32_vpshldw512:
4880   case X86::BI__builtin_ia32_vpshrdd128:
4881   case X86::BI__builtin_ia32_vpshrdd256:
4882   case X86::BI__builtin_ia32_vpshrdd512:
4883   case X86::BI__builtin_ia32_vpshrdq128:
4884   case X86::BI__builtin_ia32_vpshrdq256:
4885   case X86::BI__builtin_ia32_vpshrdq512:
4886   case X86::BI__builtin_ia32_vpshrdw128:
4887   case X86::BI__builtin_ia32_vpshrdw256:
4888   case X86::BI__builtin_ia32_vpshrdw512:
4889     i = 2; l = 0; u = 255;
4890     break;
4891   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4892   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4893   case X86::BI__builtin_ia32_fixupimmps512_mask:
4894   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4895   case X86::BI__builtin_ia32_fixupimmsd_mask:
4896   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4897   case X86::BI__builtin_ia32_fixupimmss_mask:
4898   case X86::BI__builtin_ia32_fixupimmss_maskz:
4899   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4900   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4901   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4902   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4903   case X86::BI__builtin_ia32_fixupimmps128_mask:
4904   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4905   case X86::BI__builtin_ia32_fixupimmps256_mask:
4906   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4907   case X86::BI__builtin_ia32_pternlogd512_mask:
4908   case X86::BI__builtin_ia32_pternlogd512_maskz:
4909   case X86::BI__builtin_ia32_pternlogq512_mask:
4910   case X86::BI__builtin_ia32_pternlogq512_maskz:
4911   case X86::BI__builtin_ia32_pternlogd128_mask:
4912   case X86::BI__builtin_ia32_pternlogd128_maskz:
4913   case X86::BI__builtin_ia32_pternlogd256_mask:
4914   case X86::BI__builtin_ia32_pternlogd256_maskz:
4915   case X86::BI__builtin_ia32_pternlogq128_mask:
4916   case X86::BI__builtin_ia32_pternlogq128_maskz:
4917   case X86::BI__builtin_ia32_pternlogq256_mask:
4918   case X86::BI__builtin_ia32_pternlogq256_maskz:
4919     i = 3; l = 0; u = 255;
4920     break;
4921   case X86::BI__builtin_ia32_gatherpfdpd:
4922   case X86::BI__builtin_ia32_gatherpfdps:
4923   case X86::BI__builtin_ia32_gatherpfqpd:
4924   case X86::BI__builtin_ia32_gatherpfqps:
4925   case X86::BI__builtin_ia32_scatterpfdpd:
4926   case X86::BI__builtin_ia32_scatterpfdps:
4927   case X86::BI__builtin_ia32_scatterpfqpd:
4928   case X86::BI__builtin_ia32_scatterpfqps:
4929     i = 4; l = 2; u = 3;
4930     break;
4931   case X86::BI__builtin_ia32_reducesd_mask:
4932   case X86::BI__builtin_ia32_reducess_mask:
4933   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4934   case X86::BI__builtin_ia32_rndscaless_round_mask:
4935   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4936   case X86::BI__builtin_ia32_reducesh_mask:
4937     i = 4; l = 0; u = 255;
4938     break;
4939   }
4940 
4941   // Note that we don't force a hard error on the range check here, allowing
4942   // template-generated or macro-generated dead code to potentially have out-of-
4943   // range values. These need to code generate, but don't need to necessarily
4944   // make any sense. We use a warning that defaults to an error.
4945   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4946 }
4947 
4948 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4949 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4950 /// Returns true when the format fits the function and the FormatStringInfo has
4951 /// been populated.
4952 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4953                                FormatStringInfo *FSI) {
4954   FSI->HasVAListArg = Format->getFirstArg() == 0;
4955   FSI->FormatIdx = Format->getFormatIdx() - 1;
4956   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4957 
4958   // The way the format attribute works in GCC, the implicit this argument
4959   // of member functions is counted. However, it doesn't appear in our own
4960   // lists, so decrement format_idx in that case.
4961   if (IsCXXMember) {
4962     if(FSI->FormatIdx == 0)
4963       return false;
4964     --FSI->FormatIdx;
4965     if (FSI->FirstDataArg != 0)
4966       --FSI->FirstDataArg;
4967   }
4968   return true;
4969 }
4970 
4971 /// Checks if a the given expression evaluates to null.
4972 ///
4973 /// Returns true if the value evaluates to null.
4974 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4975   // If the expression has non-null type, it doesn't evaluate to null.
4976   if (auto nullability
4977         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4978     if (*nullability == NullabilityKind::NonNull)
4979       return false;
4980   }
4981 
4982   // As a special case, transparent unions initialized with zero are
4983   // considered null for the purposes of the nonnull attribute.
4984   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4985     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4986       if (const CompoundLiteralExpr *CLE =
4987           dyn_cast<CompoundLiteralExpr>(Expr))
4988         if (const InitListExpr *ILE =
4989             dyn_cast<InitListExpr>(CLE->getInitializer()))
4990           Expr = ILE->getInit(0);
4991   }
4992 
4993   bool Result;
4994   return (!Expr->isValueDependent() &&
4995           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4996           !Result);
4997 }
4998 
4999 static void CheckNonNullArgument(Sema &S,
5000                                  const Expr *ArgExpr,
5001                                  SourceLocation CallSiteLoc) {
5002   if (CheckNonNullExpr(S, ArgExpr))
5003     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
5004                           S.PDiag(diag::warn_null_arg)
5005                               << ArgExpr->getSourceRange());
5006 }
5007 
5008 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
5009   FormatStringInfo FSI;
5010   if ((GetFormatStringType(Format) == FST_NSString) &&
5011       getFormatStringInfo(Format, false, &FSI)) {
5012     Idx = FSI.FormatIdx;
5013     return true;
5014   }
5015   return false;
5016 }
5017 
5018 /// Diagnose use of %s directive in an NSString which is being passed
5019 /// as formatting string to formatting method.
5020 static void
5021 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
5022                                         const NamedDecl *FDecl,
5023                                         Expr **Args,
5024                                         unsigned NumArgs) {
5025   unsigned Idx = 0;
5026   bool Format = false;
5027   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
5028   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
5029     Idx = 2;
5030     Format = true;
5031   }
5032   else
5033     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5034       if (S.GetFormatNSStringIdx(I, Idx)) {
5035         Format = true;
5036         break;
5037       }
5038     }
5039   if (!Format || NumArgs <= Idx)
5040     return;
5041   const Expr *FormatExpr = Args[Idx];
5042   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
5043     FormatExpr = CSCE->getSubExpr();
5044   const StringLiteral *FormatString;
5045   if (const ObjCStringLiteral *OSL =
5046       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
5047     FormatString = OSL->getString();
5048   else
5049     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
5050   if (!FormatString)
5051     return;
5052   if (S.FormatStringHasSArg(FormatString)) {
5053     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
5054       << "%s" << 1 << 1;
5055     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
5056       << FDecl->getDeclName();
5057   }
5058 }
5059 
5060 /// Determine whether the given type has a non-null nullability annotation.
5061 static bool isNonNullType(ASTContext &ctx, QualType type) {
5062   if (auto nullability = type->getNullability(ctx))
5063     return *nullability == NullabilityKind::NonNull;
5064 
5065   return false;
5066 }
5067 
5068 static void CheckNonNullArguments(Sema &S,
5069                                   const NamedDecl *FDecl,
5070                                   const FunctionProtoType *Proto,
5071                                   ArrayRef<const Expr *> Args,
5072                                   SourceLocation CallSiteLoc) {
5073   assert((FDecl || Proto) && "Need a function declaration or prototype");
5074 
5075   // Already checked by by constant evaluator.
5076   if (S.isConstantEvaluated())
5077     return;
5078   // Check the attributes attached to the method/function itself.
5079   llvm::SmallBitVector NonNullArgs;
5080   if (FDecl) {
5081     // Handle the nonnull attribute on the function/method declaration itself.
5082     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
5083       if (!NonNull->args_size()) {
5084         // Easy case: all pointer arguments are nonnull.
5085         for (const auto *Arg : Args)
5086           if (S.isValidPointerAttrType(Arg->getType()))
5087             CheckNonNullArgument(S, Arg, CallSiteLoc);
5088         return;
5089       }
5090 
5091       for (const ParamIdx &Idx : NonNull->args()) {
5092         unsigned IdxAST = Idx.getASTIndex();
5093         if (IdxAST >= Args.size())
5094           continue;
5095         if (NonNullArgs.empty())
5096           NonNullArgs.resize(Args.size());
5097         NonNullArgs.set(IdxAST);
5098       }
5099     }
5100   }
5101 
5102   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
5103     // Handle the nonnull attribute on the parameters of the
5104     // function/method.
5105     ArrayRef<ParmVarDecl*> parms;
5106     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
5107       parms = FD->parameters();
5108     else
5109       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
5110 
5111     unsigned ParamIndex = 0;
5112     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
5113          I != E; ++I, ++ParamIndex) {
5114       const ParmVarDecl *PVD = *I;
5115       if (PVD->hasAttr<NonNullAttr>() ||
5116           isNonNullType(S.Context, PVD->getType())) {
5117         if (NonNullArgs.empty())
5118           NonNullArgs.resize(Args.size());
5119 
5120         NonNullArgs.set(ParamIndex);
5121       }
5122     }
5123   } else {
5124     // If we have a non-function, non-method declaration but no
5125     // function prototype, try to dig out the function prototype.
5126     if (!Proto) {
5127       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
5128         QualType type = VD->getType().getNonReferenceType();
5129         if (auto pointerType = type->getAs<PointerType>())
5130           type = pointerType->getPointeeType();
5131         else if (auto blockType = type->getAs<BlockPointerType>())
5132           type = blockType->getPointeeType();
5133         // FIXME: data member pointers?
5134 
5135         // Dig out the function prototype, if there is one.
5136         Proto = type->getAs<FunctionProtoType>();
5137       }
5138     }
5139 
5140     // Fill in non-null argument information from the nullability
5141     // information on the parameter types (if we have them).
5142     if (Proto) {
5143       unsigned Index = 0;
5144       for (auto paramType : Proto->getParamTypes()) {
5145         if (isNonNullType(S.Context, paramType)) {
5146           if (NonNullArgs.empty())
5147             NonNullArgs.resize(Args.size());
5148 
5149           NonNullArgs.set(Index);
5150         }
5151 
5152         ++Index;
5153       }
5154     }
5155   }
5156 
5157   // Check for non-null arguments.
5158   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
5159        ArgIndex != ArgIndexEnd; ++ArgIndex) {
5160     if (NonNullArgs[ArgIndex])
5161       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
5162   }
5163 }
5164 
5165 /// Warn if a pointer or reference argument passed to a function points to an
5166 /// object that is less aligned than the parameter. This can happen when
5167 /// creating a typedef with a lower alignment than the original type and then
5168 /// calling functions defined in terms of the original type.
5169 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
5170                              StringRef ParamName, QualType ArgTy,
5171                              QualType ParamTy) {
5172 
5173   // If a function accepts a pointer or reference type
5174   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
5175     return;
5176 
5177   // If the parameter is a pointer type, get the pointee type for the
5178   // argument too. If the parameter is a reference type, don't try to get
5179   // the pointee type for the argument.
5180   if (ParamTy->isPointerType())
5181     ArgTy = ArgTy->getPointeeType();
5182 
5183   // Remove reference or pointer
5184   ParamTy = ParamTy->getPointeeType();
5185 
5186   // Find expected alignment, and the actual alignment of the passed object.
5187   // getTypeAlignInChars requires complete types
5188   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
5189       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
5190       ArgTy->isUndeducedType())
5191     return;
5192 
5193   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
5194   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
5195 
5196   // If the argument is less aligned than the parameter, there is a
5197   // potential alignment issue.
5198   if (ArgAlign < ParamAlign)
5199     Diag(Loc, diag::warn_param_mismatched_alignment)
5200         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
5201         << ParamName << (FDecl != nullptr) << FDecl;
5202 }
5203 
5204 /// Handles the checks for format strings, non-POD arguments to vararg
5205 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
5206 /// attributes.
5207 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
5208                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
5209                      bool IsMemberFunction, SourceLocation Loc,
5210                      SourceRange Range, VariadicCallType CallType) {
5211   // FIXME: We should check as much as we can in the template definition.
5212   if (CurContext->isDependentContext())
5213     return;
5214 
5215   // Printf and scanf checking.
5216   llvm::SmallBitVector CheckedVarArgs;
5217   if (FDecl) {
5218     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5219       // Only create vector if there are format attributes.
5220       CheckedVarArgs.resize(Args.size());
5221 
5222       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
5223                            CheckedVarArgs);
5224     }
5225   }
5226 
5227   // Refuse POD arguments that weren't caught by the format string
5228   // checks above.
5229   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
5230   if (CallType != VariadicDoesNotApply &&
5231       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
5232     unsigned NumParams = Proto ? Proto->getNumParams()
5233                        : FDecl && isa<FunctionDecl>(FDecl)
5234                            ? cast<FunctionDecl>(FDecl)->getNumParams()
5235                        : FDecl && isa<ObjCMethodDecl>(FDecl)
5236                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
5237                        : 0;
5238 
5239     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
5240       // Args[ArgIdx] can be null in malformed code.
5241       if (const Expr *Arg = Args[ArgIdx]) {
5242         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
5243           checkVariadicArgument(Arg, CallType);
5244       }
5245     }
5246   }
5247 
5248   if (FDecl || Proto) {
5249     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
5250 
5251     // Type safety checking.
5252     if (FDecl) {
5253       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
5254         CheckArgumentWithTypeTag(I, Args, Loc);
5255     }
5256   }
5257 
5258   // Check that passed arguments match the alignment of original arguments.
5259   // Try to get the missing prototype from the declaration.
5260   if (!Proto && FDecl) {
5261     const auto *FT = FDecl->getFunctionType();
5262     if (isa_and_nonnull<FunctionProtoType>(FT))
5263       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
5264   }
5265   if (Proto) {
5266     // For variadic functions, we may have more args than parameters.
5267     // For some K&R functions, we may have less args than parameters.
5268     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
5269     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
5270       // Args[ArgIdx] can be null in malformed code.
5271       if (const Expr *Arg = Args[ArgIdx]) {
5272         if (Arg->containsErrors())
5273           continue;
5274 
5275         QualType ParamTy = Proto->getParamType(ArgIdx);
5276         QualType ArgTy = Arg->getType();
5277         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
5278                           ArgTy, ParamTy);
5279       }
5280     }
5281   }
5282 
5283   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
5284     auto *AA = FDecl->getAttr<AllocAlignAttr>();
5285     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
5286     if (!Arg->isValueDependent()) {
5287       Expr::EvalResult Align;
5288       if (Arg->EvaluateAsInt(Align, Context)) {
5289         const llvm::APSInt &I = Align.Val.getInt();
5290         if (!I.isPowerOf2())
5291           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
5292               << Arg->getSourceRange();
5293 
5294         if (I > Sema::MaximumAlignment)
5295           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
5296               << Arg->getSourceRange() << Sema::MaximumAlignment;
5297       }
5298     }
5299   }
5300 
5301   if (FD)
5302     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
5303 }
5304 
5305 /// CheckConstructorCall - Check a constructor call for correctness and safety
5306 /// properties not enforced by the C type system.
5307 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5308                                 ArrayRef<const Expr *> Args,
5309                                 const FunctionProtoType *Proto,
5310                                 SourceLocation Loc) {
5311   VariadicCallType CallType =
5312       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5313 
5314   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5315   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5316                     Context.getPointerType(Ctor->getThisObjectType()));
5317 
5318   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5319             Loc, SourceRange(), CallType);
5320 }
5321 
5322 /// CheckFunctionCall - Check a direct function call for various correctness
5323 /// and safety properties not strictly enforced by the C type system.
5324 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5325                              const FunctionProtoType *Proto) {
5326   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5327                               isa<CXXMethodDecl>(FDecl);
5328   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5329                           IsMemberOperatorCall;
5330   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5331                                                   TheCall->getCallee());
5332   Expr** Args = TheCall->getArgs();
5333   unsigned NumArgs = TheCall->getNumArgs();
5334 
5335   Expr *ImplicitThis = nullptr;
5336   if (IsMemberOperatorCall) {
5337     // If this is a call to a member operator, hide the first argument
5338     // from checkCall.
5339     // FIXME: Our choice of AST representation here is less than ideal.
5340     ImplicitThis = Args[0];
5341     ++Args;
5342     --NumArgs;
5343   } else if (IsMemberFunction)
5344     ImplicitThis =
5345         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5346 
5347   if (ImplicitThis) {
5348     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5349     // used.
5350     QualType ThisType = ImplicitThis->getType();
5351     if (!ThisType->isPointerType()) {
5352       assert(!ThisType->isReferenceType());
5353       ThisType = Context.getPointerType(ThisType);
5354     }
5355 
5356     QualType ThisTypeFromDecl =
5357         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5358 
5359     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5360                       ThisTypeFromDecl);
5361   }
5362 
5363   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5364             IsMemberFunction, TheCall->getRParenLoc(),
5365             TheCall->getCallee()->getSourceRange(), CallType);
5366 
5367   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5368   // None of the checks below are needed for functions that don't have
5369   // simple names (e.g., C++ conversion functions).
5370   if (!FnInfo)
5371     return false;
5372 
5373   CheckTCBEnforcement(TheCall, FDecl);
5374 
5375   CheckAbsoluteValueFunction(TheCall, FDecl);
5376   CheckMaxUnsignedZero(TheCall, FDecl);
5377 
5378   if (getLangOpts().ObjC)
5379     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5380 
5381   unsigned CMId = FDecl->getMemoryFunctionKind();
5382 
5383   // Handle memory setting and copying functions.
5384   switch (CMId) {
5385   case 0:
5386     return false;
5387   case Builtin::BIstrlcpy: // fallthrough
5388   case Builtin::BIstrlcat:
5389     CheckStrlcpycatArguments(TheCall, FnInfo);
5390     break;
5391   case Builtin::BIstrncat:
5392     CheckStrncatArguments(TheCall, FnInfo);
5393     break;
5394   case Builtin::BIfree:
5395     CheckFreeArguments(TheCall);
5396     break;
5397   default:
5398     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5399   }
5400 
5401   return false;
5402 }
5403 
5404 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5405                                ArrayRef<const Expr *> Args) {
5406   VariadicCallType CallType =
5407       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5408 
5409   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5410             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5411             CallType);
5412 
5413   return false;
5414 }
5415 
5416 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5417                             const FunctionProtoType *Proto) {
5418   QualType Ty;
5419   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5420     Ty = V->getType().getNonReferenceType();
5421   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5422     Ty = F->getType().getNonReferenceType();
5423   else
5424     return false;
5425 
5426   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5427       !Ty->isFunctionProtoType())
5428     return false;
5429 
5430   VariadicCallType CallType;
5431   if (!Proto || !Proto->isVariadic()) {
5432     CallType = VariadicDoesNotApply;
5433   } else if (Ty->isBlockPointerType()) {
5434     CallType = VariadicBlock;
5435   } else { // Ty->isFunctionPointerType()
5436     CallType = VariadicFunction;
5437   }
5438 
5439   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5440             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5441             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5442             TheCall->getCallee()->getSourceRange(), CallType);
5443 
5444   return false;
5445 }
5446 
5447 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5448 /// such as function pointers returned from functions.
5449 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5450   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5451                                                   TheCall->getCallee());
5452   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5453             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5454             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5455             TheCall->getCallee()->getSourceRange(), CallType);
5456 
5457   return false;
5458 }
5459 
5460 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5461   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5462     return false;
5463 
5464   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5465   switch (Op) {
5466   case AtomicExpr::AO__c11_atomic_init:
5467   case AtomicExpr::AO__opencl_atomic_init:
5468     llvm_unreachable("There is no ordering argument for an init");
5469 
5470   case AtomicExpr::AO__c11_atomic_load:
5471   case AtomicExpr::AO__opencl_atomic_load:
5472   case AtomicExpr::AO__hip_atomic_load:
5473   case AtomicExpr::AO__atomic_load_n:
5474   case AtomicExpr::AO__atomic_load:
5475     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5476            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5477 
5478   case AtomicExpr::AO__c11_atomic_store:
5479   case AtomicExpr::AO__opencl_atomic_store:
5480   case AtomicExpr::AO__hip_atomic_store:
5481   case AtomicExpr::AO__atomic_store:
5482   case AtomicExpr::AO__atomic_store_n:
5483     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5484            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5485            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5486 
5487   default:
5488     return true;
5489   }
5490 }
5491 
5492 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5493                                          AtomicExpr::AtomicOp Op) {
5494   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5495   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5496   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5497   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5498                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5499                          Op);
5500 }
5501 
5502 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5503                                  SourceLocation RParenLoc, MultiExprArg Args,
5504                                  AtomicExpr::AtomicOp Op,
5505                                  AtomicArgumentOrder ArgOrder) {
5506   // All the non-OpenCL operations take one of the following forms.
5507   // The OpenCL operations take the __c11 forms with one extra argument for
5508   // synchronization scope.
5509   enum {
5510     // C    __c11_atomic_init(A *, C)
5511     Init,
5512 
5513     // C    __c11_atomic_load(A *, int)
5514     Load,
5515 
5516     // void __atomic_load(A *, CP, int)
5517     LoadCopy,
5518 
5519     // void __atomic_store(A *, CP, int)
5520     Copy,
5521 
5522     // C    __c11_atomic_add(A *, M, int)
5523     Arithmetic,
5524 
5525     // C    __atomic_exchange_n(A *, CP, int)
5526     Xchg,
5527 
5528     // void __atomic_exchange(A *, C *, CP, int)
5529     GNUXchg,
5530 
5531     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5532     C11CmpXchg,
5533 
5534     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5535     GNUCmpXchg
5536   } Form = Init;
5537 
5538   const unsigned NumForm = GNUCmpXchg + 1;
5539   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5540   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5541   // where:
5542   //   C is an appropriate type,
5543   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5544   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5545   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5546   //   the int parameters are for orderings.
5547 
5548   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5549       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5550       "need to update code for modified forms");
5551   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5552                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5553                         AtomicExpr::AO__atomic_load,
5554                 "need to update code for modified C11 atomics");
5555   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5556                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5557   bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load &&
5558                Op <= AtomicExpr::AO__hip_atomic_fetch_max;
5559   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5560                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5561                IsOpenCL;
5562   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5563              Op == AtomicExpr::AO__atomic_store_n ||
5564              Op == AtomicExpr::AO__atomic_exchange_n ||
5565              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5566   bool IsAddSub = false;
5567 
5568   switch (Op) {
5569   case AtomicExpr::AO__c11_atomic_init:
5570   case AtomicExpr::AO__opencl_atomic_init:
5571     Form = Init;
5572     break;
5573 
5574   case AtomicExpr::AO__c11_atomic_load:
5575   case AtomicExpr::AO__opencl_atomic_load:
5576   case AtomicExpr::AO__hip_atomic_load:
5577   case AtomicExpr::AO__atomic_load_n:
5578     Form = Load;
5579     break;
5580 
5581   case AtomicExpr::AO__atomic_load:
5582     Form = LoadCopy;
5583     break;
5584 
5585   case AtomicExpr::AO__c11_atomic_store:
5586   case AtomicExpr::AO__opencl_atomic_store:
5587   case AtomicExpr::AO__hip_atomic_store:
5588   case AtomicExpr::AO__atomic_store:
5589   case AtomicExpr::AO__atomic_store_n:
5590     Form = Copy;
5591     break;
5592   case AtomicExpr::AO__hip_atomic_fetch_add:
5593   case AtomicExpr::AO__hip_atomic_fetch_min:
5594   case AtomicExpr::AO__hip_atomic_fetch_max:
5595   case AtomicExpr::AO__c11_atomic_fetch_add:
5596   case AtomicExpr::AO__c11_atomic_fetch_sub:
5597   case AtomicExpr::AO__opencl_atomic_fetch_add:
5598   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5599   case AtomicExpr::AO__atomic_fetch_add:
5600   case AtomicExpr::AO__atomic_fetch_sub:
5601   case AtomicExpr::AO__atomic_add_fetch:
5602   case AtomicExpr::AO__atomic_sub_fetch:
5603     IsAddSub = true;
5604     Form = Arithmetic;
5605     break;
5606   case AtomicExpr::AO__c11_atomic_fetch_and:
5607   case AtomicExpr::AO__c11_atomic_fetch_or:
5608   case AtomicExpr::AO__c11_atomic_fetch_xor:
5609   case AtomicExpr::AO__hip_atomic_fetch_and:
5610   case AtomicExpr::AO__hip_atomic_fetch_or:
5611   case AtomicExpr::AO__hip_atomic_fetch_xor:
5612   case AtomicExpr::AO__c11_atomic_fetch_nand:
5613   case AtomicExpr::AO__opencl_atomic_fetch_and:
5614   case AtomicExpr::AO__opencl_atomic_fetch_or:
5615   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5616   case AtomicExpr::AO__atomic_fetch_and:
5617   case AtomicExpr::AO__atomic_fetch_or:
5618   case AtomicExpr::AO__atomic_fetch_xor:
5619   case AtomicExpr::AO__atomic_fetch_nand:
5620   case AtomicExpr::AO__atomic_and_fetch:
5621   case AtomicExpr::AO__atomic_or_fetch:
5622   case AtomicExpr::AO__atomic_xor_fetch:
5623   case AtomicExpr::AO__atomic_nand_fetch:
5624     Form = Arithmetic;
5625     break;
5626   case AtomicExpr::AO__c11_atomic_fetch_min:
5627   case AtomicExpr::AO__c11_atomic_fetch_max:
5628   case AtomicExpr::AO__opencl_atomic_fetch_min:
5629   case AtomicExpr::AO__opencl_atomic_fetch_max:
5630   case AtomicExpr::AO__atomic_min_fetch:
5631   case AtomicExpr::AO__atomic_max_fetch:
5632   case AtomicExpr::AO__atomic_fetch_min:
5633   case AtomicExpr::AO__atomic_fetch_max:
5634     Form = Arithmetic;
5635     break;
5636 
5637   case AtomicExpr::AO__c11_atomic_exchange:
5638   case AtomicExpr::AO__hip_atomic_exchange:
5639   case AtomicExpr::AO__opencl_atomic_exchange:
5640   case AtomicExpr::AO__atomic_exchange_n:
5641     Form = Xchg;
5642     break;
5643 
5644   case AtomicExpr::AO__atomic_exchange:
5645     Form = GNUXchg;
5646     break;
5647 
5648   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5649   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5650   case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5651   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5652   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5653   case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5654     Form = C11CmpXchg;
5655     break;
5656 
5657   case AtomicExpr::AO__atomic_compare_exchange:
5658   case AtomicExpr::AO__atomic_compare_exchange_n:
5659     Form = GNUCmpXchg;
5660     break;
5661   }
5662 
5663   unsigned AdjustedNumArgs = NumArgs[Form];
5664   if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init)
5665     ++AdjustedNumArgs;
5666   // Check we have the right number of arguments.
5667   if (Args.size() < AdjustedNumArgs) {
5668     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5669         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5670         << ExprRange;
5671     return ExprError();
5672   } else if (Args.size() > AdjustedNumArgs) {
5673     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5674          diag::err_typecheck_call_too_many_args)
5675         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5676         << ExprRange;
5677     return ExprError();
5678   }
5679 
5680   // Inspect the first argument of the atomic operation.
5681   Expr *Ptr = Args[0];
5682   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5683   if (ConvertedPtr.isInvalid())
5684     return ExprError();
5685 
5686   Ptr = ConvertedPtr.get();
5687   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5688   if (!pointerType) {
5689     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5690         << Ptr->getType() << Ptr->getSourceRange();
5691     return ExprError();
5692   }
5693 
5694   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5695   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5696   QualType ValType = AtomTy; // 'C'
5697   if (IsC11) {
5698     if (!AtomTy->isAtomicType()) {
5699       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5700           << Ptr->getType() << Ptr->getSourceRange();
5701       return ExprError();
5702     }
5703     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5704         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5705       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5706           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5707           << Ptr->getSourceRange();
5708       return ExprError();
5709     }
5710     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5711   } else if (Form != Load && Form != LoadCopy) {
5712     if (ValType.isConstQualified()) {
5713       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5714           << Ptr->getType() << Ptr->getSourceRange();
5715       return ExprError();
5716     }
5717   }
5718 
5719   // For an arithmetic operation, the implied arithmetic must be well-formed.
5720   if (Form == Arithmetic) {
5721     // GCC does not enforce these rules for GNU atomics, but we do to help catch
5722     // trivial type errors.
5723     auto IsAllowedValueType = [&](QualType ValType) {
5724       if (ValType->isIntegerType())
5725         return true;
5726       if (ValType->isPointerType())
5727         return true;
5728       if (!ValType->isFloatingType())
5729         return false;
5730       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5731       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5732           &Context.getTargetInfo().getLongDoubleFormat() ==
5733               &llvm::APFloat::x87DoubleExtended())
5734         return false;
5735       return true;
5736     };
5737     if (IsAddSub && !IsAllowedValueType(ValType)) {
5738       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5739           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5740       return ExprError();
5741     }
5742     if (!IsAddSub && !ValType->isIntegerType()) {
5743       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5744           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5745       return ExprError();
5746     }
5747     if (IsC11 && ValType->isPointerType() &&
5748         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5749                             diag::err_incomplete_type)) {
5750       return ExprError();
5751     }
5752   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5753     // For __atomic_*_n operations, the value type must be a scalar integral or
5754     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5755     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5756         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5757     return ExprError();
5758   }
5759 
5760   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5761       !AtomTy->isScalarType()) {
5762     // For GNU atomics, require a trivially-copyable type. This is not part of
5763     // the GNU atomics specification but we enforce it for consistency with
5764     // other atomics which generally all require a trivially-copyable type. This
5765     // is because atomics just copy bits.
5766     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5767         << Ptr->getType() << Ptr->getSourceRange();
5768     return ExprError();
5769   }
5770 
5771   switch (ValType.getObjCLifetime()) {
5772   case Qualifiers::OCL_None:
5773   case Qualifiers::OCL_ExplicitNone:
5774     // okay
5775     break;
5776 
5777   case Qualifiers::OCL_Weak:
5778   case Qualifiers::OCL_Strong:
5779   case Qualifiers::OCL_Autoreleasing:
5780     // FIXME: Can this happen? By this point, ValType should be known
5781     // to be trivially copyable.
5782     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5783         << ValType << Ptr->getSourceRange();
5784     return ExprError();
5785   }
5786 
5787   // All atomic operations have an overload which takes a pointer to a volatile
5788   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5789   // into the result or the other operands. Similarly atomic_load takes a
5790   // pointer to a const 'A'.
5791   ValType.removeLocalVolatile();
5792   ValType.removeLocalConst();
5793   QualType ResultType = ValType;
5794   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5795       Form == Init)
5796     ResultType = Context.VoidTy;
5797   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5798     ResultType = Context.BoolTy;
5799 
5800   // The type of a parameter passed 'by value'. In the GNU atomics, such
5801   // arguments are actually passed as pointers.
5802   QualType ByValType = ValType; // 'CP'
5803   bool IsPassedByAddress = false;
5804   if (!IsC11 && !IsHIP && !IsN) {
5805     ByValType = Ptr->getType();
5806     IsPassedByAddress = true;
5807   }
5808 
5809   SmallVector<Expr *, 5> APIOrderedArgs;
5810   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5811     APIOrderedArgs.push_back(Args[0]);
5812     switch (Form) {
5813     case Init:
5814     case Load:
5815       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5816       break;
5817     case LoadCopy:
5818     case Copy:
5819     case Arithmetic:
5820     case Xchg:
5821       APIOrderedArgs.push_back(Args[2]); // Val1
5822       APIOrderedArgs.push_back(Args[1]); // Order
5823       break;
5824     case GNUXchg:
5825       APIOrderedArgs.push_back(Args[2]); // Val1
5826       APIOrderedArgs.push_back(Args[3]); // Val2
5827       APIOrderedArgs.push_back(Args[1]); // Order
5828       break;
5829     case C11CmpXchg:
5830       APIOrderedArgs.push_back(Args[2]); // Val1
5831       APIOrderedArgs.push_back(Args[4]); // Val2
5832       APIOrderedArgs.push_back(Args[1]); // Order
5833       APIOrderedArgs.push_back(Args[3]); // OrderFail
5834       break;
5835     case GNUCmpXchg:
5836       APIOrderedArgs.push_back(Args[2]); // Val1
5837       APIOrderedArgs.push_back(Args[4]); // Val2
5838       APIOrderedArgs.push_back(Args[5]); // Weak
5839       APIOrderedArgs.push_back(Args[1]); // Order
5840       APIOrderedArgs.push_back(Args[3]); // OrderFail
5841       break;
5842     }
5843   } else
5844     APIOrderedArgs.append(Args.begin(), Args.end());
5845 
5846   // The first argument's non-CV pointer type is used to deduce the type of
5847   // subsequent arguments, except for:
5848   //  - weak flag (always converted to bool)
5849   //  - memory order (always converted to int)
5850   //  - scope  (always converted to int)
5851   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5852     QualType Ty;
5853     if (i < NumVals[Form] + 1) {
5854       switch (i) {
5855       case 0:
5856         // The first argument is always a pointer. It has a fixed type.
5857         // It is always dereferenced, a nullptr is undefined.
5858         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5859         // Nothing else to do: we already know all we want about this pointer.
5860         continue;
5861       case 1:
5862         // The second argument is the non-atomic operand. For arithmetic, this
5863         // is always passed by value, and for a compare_exchange it is always
5864         // passed by address. For the rest, GNU uses by-address and C11 uses
5865         // by-value.
5866         assert(Form != Load);
5867         if (Form == Arithmetic && ValType->isPointerType())
5868           Ty = Context.getPointerDiffType();
5869         else if (Form == Init || Form == Arithmetic)
5870           Ty = ValType;
5871         else if (Form == Copy || Form == Xchg) {
5872           if (IsPassedByAddress) {
5873             // The value pointer is always dereferenced, a nullptr is undefined.
5874             CheckNonNullArgument(*this, APIOrderedArgs[i],
5875                                  ExprRange.getBegin());
5876           }
5877           Ty = ByValType;
5878         } else {
5879           Expr *ValArg = APIOrderedArgs[i];
5880           // The value pointer is always dereferenced, a nullptr is undefined.
5881           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5882           LangAS AS = LangAS::Default;
5883           // Keep address space of non-atomic pointer type.
5884           if (const PointerType *PtrTy =
5885                   ValArg->getType()->getAs<PointerType>()) {
5886             AS = PtrTy->getPointeeType().getAddressSpace();
5887           }
5888           Ty = Context.getPointerType(
5889               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5890         }
5891         break;
5892       case 2:
5893         // The third argument to compare_exchange / GNU exchange is the desired
5894         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5895         if (IsPassedByAddress)
5896           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5897         Ty = ByValType;
5898         break;
5899       case 3:
5900         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5901         Ty = Context.BoolTy;
5902         break;
5903       }
5904     } else {
5905       // The order(s) and scope are always converted to int.
5906       Ty = Context.IntTy;
5907     }
5908 
5909     InitializedEntity Entity =
5910         InitializedEntity::InitializeParameter(Context, Ty, false);
5911     ExprResult Arg = APIOrderedArgs[i];
5912     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5913     if (Arg.isInvalid())
5914       return true;
5915     APIOrderedArgs[i] = Arg.get();
5916   }
5917 
5918   // Permute the arguments into a 'consistent' order.
5919   SmallVector<Expr*, 5> SubExprs;
5920   SubExprs.push_back(Ptr);
5921   switch (Form) {
5922   case Init:
5923     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5924     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5925     break;
5926   case Load:
5927     SubExprs.push_back(APIOrderedArgs[1]); // Order
5928     break;
5929   case LoadCopy:
5930   case Copy:
5931   case Arithmetic:
5932   case Xchg:
5933     SubExprs.push_back(APIOrderedArgs[2]); // Order
5934     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5935     break;
5936   case GNUXchg:
5937     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5938     SubExprs.push_back(APIOrderedArgs[3]); // Order
5939     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5940     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5941     break;
5942   case C11CmpXchg:
5943     SubExprs.push_back(APIOrderedArgs[3]); // Order
5944     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5945     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5946     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5947     break;
5948   case GNUCmpXchg:
5949     SubExprs.push_back(APIOrderedArgs[4]); // Order
5950     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5951     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5952     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5953     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5954     break;
5955   }
5956 
5957   if (SubExprs.size() >= 2 && Form != Init) {
5958     if (Optional<llvm::APSInt> Result =
5959             SubExprs[1]->getIntegerConstantExpr(Context))
5960       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5961         Diag(SubExprs[1]->getBeginLoc(),
5962              diag::warn_atomic_op_has_invalid_memory_order)
5963             << SubExprs[1]->getSourceRange();
5964   }
5965 
5966   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5967     auto *Scope = Args[Args.size() - 1];
5968     if (Optional<llvm::APSInt> Result =
5969             Scope->getIntegerConstantExpr(Context)) {
5970       if (!ScopeModel->isValid(Result->getZExtValue()))
5971         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5972             << Scope->getSourceRange();
5973     }
5974     SubExprs.push_back(Scope);
5975   }
5976 
5977   AtomicExpr *AE = new (Context)
5978       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5979 
5980   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5981        Op == AtomicExpr::AO__c11_atomic_store ||
5982        Op == AtomicExpr::AO__opencl_atomic_load ||
5983        Op == AtomicExpr::AO__hip_atomic_load ||
5984        Op == AtomicExpr::AO__opencl_atomic_store ||
5985        Op == AtomicExpr::AO__hip_atomic_store) &&
5986       Context.AtomicUsesUnsupportedLibcall(AE))
5987     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5988         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5989              Op == AtomicExpr::AO__opencl_atomic_load ||
5990              Op == AtomicExpr::AO__hip_atomic_load)
5991                 ? 0
5992                 : 1);
5993 
5994   if (ValType->isBitIntType()) {
5995     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
5996     return ExprError();
5997   }
5998 
5999   return AE;
6000 }
6001 
6002 /// checkBuiltinArgument - Given a call to a builtin function, perform
6003 /// normal type-checking on the given argument, updating the call in
6004 /// place.  This is useful when a builtin function requires custom
6005 /// type-checking for some of its arguments but not necessarily all of
6006 /// them.
6007 ///
6008 /// Returns true on error.
6009 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
6010   FunctionDecl *Fn = E->getDirectCallee();
6011   assert(Fn && "builtin call without direct callee!");
6012 
6013   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
6014   InitializedEntity Entity =
6015     InitializedEntity::InitializeParameter(S.Context, Param);
6016 
6017   ExprResult Arg = E->getArg(0);
6018   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
6019   if (Arg.isInvalid())
6020     return true;
6021 
6022   E->setArg(ArgIndex, Arg.get());
6023   return false;
6024 }
6025 
6026 /// We have a call to a function like __sync_fetch_and_add, which is an
6027 /// overloaded function based on the pointer type of its first argument.
6028 /// The main BuildCallExpr routines have already promoted the types of
6029 /// arguments because all of these calls are prototyped as void(...).
6030 ///
6031 /// This function goes through and does final semantic checking for these
6032 /// builtins, as well as generating any warnings.
6033 ExprResult
6034 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
6035   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
6036   Expr *Callee = TheCall->getCallee();
6037   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
6038   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6039 
6040   // Ensure that we have at least one argument to do type inference from.
6041   if (TheCall->getNumArgs() < 1) {
6042     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6043         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
6044     return ExprError();
6045   }
6046 
6047   // Inspect the first argument of the atomic builtin.  This should always be
6048   // a pointer type, whose element is an integral scalar or pointer type.
6049   // Because it is a pointer type, we don't have to worry about any implicit
6050   // casts here.
6051   // FIXME: We don't allow floating point scalars as input.
6052   Expr *FirstArg = TheCall->getArg(0);
6053   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
6054   if (FirstArgResult.isInvalid())
6055     return ExprError();
6056   FirstArg = FirstArgResult.get();
6057   TheCall->setArg(0, FirstArg);
6058 
6059   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
6060   if (!pointerType) {
6061     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
6062         << FirstArg->getType() << FirstArg->getSourceRange();
6063     return ExprError();
6064   }
6065 
6066   QualType ValType = pointerType->getPointeeType();
6067   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6068       !ValType->isBlockPointerType()) {
6069     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
6070         << FirstArg->getType() << FirstArg->getSourceRange();
6071     return ExprError();
6072   }
6073 
6074   if (ValType.isConstQualified()) {
6075     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
6076         << FirstArg->getType() << FirstArg->getSourceRange();
6077     return ExprError();
6078   }
6079 
6080   switch (ValType.getObjCLifetime()) {
6081   case Qualifiers::OCL_None:
6082   case Qualifiers::OCL_ExplicitNone:
6083     // okay
6084     break;
6085 
6086   case Qualifiers::OCL_Weak:
6087   case Qualifiers::OCL_Strong:
6088   case Qualifiers::OCL_Autoreleasing:
6089     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
6090         << ValType << FirstArg->getSourceRange();
6091     return ExprError();
6092   }
6093 
6094   // Strip any qualifiers off ValType.
6095   ValType = ValType.getUnqualifiedType();
6096 
6097   // The majority of builtins return a value, but a few have special return
6098   // types, so allow them to override appropriately below.
6099   QualType ResultType = ValType;
6100 
6101   // We need to figure out which concrete builtin this maps onto.  For example,
6102   // __sync_fetch_and_add with a 2 byte object turns into
6103   // __sync_fetch_and_add_2.
6104 #define BUILTIN_ROW(x) \
6105   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
6106     Builtin::BI##x##_8, Builtin::BI##x##_16 }
6107 
6108   static const unsigned BuiltinIndices[][5] = {
6109     BUILTIN_ROW(__sync_fetch_and_add),
6110     BUILTIN_ROW(__sync_fetch_and_sub),
6111     BUILTIN_ROW(__sync_fetch_and_or),
6112     BUILTIN_ROW(__sync_fetch_and_and),
6113     BUILTIN_ROW(__sync_fetch_and_xor),
6114     BUILTIN_ROW(__sync_fetch_and_nand),
6115 
6116     BUILTIN_ROW(__sync_add_and_fetch),
6117     BUILTIN_ROW(__sync_sub_and_fetch),
6118     BUILTIN_ROW(__sync_and_and_fetch),
6119     BUILTIN_ROW(__sync_or_and_fetch),
6120     BUILTIN_ROW(__sync_xor_and_fetch),
6121     BUILTIN_ROW(__sync_nand_and_fetch),
6122 
6123     BUILTIN_ROW(__sync_val_compare_and_swap),
6124     BUILTIN_ROW(__sync_bool_compare_and_swap),
6125     BUILTIN_ROW(__sync_lock_test_and_set),
6126     BUILTIN_ROW(__sync_lock_release),
6127     BUILTIN_ROW(__sync_swap)
6128   };
6129 #undef BUILTIN_ROW
6130 
6131   // Determine the index of the size.
6132   unsigned SizeIndex;
6133   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
6134   case 1: SizeIndex = 0; break;
6135   case 2: SizeIndex = 1; break;
6136   case 4: SizeIndex = 2; break;
6137   case 8: SizeIndex = 3; break;
6138   case 16: SizeIndex = 4; break;
6139   default:
6140     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
6141         << FirstArg->getType() << FirstArg->getSourceRange();
6142     return ExprError();
6143   }
6144 
6145   // Each of these builtins has one pointer argument, followed by some number of
6146   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
6147   // that we ignore.  Find out which row of BuiltinIndices to read from as well
6148   // as the number of fixed args.
6149   unsigned BuiltinID = FDecl->getBuiltinID();
6150   unsigned BuiltinIndex, NumFixed = 1;
6151   bool WarnAboutSemanticsChange = false;
6152   switch (BuiltinID) {
6153   default: llvm_unreachable("Unknown overloaded atomic builtin!");
6154   case Builtin::BI__sync_fetch_and_add:
6155   case Builtin::BI__sync_fetch_and_add_1:
6156   case Builtin::BI__sync_fetch_and_add_2:
6157   case Builtin::BI__sync_fetch_and_add_4:
6158   case Builtin::BI__sync_fetch_and_add_8:
6159   case Builtin::BI__sync_fetch_and_add_16:
6160     BuiltinIndex = 0;
6161     break;
6162 
6163   case Builtin::BI__sync_fetch_and_sub:
6164   case Builtin::BI__sync_fetch_and_sub_1:
6165   case Builtin::BI__sync_fetch_and_sub_2:
6166   case Builtin::BI__sync_fetch_and_sub_4:
6167   case Builtin::BI__sync_fetch_and_sub_8:
6168   case Builtin::BI__sync_fetch_and_sub_16:
6169     BuiltinIndex = 1;
6170     break;
6171 
6172   case Builtin::BI__sync_fetch_and_or:
6173   case Builtin::BI__sync_fetch_and_or_1:
6174   case Builtin::BI__sync_fetch_and_or_2:
6175   case Builtin::BI__sync_fetch_and_or_4:
6176   case Builtin::BI__sync_fetch_and_or_8:
6177   case Builtin::BI__sync_fetch_and_or_16:
6178     BuiltinIndex = 2;
6179     break;
6180 
6181   case Builtin::BI__sync_fetch_and_and:
6182   case Builtin::BI__sync_fetch_and_and_1:
6183   case Builtin::BI__sync_fetch_and_and_2:
6184   case Builtin::BI__sync_fetch_and_and_4:
6185   case Builtin::BI__sync_fetch_and_and_8:
6186   case Builtin::BI__sync_fetch_and_and_16:
6187     BuiltinIndex = 3;
6188     break;
6189 
6190   case Builtin::BI__sync_fetch_and_xor:
6191   case Builtin::BI__sync_fetch_and_xor_1:
6192   case Builtin::BI__sync_fetch_and_xor_2:
6193   case Builtin::BI__sync_fetch_and_xor_4:
6194   case Builtin::BI__sync_fetch_and_xor_8:
6195   case Builtin::BI__sync_fetch_and_xor_16:
6196     BuiltinIndex = 4;
6197     break;
6198 
6199   case Builtin::BI__sync_fetch_and_nand:
6200   case Builtin::BI__sync_fetch_and_nand_1:
6201   case Builtin::BI__sync_fetch_and_nand_2:
6202   case Builtin::BI__sync_fetch_and_nand_4:
6203   case Builtin::BI__sync_fetch_and_nand_8:
6204   case Builtin::BI__sync_fetch_and_nand_16:
6205     BuiltinIndex = 5;
6206     WarnAboutSemanticsChange = true;
6207     break;
6208 
6209   case Builtin::BI__sync_add_and_fetch:
6210   case Builtin::BI__sync_add_and_fetch_1:
6211   case Builtin::BI__sync_add_and_fetch_2:
6212   case Builtin::BI__sync_add_and_fetch_4:
6213   case Builtin::BI__sync_add_and_fetch_8:
6214   case Builtin::BI__sync_add_and_fetch_16:
6215     BuiltinIndex = 6;
6216     break;
6217 
6218   case Builtin::BI__sync_sub_and_fetch:
6219   case Builtin::BI__sync_sub_and_fetch_1:
6220   case Builtin::BI__sync_sub_and_fetch_2:
6221   case Builtin::BI__sync_sub_and_fetch_4:
6222   case Builtin::BI__sync_sub_and_fetch_8:
6223   case Builtin::BI__sync_sub_and_fetch_16:
6224     BuiltinIndex = 7;
6225     break;
6226 
6227   case Builtin::BI__sync_and_and_fetch:
6228   case Builtin::BI__sync_and_and_fetch_1:
6229   case Builtin::BI__sync_and_and_fetch_2:
6230   case Builtin::BI__sync_and_and_fetch_4:
6231   case Builtin::BI__sync_and_and_fetch_8:
6232   case Builtin::BI__sync_and_and_fetch_16:
6233     BuiltinIndex = 8;
6234     break;
6235 
6236   case Builtin::BI__sync_or_and_fetch:
6237   case Builtin::BI__sync_or_and_fetch_1:
6238   case Builtin::BI__sync_or_and_fetch_2:
6239   case Builtin::BI__sync_or_and_fetch_4:
6240   case Builtin::BI__sync_or_and_fetch_8:
6241   case Builtin::BI__sync_or_and_fetch_16:
6242     BuiltinIndex = 9;
6243     break;
6244 
6245   case Builtin::BI__sync_xor_and_fetch:
6246   case Builtin::BI__sync_xor_and_fetch_1:
6247   case Builtin::BI__sync_xor_and_fetch_2:
6248   case Builtin::BI__sync_xor_and_fetch_4:
6249   case Builtin::BI__sync_xor_and_fetch_8:
6250   case Builtin::BI__sync_xor_and_fetch_16:
6251     BuiltinIndex = 10;
6252     break;
6253 
6254   case Builtin::BI__sync_nand_and_fetch:
6255   case Builtin::BI__sync_nand_and_fetch_1:
6256   case Builtin::BI__sync_nand_and_fetch_2:
6257   case Builtin::BI__sync_nand_and_fetch_4:
6258   case Builtin::BI__sync_nand_and_fetch_8:
6259   case Builtin::BI__sync_nand_and_fetch_16:
6260     BuiltinIndex = 11;
6261     WarnAboutSemanticsChange = true;
6262     break;
6263 
6264   case Builtin::BI__sync_val_compare_and_swap:
6265   case Builtin::BI__sync_val_compare_and_swap_1:
6266   case Builtin::BI__sync_val_compare_and_swap_2:
6267   case Builtin::BI__sync_val_compare_and_swap_4:
6268   case Builtin::BI__sync_val_compare_and_swap_8:
6269   case Builtin::BI__sync_val_compare_and_swap_16:
6270     BuiltinIndex = 12;
6271     NumFixed = 2;
6272     break;
6273 
6274   case Builtin::BI__sync_bool_compare_and_swap:
6275   case Builtin::BI__sync_bool_compare_and_swap_1:
6276   case Builtin::BI__sync_bool_compare_and_swap_2:
6277   case Builtin::BI__sync_bool_compare_and_swap_4:
6278   case Builtin::BI__sync_bool_compare_and_swap_8:
6279   case Builtin::BI__sync_bool_compare_and_swap_16:
6280     BuiltinIndex = 13;
6281     NumFixed = 2;
6282     ResultType = Context.BoolTy;
6283     break;
6284 
6285   case Builtin::BI__sync_lock_test_and_set:
6286   case Builtin::BI__sync_lock_test_and_set_1:
6287   case Builtin::BI__sync_lock_test_and_set_2:
6288   case Builtin::BI__sync_lock_test_and_set_4:
6289   case Builtin::BI__sync_lock_test_and_set_8:
6290   case Builtin::BI__sync_lock_test_and_set_16:
6291     BuiltinIndex = 14;
6292     break;
6293 
6294   case Builtin::BI__sync_lock_release:
6295   case Builtin::BI__sync_lock_release_1:
6296   case Builtin::BI__sync_lock_release_2:
6297   case Builtin::BI__sync_lock_release_4:
6298   case Builtin::BI__sync_lock_release_8:
6299   case Builtin::BI__sync_lock_release_16:
6300     BuiltinIndex = 15;
6301     NumFixed = 0;
6302     ResultType = Context.VoidTy;
6303     break;
6304 
6305   case Builtin::BI__sync_swap:
6306   case Builtin::BI__sync_swap_1:
6307   case Builtin::BI__sync_swap_2:
6308   case Builtin::BI__sync_swap_4:
6309   case Builtin::BI__sync_swap_8:
6310   case Builtin::BI__sync_swap_16:
6311     BuiltinIndex = 16;
6312     break;
6313   }
6314 
6315   // Now that we know how many fixed arguments we expect, first check that we
6316   // have at least that many.
6317   if (TheCall->getNumArgs() < 1+NumFixed) {
6318     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6319         << 0 << 1 + NumFixed << TheCall->getNumArgs()
6320         << Callee->getSourceRange();
6321     return ExprError();
6322   }
6323 
6324   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6325       << Callee->getSourceRange();
6326 
6327   if (WarnAboutSemanticsChange) {
6328     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6329         << Callee->getSourceRange();
6330   }
6331 
6332   // Get the decl for the concrete builtin from this, we can tell what the
6333   // concrete integer type we should convert to is.
6334   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6335   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6336   FunctionDecl *NewBuiltinDecl;
6337   if (NewBuiltinID == BuiltinID)
6338     NewBuiltinDecl = FDecl;
6339   else {
6340     // Perform builtin lookup to avoid redeclaring it.
6341     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6342     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6343     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6344     assert(Res.getFoundDecl());
6345     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6346     if (!NewBuiltinDecl)
6347       return ExprError();
6348   }
6349 
6350   // The first argument --- the pointer --- has a fixed type; we
6351   // deduce the types of the rest of the arguments accordingly.  Walk
6352   // the remaining arguments, converting them to the deduced value type.
6353   for (unsigned i = 0; i != NumFixed; ++i) {
6354     ExprResult Arg = TheCall->getArg(i+1);
6355 
6356     // GCC does an implicit conversion to the pointer or integer ValType.  This
6357     // can fail in some cases (1i -> int**), check for this error case now.
6358     // Initialize the argument.
6359     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6360                                                    ValType, /*consume*/ false);
6361     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6362     if (Arg.isInvalid())
6363       return ExprError();
6364 
6365     // Okay, we have something that *can* be converted to the right type.  Check
6366     // to see if there is a potentially weird extension going on here.  This can
6367     // happen when you do an atomic operation on something like an char* and
6368     // pass in 42.  The 42 gets converted to char.  This is even more strange
6369     // for things like 45.123 -> char, etc.
6370     // FIXME: Do this check.
6371     TheCall->setArg(i+1, Arg.get());
6372   }
6373 
6374   // Create a new DeclRefExpr to refer to the new decl.
6375   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6376       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6377       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6378       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6379 
6380   // Set the callee in the CallExpr.
6381   // FIXME: This loses syntactic information.
6382   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6383   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6384                                               CK_BuiltinFnToFnPtr);
6385   TheCall->setCallee(PromotedCall.get());
6386 
6387   // Change the result type of the call to match the original value type. This
6388   // is arbitrary, but the codegen for these builtins ins design to handle it
6389   // gracefully.
6390   TheCall->setType(ResultType);
6391 
6392   // Prohibit problematic uses of bit-precise integer types with atomic
6393   // builtins. The arguments would have already been converted to the first
6394   // argument's type, so only need to check the first argument.
6395   const auto *BitIntValType = ValType->getAs<BitIntType>();
6396   if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
6397     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6398     return ExprError();
6399   }
6400 
6401   return TheCallResult;
6402 }
6403 
6404 /// SemaBuiltinNontemporalOverloaded - We have a call to
6405 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6406 /// overloaded function based on the pointer type of its last argument.
6407 ///
6408 /// This function goes through and does final semantic checking for these
6409 /// builtins.
6410 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6411   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6412   DeclRefExpr *DRE =
6413       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6414   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6415   unsigned BuiltinID = FDecl->getBuiltinID();
6416   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6417           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6418          "Unexpected nontemporal load/store builtin!");
6419   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6420   unsigned numArgs = isStore ? 2 : 1;
6421 
6422   // Ensure that we have the proper number of arguments.
6423   if (checkArgCount(*this, TheCall, numArgs))
6424     return ExprError();
6425 
6426   // Inspect the last argument of the nontemporal builtin.  This should always
6427   // be a pointer type, from which we imply the type of the memory access.
6428   // Because it is a pointer type, we don't have to worry about any implicit
6429   // casts here.
6430   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6431   ExprResult PointerArgResult =
6432       DefaultFunctionArrayLvalueConversion(PointerArg);
6433 
6434   if (PointerArgResult.isInvalid())
6435     return ExprError();
6436   PointerArg = PointerArgResult.get();
6437   TheCall->setArg(numArgs - 1, PointerArg);
6438 
6439   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6440   if (!pointerType) {
6441     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6442         << PointerArg->getType() << PointerArg->getSourceRange();
6443     return ExprError();
6444   }
6445 
6446   QualType ValType = pointerType->getPointeeType();
6447 
6448   // Strip any qualifiers off ValType.
6449   ValType = ValType.getUnqualifiedType();
6450   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6451       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6452       !ValType->isVectorType()) {
6453     Diag(DRE->getBeginLoc(),
6454          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6455         << PointerArg->getType() << PointerArg->getSourceRange();
6456     return ExprError();
6457   }
6458 
6459   if (!isStore) {
6460     TheCall->setType(ValType);
6461     return TheCallResult;
6462   }
6463 
6464   ExprResult ValArg = TheCall->getArg(0);
6465   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6466       Context, ValType, /*consume*/ false);
6467   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6468   if (ValArg.isInvalid())
6469     return ExprError();
6470 
6471   TheCall->setArg(0, ValArg.get());
6472   TheCall->setType(Context.VoidTy);
6473   return TheCallResult;
6474 }
6475 
6476 /// CheckObjCString - Checks that the argument to the builtin
6477 /// CFString constructor is correct
6478 /// Note: It might also make sense to do the UTF-16 conversion here (would
6479 /// simplify the backend).
6480 bool Sema::CheckObjCString(Expr *Arg) {
6481   Arg = Arg->IgnoreParenCasts();
6482   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6483 
6484   if (!Literal || !Literal->isAscii()) {
6485     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6486         << Arg->getSourceRange();
6487     return true;
6488   }
6489 
6490   if (Literal->containsNonAsciiOrNull()) {
6491     StringRef String = Literal->getString();
6492     unsigned NumBytes = String.size();
6493     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6494     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6495     llvm::UTF16 *ToPtr = &ToBuf[0];
6496 
6497     llvm::ConversionResult Result =
6498         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6499                                  ToPtr + NumBytes, llvm::strictConversion);
6500     // Check for conversion failure.
6501     if (Result != llvm::conversionOK)
6502       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6503           << Arg->getSourceRange();
6504   }
6505   return false;
6506 }
6507 
6508 /// CheckObjCString - Checks that the format string argument to the os_log()
6509 /// and os_trace() functions is correct, and converts it to const char *.
6510 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6511   Arg = Arg->IgnoreParenCasts();
6512   auto *Literal = dyn_cast<StringLiteral>(Arg);
6513   if (!Literal) {
6514     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6515       Literal = ObjcLiteral->getString();
6516     }
6517   }
6518 
6519   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6520     return ExprError(
6521         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6522         << Arg->getSourceRange());
6523   }
6524 
6525   ExprResult Result(Literal);
6526   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6527   InitializedEntity Entity =
6528       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6529   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6530   return Result;
6531 }
6532 
6533 /// Check that the user is calling the appropriate va_start builtin for the
6534 /// target and calling convention.
6535 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6536   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6537   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6538   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6539                     TT.getArch() == llvm::Triple::aarch64_32);
6540   bool IsWindows = TT.isOSWindows();
6541   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6542   if (IsX64 || IsAArch64) {
6543     CallingConv CC = CC_C;
6544     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6545       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6546     if (IsMSVAStart) {
6547       // Don't allow this in System V ABI functions.
6548       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6549         return S.Diag(Fn->getBeginLoc(),
6550                       diag::err_ms_va_start_used_in_sysv_function);
6551     } else {
6552       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6553       // On x64 Windows, don't allow this in System V ABI functions.
6554       // (Yes, that means there's no corresponding way to support variadic
6555       // System V ABI functions on Windows.)
6556       if ((IsWindows && CC == CC_X86_64SysV) ||
6557           (!IsWindows && CC == CC_Win64))
6558         return S.Diag(Fn->getBeginLoc(),
6559                       diag::err_va_start_used_in_wrong_abi_function)
6560                << !IsWindows;
6561     }
6562     return false;
6563   }
6564 
6565   if (IsMSVAStart)
6566     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6567   return false;
6568 }
6569 
6570 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6571                                              ParmVarDecl **LastParam = nullptr) {
6572   // Determine whether the current function, block, or obj-c method is variadic
6573   // and get its parameter list.
6574   bool IsVariadic = false;
6575   ArrayRef<ParmVarDecl *> Params;
6576   DeclContext *Caller = S.CurContext;
6577   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6578     IsVariadic = Block->isVariadic();
6579     Params = Block->parameters();
6580   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6581     IsVariadic = FD->isVariadic();
6582     Params = FD->parameters();
6583   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6584     IsVariadic = MD->isVariadic();
6585     // FIXME: This isn't correct for methods (results in bogus warning).
6586     Params = MD->parameters();
6587   } else if (isa<CapturedDecl>(Caller)) {
6588     // We don't support va_start in a CapturedDecl.
6589     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6590     return true;
6591   } else {
6592     // This must be some other declcontext that parses exprs.
6593     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6594     return true;
6595   }
6596 
6597   if (!IsVariadic) {
6598     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6599     return true;
6600   }
6601 
6602   if (LastParam)
6603     *LastParam = Params.empty() ? nullptr : Params.back();
6604 
6605   return false;
6606 }
6607 
6608 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6609 /// for validity.  Emit an error and return true on failure; return false
6610 /// on success.
6611 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6612   Expr *Fn = TheCall->getCallee();
6613 
6614   if (checkVAStartABI(*this, BuiltinID, Fn))
6615     return true;
6616 
6617   if (checkArgCount(*this, TheCall, 2))
6618     return true;
6619 
6620   // Type-check the first argument normally.
6621   if (checkBuiltinArgument(*this, TheCall, 0))
6622     return true;
6623 
6624   // Check that the current function is variadic, and get its last parameter.
6625   ParmVarDecl *LastParam;
6626   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6627     return true;
6628 
6629   // Verify that the second argument to the builtin is the last argument of the
6630   // current function or method.
6631   bool SecondArgIsLastNamedArgument = false;
6632   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6633 
6634   // These are valid if SecondArgIsLastNamedArgument is false after the next
6635   // block.
6636   QualType Type;
6637   SourceLocation ParamLoc;
6638   bool IsCRegister = false;
6639 
6640   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6641     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6642       SecondArgIsLastNamedArgument = PV == LastParam;
6643 
6644       Type = PV->getType();
6645       ParamLoc = PV->getLocation();
6646       IsCRegister =
6647           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6648     }
6649   }
6650 
6651   if (!SecondArgIsLastNamedArgument)
6652     Diag(TheCall->getArg(1)->getBeginLoc(),
6653          diag::warn_second_arg_of_va_start_not_last_named_param);
6654   else if (IsCRegister || Type->isReferenceType() ||
6655            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6656              // Promotable integers are UB, but enumerations need a bit of
6657              // extra checking to see what their promotable type actually is.
6658              if (!Type->isPromotableIntegerType())
6659                return false;
6660              if (!Type->isEnumeralType())
6661                return true;
6662              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6663              return !(ED &&
6664                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6665            }()) {
6666     unsigned Reason = 0;
6667     if (Type->isReferenceType())  Reason = 1;
6668     else if (IsCRegister)         Reason = 2;
6669     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6670     Diag(ParamLoc, diag::note_parameter_type) << Type;
6671   }
6672 
6673   TheCall->setType(Context.VoidTy);
6674   return false;
6675 }
6676 
6677 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6678   auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6679     const LangOptions &LO = getLangOpts();
6680 
6681     if (LO.CPlusPlus)
6682       return Arg->getType()
6683                  .getCanonicalType()
6684                  .getTypePtr()
6685                  ->getPointeeType()
6686                  .withoutLocalFastQualifiers() == Context.CharTy;
6687 
6688     // In C, allow aliasing through `char *`, this is required for AArch64 at
6689     // least.
6690     return true;
6691   };
6692 
6693   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6694   //                 const char *named_addr);
6695 
6696   Expr *Func = Call->getCallee();
6697 
6698   if (Call->getNumArgs() < 3)
6699     return Diag(Call->getEndLoc(),
6700                 diag::err_typecheck_call_too_few_args_at_least)
6701            << 0 /*function call*/ << 3 << Call->getNumArgs();
6702 
6703   // Type-check the first argument normally.
6704   if (checkBuiltinArgument(*this, Call, 0))
6705     return true;
6706 
6707   // Check that the current function is variadic.
6708   if (checkVAStartIsInVariadicFunction(*this, Func))
6709     return true;
6710 
6711   // __va_start on Windows does not validate the parameter qualifiers
6712 
6713   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6714   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6715 
6716   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6717   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6718 
6719   const QualType &ConstCharPtrTy =
6720       Context.getPointerType(Context.CharTy.withConst());
6721   if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6722     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6723         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6724         << 0                                      /* qualifier difference */
6725         << 3                                      /* parameter mismatch */
6726         << 2 << Arg1->getType() << ConstCharPtrTy;
6727 
6728   const QualType SizeTy = Context.getSizeType();
6729   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6730     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6731         << Arg2->getType() << SizeTy << 1 /* different class */
6732         << 0                              /* qualifier difference */
6733         << 3                              /* parameter mismatch */
6734         << 3 << Arg2->getType() << SizeTy;
6735 
6736   return false;
6737 }
6738 
6739 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6740 /// friends.  This is declared to take (...), so we have to check everything.
6741 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6742   if (checkArgCount(*this, TheCall, 2))
6743     return true;
6744 
6745   ExprResult OrigArg0 = TheCall->getArg(0);
6746   ExprResult OrigArg1 = TheCall->getArg(1);
6747 
6748   // Do standard promotions between the two arguments, returning their common
6749   // type.
6750   QualType Res = UsualArithmeticConversions(
6751       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6752   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6753     return true;
6754 
6755   // Make sure any conversions are pushed back into the call; this is
6756   // type safe since unordered compare builtins are declared as "_Bool
6757   // foo(...)".
6758   TheCall->setArg(0, OrigArg0.get());
6759   TheCall->setArg(1, OrigArg1.get());
6760 
6761   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6762     return false;
6763 
6764   // If the common type isn't a real floating type, then the arguments were
6765   // invalid for this operation.
6766   if (Res.isNull() || !Res->isRealFloatingType())
6767     return Diag(OrigArg0.get()->getBeginLoc(),
6768                 diag::err_typecheck_call_invalid_ordered_compare)
6769            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6770            << SourceRange(OrigArg0.get()->getBeginLoc(),
6771                           OrigArg1.get()->getEndLoc());
6772 
6773   return false;
6774 }
6775 
6776 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6777 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6778 /// to check everything. We expect the last argument to be a floating point
6779 /// value.
6780 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6781   if (checkArgCount(*this, TheCall, NumArgs))
6782     return true;
6783 
6784   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6785   // on all preceding parameters just being int.  Try all of those.
6786   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6787     Expr *Arg = TheCall->getArg(i);
6788 
6789     if (Arg->isTypeDependent())
6790       return false;
6791 
6792     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6793 
6794     if (Res.isInvalid())
6795       return true;
6796     TheCall->setArg(i, Res.get());
6797   }
6798 
6799   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6800 
6801   if (OrigArg->isTypeDependent())
6802     return false;
6803 
6804   // Usual Unary Conversions will convert half to float, which we want for
6805   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6806   // type how it is, but do normal L->Rvalue conversions.
6807   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6808     OrigArg = UsualUnaryConversions(OrigArg).get();
6809   else
6810     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6811   TheCall->setArg(NumArgs - 1, OrigArg);
6812 
6813   // This operation requires a non-_Complex floating-point number.
6814   if (!OrigArg->getType()->isRealFloatingType())
6815     return Diag(OrigArg->getBeginLoc(),
6816                 diag::err_typecheck_call_invalid_unary_fp)
6817            << OrigArg->getType() << OrigArg->getSourceRange();
6818 
6819   return false;
6820 }
6821 
6822 /// Perform semantic analysis for a call to __builtin_complex.
6823 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6824   if (checkArgCount(*this, TheCall, 2))
6825     return true;
6826 
6827   bool Dependent = false;
6828   for (unsigned I = 0; I != 2; ++I) {
6829     Expr *Arg = TheCall->getArg(I);
6830     QualType T = Arg->getType();
6831     if (T->isDependentType()) {
6832       Dependent = true;
6833       continue;
6834     }
6835 
6836     // Despite supporting _Complex int, GCC requires a real floating point type
6837     // for the operands of __builtin_complex.
6838     if (!T->isRealFloatingType()) {
6839       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6840              << Arg->getType() << Arg->getSourceRange();
6841     }
6842 
6843     ExprResult Converted = DefaultLvalueConversion(Arg);
6844     if (Converted.isInvalid())
6845       return true;
6846     TheCall->setArg(I, Converted.get());
6847   }
6848 
6849   if (Dependent) {
6850     TheCall->setType(Context.DependentTy);
6851     return false;
6852   }
6853 
6854   Expr *Real = TheCall->getArg(0);
6855   Expr *Imag = TheCall->getArg(1);
6856   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6857     return Diag(Real->getBeginLoc(),
6858                 diag::err_typecheck_call_different_arg_types)
6859            << Real->getType() << Imag->getType()
6860            << Real->getSourceRange() << Imag->getSourceRange();
6861   }
6862 
6863   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6864   // don't allow this builtin to form those types either.
6865   // FIXME: Should we allow these types?
6866   if (Real->getType()->isFloat16Type())
6867     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6868            << "_Float16";
6869   if (Real->getType()->isHalfType())
6870     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6871            << "half";
6872 
6873   TheCall->setType(Context.getComplexType(Real->getType()));
6874   return false;
6875 }
6876 
6877 // Customized Sema Checking for VSX builtins that have the following signature:
6878 // vector [...] builtinName(vector [...], vector [...], const int);
6879 // Which takes the same type of vectors (any legal vector type) for the first
6880 // two arguments and takes compile time constant for the third argument.
6881 // Example builtins are :
6882 // vector double vec_xxpermdi(vector double, vector double, int);
6883 // vector short vec_xxsldwi(vector short, vector short, int);
6884 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6885   unsigned ExpectedNumArgs = 3;
6886   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6887     return true;
6888 
6889   // Check the third argument is a compile time constant
6890   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6891     return Diag(TheCall->getBeginLoc(),
6892                 diag::err_vsx_builtin_nonconstant_argument)
6893            << 3 /* argument index */ << TheCall->getDirectCallee()
6894            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6895                           TheCall->getArg(2)->getEndLoc());
6896 
6897   QualType Arg1Ty = TheCall->getArg(0)->getType();
6898   QualType Arg2Ty = TheCall->getArg(1)->getType();
6899 
6900   // Check the type of argument 1 and argument 2 are vectors.
6901   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6902   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6903       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6904     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6905            << TheCall->getDirectCallee()
6906            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6907                           TheCall->getArg(1)->getEndLoc());
6908   }
6909 
6910   // Check the first two arguments are the same type.
6911   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6912     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6913            << TheCall->getDirectCallee()
6914            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6915                           TheCall->getArg(1)->getEndLoc());
6916   }
6917 
6918   // When default clang type checking is turned off and the customized type
6919   // checking is used, the returning type of the function must be explicitly
6920   // set. Otherwise it is _Bool by default.
6921   TheCall->setType(Arg1Ty);
6922 
6923   return false;
6924 }
6925 
6926 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6927 // This is declared to take (...), so we have to check everything.
6928 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6929   if (TheCall->getNumArgs() < 2)
6930     return ExprError(Diag(TheCall->getEndLoc(),
6931                           diag::err_typecheck_call_too_few_args_at_least)
6932                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6933                      << TheCall->getSourceRange());
6934 
6935   // Determine which of the following types of shufflevector we're checking:
6936   // 1) unary, vector mask: (lhs, mask)
6937   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6938   QualType resType = TheCall->getArg(0)->getType();
6939   unsigned numElements = 0;
6940 
6941   if (!TheCall->getArg(0)->isTypeDependent() &&
6942       !TheCall->getArg(1)->isTypeDependent()) {
6943     QualType LHSType = TheCall->getArg(0)->getType();
6944     QualType RHSType = TheCall->getArg(1)->getType();
6945 
6946     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6947       return ExprError(
6948           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6949           << TheCall->getDirectCallee()
6950           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6951                          TheCall->getArg(1)->getEndLoc()));
6952 
6953     numElements = LHSType->castAs<VectorType>()->getNumElements();
6954     unsigned numResElements = TheCall->getNumArgs() - 2;
6955 
6956     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6957     // with mask.  If so, verify that RHS is an integer vector type with the
6958     // same number of elts as lhs.
6959     if (TheCall->getNumArgs() == 2) {
6960       if (!RHSType->hasIntegerRepresentation() ||
6961           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6962         return ExprError(Diag(TheCall->getBeginLoc(),
6963                               diag::err_vec_builtin_incompatible_vector)
6964                          << TheCall->getDirectCallee()
6965                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6966                                         TheCall->getArg(1)->getEndLoc()));
6967     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6968       return ExprError(Diag(TheCall->getBeginLoc(),
6969                             diag::err_vec_builtin_incompatible_vector)
6970                        << TheCall->getDirectCallee()
6971                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6972                                       TheCall->getArg(1)->getEndLoc()));
6973     } else if (numElements != numResElements) {
6974       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6975       resType = Context.getVectorType(eltType, numResElements,
6976                                       VectorType::GenericVector);
6977     }
6978   }
6979 
6980   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6981     if (TheCall->getArg(i)->isTypeDependent() ||
6982         TheCall->getArg(i)->isValueDependent())
6983       continue;
6984 
6985     Optional<llvm::APSInt> Result;
6986     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6987       return ExprError(Diag(TheCall->getBeginLoc(),
6988                             diag::err_shufflevector_nonconstant_argument)
6989                        << TheCall->getArg(i)->getSourceRange());
6990 
6991     // Allow -1 which will be translated to undef in the IR.
6992     if (Result->isSigned() && Result->isAllOnes())
6993       continue;
6994 
6995     if (Result->getActiveBits() > 64 ||
6996         Result->getZExtValue() >= numElements * 2)
6997       return ExprError(Diag(TheCall->getBeginLoc(),
6998                             diag::err_shufflevector_argument_too_large)
6999                        << TheCall->getArg(i)->getSourceRange());
7000   }
7001 
7002   SmallVector<Expr*, 32> exprs;
7003 
7004   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
7005     exprs.push_back(TheCall->getArg(i));
7006     TheCall->setArg(i, nullptr);
7007   }
7008 
7009   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
7010                                          TheCall->getCallee()->getBeginLoc(),
7011                                          TheCall->getRParenLoc());
7012 }
7013 
7014 /// SemaConvertVectorExpr - Handle __builtin_convertvector
7015 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
7016                                        SourceLocation BuiltinLoc,
7017                                        SourceLocation RParenLoc) {
7018   ExprValueKind VK = VK_PRValue;
7019   ExprObjectKind OK = OK_Ordinary;
7020   QualType DstTy = TInfo->getType();
7021   QualType SrcTy = E->getType();
7022 
7023   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
7024     return ExprError(Diag(BuiltinLoc,
7025                           diag::err_convertvector_non_vector)
7026                      << E->getSourceRange());
7027   if (!DstTy->isVectorType() && !DstTy->isDependentType())
7028     return ExprError(Diag(BuiltinLoc,
7029                           diag::err_convertvector_non_vector_type));
7030 
7031   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
7032     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
7033     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
7034     if (SrcElts != DstElts)
7035       return ExprError(Diag(BuiltinLoc,
7036                             diag::err_convertvector_incompatible_vector)
7037                        << E->getSourceRange());
7038   }
7039 
7040   return new (Context)
7041       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
7042 }
7043 
7044 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
7045 // This is declared to take (const void*, ...) and can take two
7046 // optional constant int args.
7047 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
7048   unsigned NumArgs = TheCall->getNumArgs();
7049 
7050   if (NumArgs > 3)
7051     return Diag(TheCall->getEndLoc(),
7052                 diag::err_typecheck_call_too_many_args_at_most)
7053            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7054 
7055   // Argument 0 is checked for us and the remaining arguments must be
7056   // constant integers.
7057   for (unsigned i = 1; i != NumArgs; ++i)
7058     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
7059       return true;
7060 
7061   return false;
7062 }
7063 
7064 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
7065 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
7066   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
7067     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
7068            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7069   if (checkArgCount(*this, TheCall, 1))
7070     return true;
7071   Expr *Arg = TheCall->getArg(0);
7072   if (Arg->isInstantiationDependent())
7073     return false;
7074 
7075   QualType ArgTy = Arg->getType();
7076   if (!ArgTy->hasFloatingRepresentation())
7077     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
7078            << ArgTy;
7079   if (Arg->isLValue()) {
7080     ExprResult FirstArg = DefaultLvalueConversion(Arg);
7081     TheCall->setArg(0, FirstArg.get());
7082   }
7083   TheCall->setType(TheCall->getArg(0)->getType());
7084   return false;
7085 }
7086 
7087 /// SemaBuiltinAssume - Handle __assume (MS Extension).
7088 // __assume does not evaluate its arguments, and should warn if its argument
7089 // has side effects.
7090 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
7091   Expr *Arg = TheCall->getArg(0);
7092   if (Arg->isInstantiationDependent()) return false;
7093 
7094   if (Arg->HasSideEffects(Context))
7095     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
7096         << Arg->getSourceRange()
7097         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
7098 
7099   return false;
7100 }
7101 
7102 /// Handle __builtin_alloca_with_align. This is declared
7103 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
7104 /// than 8.
7105 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
7106   // The alignment must be a constant integer.
7107   Expr *Arg = TheCall->getArg(1);
7108 
7109   // We can't check the value of a dependent argument.
7110   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7111     if (const auto *UE =
7112             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
7113       if (UE->getKind() == UETT_AlignOf ||
7114           UE->getKind() == UETT_PreferredAlignOf)
7115         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
7116             << Arg->getSourceRange();
7117 
7118     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
7119 
7120     if (!Result.isPowerOf2())
7121       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7122              << Arg->getSourceRange();
7123 
7124     if (Result < Context.getCharWidth())
7125       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
7126              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
7127 
7128     if (Result > std::numeric_limits<int32_t>::max())
7129       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
7130              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
7131   }
7132 
7133   return false;
7134 }
7135 
7136 /// Handle __builtin_assume_aligned. This is declared
7137 /// as (const void*, size_t, ...) and can take one optional constant int arg.
7138 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
7139   unsigned NumArgs = TheCall->getNumArgs();
7140 
7141   if (NumArgs > 3)
7142     return Diag(TheCall->getEndLoc(),
7143                 diag::err_typecheck_call_too_many_args_at_most)
7144            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7145 
7146   // The alignment must be a constant integer.
7147   Expr *Arg = TheCall->getArg(1);
7148 
7149   // We can't check the value of a dependent argument.
7150   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7151     llvm::APSInt Result;
7152     if (SemaBuiltinConstantArg(TheCall, 1, Result))
7153       return true;
7154 
7155     if (!Result.isPowerOf2())
7156       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7157              << Arg->getSourceRange();
7158 
7159     if (Result > Sema::MaximumAlignment)
7160       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
7161           << Arg->getSourceRange() << Sema::MaximumAlignment;
7162   }
7163 
7164   if (NumArgs > 2) {
7165     ExprResult Arg(TheCall->getArg(2));
7166     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
7167       Context.getSizeType(), false);
7168     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7169     if (Arg.isInvalid()) return true;
7170     TheCall->setArg(2, Arg.get());
7171   }
7172 
7173   return false;
7174 }
7175 
7176 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
7177   unsigned BuiltinID =
7178       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
7179   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
7180 
7181   unsigned NumArgs = TheCall->getNumArgs();
7182   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
7183   if (NumArgs < NumRequiredArgs) {
7184     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
7185            << 0 /* function call */ << NumRequiredArgs << NumArgs
7186            << TheCall->getSourceRange();
7187   }
7188   if (NumArgs >= NumRequiredArgs + 0x100) {
7189     return Diag(TheCall->getEndLoc(),
7190                 diag::err_typecheck_call_too_many_args_at_most)
7191            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
7192            << TheCall->getSourceRange();
7193   }
7194   unsigned i = 0;
7195 
7196   // For formatting call, check buffer arg.
7197   if (!IsSizeCall) {
7198     ExprResult Arg(TheCall->getArg(i));
7199     InitializedEntity Entity = InitializedEntity::InitializeParameter(
7200         Context, Context.VoidPtrTy, false);
7201     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7202     if (Arg.isInvalid())
7203       return true;
7204     TheCall->setArg(i, Arg.get());
7205     i++;
7206   }
7207 
7208   // Check string literal arg.
7209   unsigned FormatIdx = i;
7210   {
7211     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
7212     if (Arg.isInvalid())
7213       return true;
7214     TheCall->setArg(i, Arg.get());
7215     i++;
7216   }
7217 
7218   // Make sure variadic args are scalar.
7219   unsigned FirstDataArg = i;
7220   while (i < NumArgs) {
7221     ExprResult Arg = DefaultVariadicArgumentPromotion(
7222         TheCall->getArg(i), VariadicFunction, nullptr);
7223     if (Arg.isInvalid())
7224       return true;
7225     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
7226     if (ArgSize.getQuantity() >= 0x100) {
7227       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
7228              << i << (int)ArgSize.getQuantity() << 0xff
7229              << TheCall->getSourceRange();
7230     }
7231     TheCall->setArg(i, Arg.get());
7232     i++;
7233   }
7234 
7235   // Check formatting specifiers. NOTE: We're only doing this for the non-size
7236   // call to avoid duplicate diagnostics.
7237   if (!IsSizeCall) {
7238     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
7239     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
7240     bool Success = CheckFormatArguments(
7241         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
7242         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
7243         CheckedVarArgs);
7244     if (!Success)
7245       return true;
7246   }
7247 
7248   if (IsSizeCall) {
7249     TheCall->setType(Context.getSizeType());
7250   } else {
7251     TheCall->setType(Context.VoidPtrTy);
7252   }
7253   return false;
7254 }
7255 
7256 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
7257 /// TheCall is a constant expression.
7258 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7259                                   llvm::APSInt &Result) {
7260   Expr *Arg = TheCall->getArg(ArgNum);
7261   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
7262   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
7263 
7264   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
7265 
7266   Optional<llvm::APSInt> R;
7267   if (!(R = Arg->getIntegerConstantExpr(Context)))
7268     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
7269            << FDecl->getDeclName() << Arg->getSourceRange();
7270   Result = *R;
7271   return false;
7272 }
7273 
7274 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
7275 /// TheCall is a constant expression in the range [Low, High].
7276 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
7277                                        int Low, int High, bool RangeIsError) {
7278   if (isConstantEvaluated())
7279     return false;
7280   llvm::APSInt Result;
7281 
7282   // We can't check the value of a dependent argument.
7283   Expr *Arg = TheCall->getArg(ArgNum);
7284   if (Arg->isTypeDependent() || Arg->isValueDependent())
7285     return false;
7286 
7287   // Check constant-ness first.
7288   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7289     return true;
7290 
7291   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7292     if (RangeIsError)
7293       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
7294              << toString(Result, 10) << Low << High << Arg->getSourceRange();
7295     else
7296       // Defer the warning until we know if the code will be emitted so that
7297       // dead code can ignore this.
7298       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
7299                           PDiag(diag::warn_argument_invalid_range)
7300                               << toString(Result, 10) << Low << High
7301                               << Arg->getSourceRange());
7302   }
7303 
7304   return false;
7305 }
7306 
7307 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
7308 /// TheCall is a constant expression is a multiple of Num..
7309 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
7310                                           unsigned Num) {
7311   llvm::APSInt Result;
7312 
7313   // We can't check the value of a dependent argument.
7314   Expr *Arg = TheCall->getArg(ArgNum);
7315   if (Arg->isTypeDependent() || Arg->isValueDependent())
7316     return false;
7317 
7318   // Check constant-ness first.
7319   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7320     return true;
7321 
7322   if (Result.getSExtValue() % Num != 0)
7323     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7324            << Num << Arg->getSourceRange();
7325 
7326   return false;
7327 }
7328 
7329 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7330 /// constant expression representing a power of 2.
7331 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7332   llvm::APSInt Result;
7333 
7334   // We can't check the value of a dependent argument.
7335   Expr *Arg = TheCall->getArg(ArgNum);
7336   if (Arg->isTypeDependent() || Arg->isValueDependent())
7337     return false;
7338 
7339   // Check constant-ness first.
7340   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7341     return true;
7342 
7343   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7344   // and only if x is a power of 2.
7345   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7346     return false;
7347 
7348   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7349          << Arg->getSourceRange();
7350 }
7351 
7352 static bool IsShiftedByte(llvm::APSInt Value) {
7353   if (Value.isNegative())
7354     return false;
7355 
7356   // Check if it's a shifted byte, by shifting it down
7357   while (true) {
7358     // If the value fits in the bottom byte, the check passes.
7359     if (Value < 0x100)
7360       return true;
7361 
7362     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7363     // fails.
7364     if ((Value & 0xFF) != 0)
7365       return false;
7366 
7367     // If the bottom 8 bits are all 0, but something above that is nonzero,
7368     // then shifting the value right by 8 bits won't affect whether it's a
7369     // shifted byte or not. So do that, and go round again.
7370     Value >>= 8;
7371   }
7372 }
7373 
7374 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7375 /// a constant expression representing an arbitrary byte value shifted left by
7376 /// a multiple of 8 bits.
7377 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7378                                              unsigned ArgBits) {
7379   llvm::APSInt Result;
7380 
7381   // We can't check the value of a dependent argument.
7382   Expr *Arg = TheCall->getArg(ArgNum);
7383   if (Arg->isTypeDependent() || Arg->isValueDependent())
7384     return false;
7385 
7386   // Check constant-ness first.
7387   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7388     return true;
7389 
7390   // Truncate to the given size.
7391   Result = Result.getLoBits(ArgBits);
7392   Result.setIsUnsigned(true);
7393 
7394   if (IsShiftedByte(Result))
7395     return false;
7396 
7397   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7398          << Arg->getSourceRange();
7399 }
7400 
7401 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7402 /// TheCall is a constant expression representing either a shifted byte value,
7403 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7404 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7405 /// Arm MVE intrinsics.
7406 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7407                                                    int ArgNum,
7408                                                    unsigned ArgBits) {
7409   llvm::APSInt Result;
7410 
7411   // We can't check the value of a dependent argument.
7412   Expr *Arg = TheCall->getArg(ArgNum);
7413   if (Arg->isTypeDependent() || Arg->isValueDependent())
7414     return false;
7415 
7416   // Check constant-ness first.
7417   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7418     return true;
7419 
7420   // Truncate to the given size.
7421   Result = Result.getLoBits(ArgBits);
7422   Result.setIsUnsigned(true);
7423 
7424   // Check to see if it's in either of the required forms.
7425   if (IsShiftedByte(Result) ||
7426       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7427     return false;
7428 
7429   return Diag(TheCall->getBeginLoc(),
7430               diag::err_argument_not_shifted_byte_or_xxff)
7431          << Arg->getSourceRange();
7432 }
7433 
7434 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7435 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7436   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7437     if (checkArgCount(*this, TheCall, 2))
7438       return true;
7439     Expr *Arg0 = TheCall->getArg(0);
7440     Expr *Arg1 = TheCall->getArg(1);
7441 
7442     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7443     if (FirstArg.isInvalid())
7444       return true;
7445     QualType FirstArgType = FirstArg.get()->getType();
7446     if (!FirstArgType->isAnyPointerType())
7447       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7448                << "first" << FirstArgType << Arg0->getSourceRange();
7449     TheCall->setArg(0, FirstArg.get());
7450 
7451     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7452     if (SecArg.isInvalid())
7453       return true;
7454     QualType SecArgType = SecArg.get()->getType();
7455     if (!SecArgType->isIntegerType())
7456       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7457                << "second" << SecArgType << Arg1->getSourceRange();
7458 
7459     // Derive the return type from the pointer argument.
7460     TheCall->setType(FirstArgType);
7461     return false;
7462   }
7463 
7464   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7465     if (checkArgCount(*this, TheCall, 2))
7466       return true;
7467 
7468     Expr *Arg0 = TheCall->getArg(0);
7469     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7470     if (FirstArg.isInvalid())
7471       return true;
7472     QualType FirstArgType = FirstArg.get()->getType();
7473     if (!FirstArgType->isAnyPointerType())
7474       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7475                << "first" << FirstArgType << Arg0->getSourceRange();
7476     TheCall->setArg(0, FirstArg.get());
7477 
7478     // Derive the return type from the pointer argument.
7479     TheCall->setType(FirstArgType);
7480 
7481     // Second arg must be an constant in range [0,15]
7482     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7483   }
7484 
7485   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7486     if (checkArgCount(*this, TheCall, 2))
7487       return true;
7488     Expr *Arg0 = TheCall->getArg(0);
7489     Expr *Arg1 = TheCall->getArg(1);
7490 
7491     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7492     if (FirstArg.isInvalid())
7493       return true;
7494     QualType FirstArgType = FirstArg.get()->getType();
7495     if (!FirstArgType->isAnyPointerType())
7496       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7497                << "first" << FirstArgType << Arg0->getSourceRange();
7498 
7499     QualType SecArgType = Arg1->getType();
7500     if (!SecArgType->isIntegerType())
7501       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7502                << "second" << SecArgType << Arg1->getSourceRange();
7503     TheCall->setType(Context.IntTy);
7504     return false;
7505   }
7506 
7507   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7508       BuiltinID == AArch64::BI__builtin_arm_stg) {
7509     if (checkArgCount(*this, TheCall, 1))
7510       return true;
7511     Expr *Arg0 = TheCall->getArg(0);
7512     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7513     if (FirstArg.isInvalid())
7514       return true;
7515 
7516     QualType FirstArgType = FirstArg.get()->getType();
7517     if (!FirstArgType->isAnyPointerType())
7518       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7519                << "first" << FirstArgType << Arg0->getSourceRange();
7520     TheCall->setArg(0, FirstArg.get());
7521 
7522     // Derive the return type from the pointer argument.
7523     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7524       TheCall->setType(FirstArgType);
7525     return false;
7526   }
7527 
7528   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7529     Expr *ArgA = TheCall->getArg(0);
7530     Expr *ArgB = TheCall->getArg(1);
7531 
7532     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7533     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7534 
7535     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7536       return true;
7537 
7538     QualType ArgTypeA = ArgExprA.get()->getType();
7539     QualType ArgTypeB = ArgExprB.get()->getType();
7540 
7541     auto isNull = [&] (Expr *E) -> bool {
7542       return E->isNullPointerConstant(
7543                         Context, Expr::NPC_ValueDependentIsNotNull); };
7544 
7545     // argument should be either a pointer or null
7546     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7547       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7548         << "first" << ArgTypeA << ArgA->getSourceRange();
7549 
7550     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7551       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7552         << "second" << ArgTypeB << ArgB->getSourceRange();
7553 
7554     // Ensure Pointee types are compatible
7555     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7556         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7557       QualType pointeeA = ArgTypeA->getPointeeType();
7558       QualType pointeeB = ArgTypeB->getPointeeType();
7559       if (!Context.typesAreCompatible(
7560              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7561              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7562         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7563           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7564           << ArgB->getSourceRange();
7565       }
7566     }
7567 
7568     // at least one argument should be pointer type
7569     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7570       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7571         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7572 
7573     if (isNull(ArgA)) // adopt type of the other pointer
7574       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7575 
7576     if (isNull(ArgB))
7577       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7578 
7579     TheCall->setArg(0, ArgExprA.get());
7580     TheCall->setArg(1, ArgExprB.get());
7581     TheCall->setType(Context.LongLongTy);
7582     return false;
7583   }
7584   assert(false && "Unhandled ARM MTE intrinsic");
7585   return true;
7586 }
7587 
7588 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7589 /// TheCall is an ARM/AArch64 special register string literal.
7590 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7591                                     int ArgNum, unsigned ExpectedFieldNum,
7592                                     bool AllowName) {
7593   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7594                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7595                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7596                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7597                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7598                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7599   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7600                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7601                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7602                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7603                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7604                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7605   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7606 
7607   // We can't check the value of a dependent argument.
7608   Expr *Arg = TheCall->getArg(ArgNum);
7609   if (Arg->isTypeDependent() || Arg->isValueDependent())
7610     return false;
7611 
7612   // Check if the argument is a string literal.
7613   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7614     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7615            << Arg->getSourceRange();
7616 
7617   // Check the type of special register given.
7618   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7619   SmallVector<StringRef, 6> Fields;
7620   Reg.split(Fields, ":");
7621 
7622   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7623     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7624            << Arg->getSourceRange();
7625 
7626   // If the string is the name of a register then we cannot check that it is
7627   // valid here but if the string is of one the forms described in ACLE then we
7628   // can check that the supplied fields are integers and within the valid
7629   // ranges.
7630   if (Fields.size() > 1) {
7631     bool FiveFields = Fields.size() == 5;
7632 
7633     bool ValidString = true;
7634     if (IsARMBuiltin) {
7635       ValidString &= Fields[0].startswith_insensitive("cp") ||
7636                      Fields[0].startswith_insensitive("p");
7637       if (ValidString)
7638         Fields[0] = Fields[0].drop_front(
7639             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7640 
7641       ValidString &= Fields[2].startswith_insensitive("c");
7642       if (ValidString)
7643         Fields[2] = Fields[2].drop_front(1);
7644 
7645       if (FiveFields) {
7646         ValidString &= Fields[3].startswith_insensitive("c");
7647         if (ValidString)
7648           Fields[3] = Fields[3].drop_front(1);
7649       }
7650     }
7651 
7652     SmallVector<int, 5> Ranges;
7653     if (FiveFields)
7654       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7655     else
7656       Ranges.append({15, 7, 15});
7657 
7658     for (unsigned i=0; i<Fields.size(); ++i) {
7659       int IntField;
7660       ValidString &= !Fields[i].getAsInteger(10, IntField);
7661       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7662     }
7663 
7664     if (!ValidString)
7665       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7666              << Arg->getSourceRange();
7667   } else if (IsAArch64Builtin && Fields.size() == 1) {
7668     // If the register name is one of those that appear in the condition below
7669     // and the special register builtin being used is one of the write builtins,
7670     // then we require that the argument provided for writing to the register
7671     // is an integer constant expression. This is because it will be lowered to
7672     // an MSR (immediate) instruction, so we need to know the immediate at
7673     // compile time.
7674     if (TheCall->getNumArgs() != 2)
7675       return false;
7676 
7677     std::string RegLower = Reg.lower();
7678     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7679         RegLower != "pan" && RegLower != "uao")
7680       return false;
7681 
7682     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7683   }
7684 
7685   return false;
7686 }
7687 
7688 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7689 /// Emit an error and return true on failure; return false on success.
7690 /// TypeStr is a string containing the type descriptor of the value returned by
7691 /// the builtin and the descriptors of the expected type of the arguments.
7692 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
7693                                  const char *TypeStr) {
7694 
7695   assert((TypeStr[0] != '\0') &&
7696          "Invalid types in PPC MMA builtin declaration");
7697 
7698   switch (BuiltinID) {
7699   default:
7700     // This function is called in CheckPPCBuiltinFunctionCall where the
7701     // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here
7702     // we are isolating the pair vector memop builtins that can be used with mma
7703     // off so the default case is every builtin that requires mma and paired
7704     // vector memops.
7705     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7706                          diag::err_ppc_builtin_only_on_arch, "10") ||
7707         SemaFeatureCheck(*this, TheCall, "mma",
7708                          diag::err_ppc_builtin_only_on_arch, "10"))
7709       return true;
7710     break;
7711   case PPC::BI__builtin_vsx_lxvp:
7712   case PPC::BI__builtin_vsx_stxvp:
7713   case PPC::BI__builtin_vsx_assemble_pair:
7714   case PPC::BI__builtin_vsx_disassemble_pair:
7715     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7716                          diag::err_ppc_builtin_only_on_arch, "10"))
7717       return true;
7718     break;
7719   }
7720 
7721   unsigned Mask = 0;
7722   unsigned ArgNum = 0;
7723 
7724   // The first type in TypeStr is the type of the value returned by the
7725   // builtin. So we first read that type and change the type of TheCall.
7726   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7727   TheCall->setType(type);
7728 
7729   while (*TypeStr != '\0') {
7730     Mask = 0;
7731     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7732     if (ArgNum >= TheCall->getNumArgs()) {
7733       ArgNum++;
7734       break;
7735     }
7736 
7737     Expr *Arg = TheCall->getArg(ArgNum);
7738     QualType PassedType = Arg->getType();
7739     QualType StrippedRVType = PassedType.getCanonicalType();
7740 
7741     // Strip Restrict/Volatile qualifiers.
7742     if (StrippedRVType.isRestrictQualified() ||
7743         StrippedRVType.isVolatileQualified())
7744       StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
7745 
7746     // The only case where the argument type and expected type are allowed to
7747     // mismatch is if the argument type is a non-void pointer (or array) and
7748     // expected type is a void pointer.
7749     if (StrippedRVType != ExpectedType)
7750       if (!(ExpectedType->isVoidPointerType() &&
7751             (StrippedRVType->isPointerType() || StrippedRVType->isArrayType())))
7752         return Diag(Arg->getBeginLoc(),
7753                     diag::err_typecheck_convert_incompatible)
7754                << PassedType << ExpectedType << 1 << 0 << 0;
7755 
7756     // If the value of the Mask is not 0, we have a constraint in the size of
7757     // the integer argument so here we ensure the argument is a constant that
7758     // is in the valid range.
7759     if (Mask != 0 &&
7760         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7761       return true;
7762 
7763     ArgNum++;
7764   }
7765 
7766   // In case we exited early from the previous loop, there are other types to
7767   // read from TypeStr. So we need to read them all to ensure we have the right
7768   // number of arguments in TheCall and if it is not the case, to display a
7769   // better error message.
7770   while (*TypeStr != '\0') {
7771     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7772     ArgNum++;
7773   }
7774   if (checkArgCount(*this, TheCall, ArgNum))
7775     return true;
7776 
7777   return false;
7778 }
7779 
7780 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7781 /// This checks that the target supports __builtin_longjmp and
7782 /// that val is a constant 1.
7783 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7784   if (!Context.getTargetInfo().hasSjLjLowering())
7785     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7786            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7787 
7788   Expr *Arg = TheCall->getArg(1);
7789   llvm::APSInt Result;
7790 
7791   // TODO: This is less than ideal. Overload this to take a value.
7792   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7793     return true;
7794 
7795   if (Result != 1)
7796     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7797            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7798 
7799   return false;
7800 }
7801 
7802 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7803 /// This checks that the target supports __builtin_setjmp.
7804 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7805   if (!Context.getTargetInfo().hasSjLjLowering())
7806     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7807            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7808   return false;
7809 }
7810 
7811 namespace {
7812 
7813 class UncoveredArgHandler {
7814   enum { Unknown = -1, AllCovered = -2 };
7815 
7816   signed FirstUncoveredArg = Unknown;
7817   SmallVector<const Expr *, 4> DiagnosticExprs;
7818 
7819 public:
7820   UncoveredArgHandler() = default;
7821 
7822   bool hasUncoveredArg() const {
7823     return (FirstUncoveredArg >= 0);
7824   }
7825 
7826   unsigned getUncoveredArg() const {
7827     assert(hasUncoveredArg() && "no uncovered argument");
7828     return FirstUncoveredArg;
7829   }
7830 
7831   void setAllCovered() {
7832     // A string has been found with all arguments covered, so clear out
7833     // the diagnostics.
7834     DiagnosticExprs.clear();
7835     FirstUncoveredArg = AllCovered;
7836   }
7837 
7838   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7839     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7840 
7841     // Don't update if a previous string covers all arguments.
7842     if (FirstUncoveredArg == AllCovered)
7843       return;
7844 
7845     // UncoveredArgHandler tracks the highest uncovered argument index
7846     // and with it all the strings that match this index.
7847     if (NewFirstUncoveredArg == FirstUncoveredArg)
7848       DiagnosticExprs.push_back(StrExpr);
7849     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7850       DiagnosticExprs.clear();
7851       DiagnosticExprs.push_back(StrExpr);
7852       FirstUncoveredArg = NewFirstUncoveredArg;
7853     }
7854   }
7855 
7856   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7857 };
7858 
7859 enum StringLiteralCheckType {
7860   SLCT_NotALiteral,
7861   SLCT_UncheckedLiteral,
7862   SLCT_CheckedLiteral
7863 };
7864 
7865 } // namespace
7866 
7867 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7868                                      BinaryOperatorKind BinOpKind,
7869                                      bool AddendIsRight) {
7870   unsigned BitWidth = Offset.getBitWidth();
7871   unsigned AddendBitWidth = Addend.getBitWidth();
7872   // There might be negative interim results.
7873   if (Addend.isUnsigned()) {
7874     Addend = Addend.zext(++AddendBitWidth);
7875     Addend.setIsSigned(true);
7876   }
7877   // Adjust the bit width of the APSInts.
7878   if (AddendBitWidth > BitWidth) {
7879     Offset = Offset.sext(AddendBitWidth);
7880     BitWidth = AddendBitWidth;
7881   } else if (BitWidth > AddendBitWidth) {
7882     Addend = Addend.sext(BitWidth);
7883   }
7884 
7885   bool Ov = false;
7886   llvm::APSInt ResOffset = Offset;
7887   if (BinOpKind == BO_Add)
7888     ResOffset = Offset.sadd_ov(Addend, Ov);
7889   else {
7890     assert(AddendIsRight && BinOpKind == BO_Sub &&
7891            "operator must be add or sub with addend on the right");
7892     ResOffset = Offset.ssub_ov(Addend, Ov);
7893   }
7894 
7895   // We add an offset to a pointer here so we should support an offset as big as
7896   // possible.
7897   if (Ov) {
7898     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7899            "index (intermediate) result too big");
7900     Offset = Offset.sext(2 * BitWidth);
7901     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7902     return;
7903   }
7904 
7905   Offset = ResOffset;
7906 }
7907 
7908 namespace {
7909 
7910 // This is a wrapper class around StringLiteral to support offsetted string
7911 // literals as format strings. It takes the offset into account when returning
7912 // the string and its length or the source locations to display notes correctly.
7913 class FormatStringLiteral {
7914   const StringLiteral *FExpr;
7915   int64_t Offset;
7916 
7917  public:
7918   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7919       : FExpr(fexpr), Offset(Offset) {}
7920 
7921   StringRef getString() const {
7922     return FExpr->getString().drop_front(Offset);
7923   }
7924 
7925   unsigned getByteLength() const {
7926     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7927   }
7928 
7929   unsigned getLength() const { return FExpr->getLength() - Offset; }
7930   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7931 
7932   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7933 
7934   QualType getType() const { return FExpr->getType(); }
7935 
7936   bool isAscii() const { return FExpr->isAscii(); }
7937   bool isWide() const { return FExpr->isWide(); }
7938   bool isUTF8() const { return FExpr->isUTF8(); }
7939   bool isUTF16() const { return FExpr->isUTF16(); }
7940   bool isUTF32() const { return FExpr->isUTF32(); }
7941   bool isPascal() const { return FExpr->isPascal(); }
7942 
7943   SourceLocation getLocationOfByte(
7944       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7945       const TargetInfo &Target, unsigned *StartToken = nullptr,
7946       unsigned *StartTokenByteOffset = nullptr) const {
7947     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7948                                     StartToken, StartTokenByteOffset);
7949   }
7950 
7951   SourceLocation getBeginLoc() const LLVM_READONLY {
7952     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7953   }
7954 
7955   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7956 };
7957 
7958 }  // namespace
7959 
7960 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7961                               const Expr *OrigFormatExpr,
7962                               ArrayRef<const Expr *> Args,
7963                               bool HasVAListArg, unsigned format_idx,
7964                               unsigned firstDataArg,
7965                               Sema::FormatStringType Type,
7966                               bool inFunctionCall,
7967                               Sema::VariadicCallType CallType,
7968                               llvm::SmallBitVector &CheckedVarArgs,
7969                               UncoveredArgHandler &UncoveredArg,
7970                               bool IgnoreStringsWithoutSpecifiers);
7971 
7972 // Determine if an expression is a string literal or constant string.
7973 // If this function returns false on the arguments to a function expecting a
7974 // format string, we will usually need to emit a warning.
7975 // True string literals are then checked by CheckFormatString.
7976 static StringLiteralCheckType
7977 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7978                       bool HasVAListArg, unsigned format_idx,
7979                       unsigned firstDataArg, Sema::FormatStringType Type,
7980                       Sema::VariadicCallType CallType, bool InFunctionCall,
7981                       llvm::SmallBitVector &CheckedVarArgs,
7982                       UncoveredArgHandler &UncoveredArg,
7983                       llvm::APSInt Offset,
7984                       bool IgnoreStringsWithoutSpecifiers = false) {
7985   if (S.isConstantEvaluated())
7986     return SLCT_NotALiteral;
7987  tryAgain:
7988   assert(Offset.isSigned() && "invalid offset");
7989 
7990   if (E->isTypeDependent() || E->isValueDependent())
7991     return SLCT_NotALiteral;
7992 
7993   E = E->IgnoreParenCasts();
7994 
7995   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7996     // Technically -Wformat-nonliteral does not warn about this case.
7997     // The behavior of printf and friends in this case is implementation
7998     // dependent.  Ideally if the format string cannot be null then
7999     // it should have a 'nonnull' attribute in the function prototype.
8000     return SLCT_UncheckedLiteral;
8001 
8002   switch (E->getStmtClass()) {
8003   case Stmt::BinaryConditionalOperatorClass:
8004   case Stmt::ConditionalOperatorClass: {
8005     // The expression is a literal if both sub-expressions were, and it was
8006     // completely checked only if both sub-expressions were checked.
8007     const AbstractConditionalOperator *C =
8008         cast<AbstractConditionalOperator>(E);
8009 
8010     // Determine whether it is necessary to check both sub-expressions, for
8011     // example, because the condition expression is a constant that can be
8012     // evaluated at compile time.
8013     bool CheckLeft = true, CheckRight = true;
8014 
8015     bool Cond;
8016     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
8017                                                  S.isConstantEvaluated())) {
8018       if (Cond)
8019         CheckRight = false;
8020       else
8021         CheckLeft = false;
8022     }
8023 
8024     // We need to maintain the offsets for the right and the left hand side
8025     // separately to check if every possible indexed expression is a valid
8026     // string literal. They might have different offsets for different string
8027     // literals in the end.
8028     StringLiteralCheckType Left;
8029     if (!CheckLeft)
8030       Left = SLCT_UncheckedLiteral;
8031     else {
8032       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
8033                                    HasVAListArg, format_idx, firstDataArg,
8034                                    Type, CallType, InFunctionCall,
8035                                    CheckedVarArgs, UncoveredArg, Offset,
8036                                    IgnoreStringsWithoutSpecifiers);
8037       if (Left == SLCT_NotALiteral || !CheckRight) {
8038         return Left;
8039       }
8040     }
8041 
8042     StringLiteralCheckType Right = checkFormatStringExpr(
8043         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
8044         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8045         IgnoreStringsWithoutSpecifiers);
8046 
8047     return (CheckLeft && Left < Right) ? Left : Right;
8048   }
8049 
8050   case Stmt::ImplicitCastExprClass:
8051     E = cast<ImplicitCastExpr>(E)->getSubExpr();
8052     goto tryAgain;
8053 
8054   case Stmt::OpaqueValueExprClass:
8055     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
8056       E = src;
8057       goto tryAgain;
8058     }
8059     return SLCT_NotALiteral;
8060 
8061   case Stmt::PredefinedExprClass:
8062     // While __func__, etc., are technically not string literals, they
8063     // cannot contain format specifiers and thus are not a security
8064     // liability.
8065     return SLCT_UncheckedLiteral;
8066 
8067   case Stmt::DeclRefExprClass: {
8068     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8069 
8070     // As an exception, do not flag errors for variables binding to
8071     // const string literals.
8072     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
8073       bool isConstant = false;
8074       QualType T = DR->getType();
8075 
8076       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
8077         isConstant = AT->getElementType().isConstant(S.Context);
8078       } else if (const PointerType *PT = T->getAs<PointerType>()) {
8079         isConstant = T.isConstant(S.Context) &&
8080                      PT->getPointeeType().isConstant(S.Context);
8081       } else if (T->isObjCObjectPointerType()) {
8082         // In ObjC, there is usually no "const ObjectPointer" type,
8083         // so don't check if the pointee type is constant.
8084         isConstant = T.isConstant(S.Context);
8085       }
8086 
8087       if (isConstant) {
8088         if (const Expr *Init = VD->getAnyInitializer()) {
8089           // Look through initializers like const char c[] = { "foo" }
8090           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
8091             if (InitList->isStringLiteralInit())
8092               Init = InitList->getInit(0)->IgnoreParenImpCasts();
8093           }
8094           return checkFormatStringExpr(S, Init, Args,
8095                                        HasVAListArg, format_idx,
8096                                        firstDataArg, Type, CallType,
8097                                        /*InFunctionCall*/ false, CheckedVarArgs,
8098                                        UncoveredArg, Offset);
8099         }
8100       }
8101 
8102       // For vprintf* functions (i.e., HasVAListArg==true), we add a
8103       // special check to see if the format string is a function parameter
8104       // of the function calling the printf function.  If the function
8105       // has an attribute indicating it is a printf-like function, then we
8106       // should suppress warnings concerning non-literals being used in a call
8107       // to a vprintf function.  For example:
8108       //
8109       // void
8110       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
8111       //      va_list ap;
8112       //      va_start(ap, fmt);
8113       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
8114       //      ...
8115       // }
8116       if (HasVAListArg) {
8117         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
8118           if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) {
8119             int PVIndex = PV->getFunctionScopeIndex() + 1;
8120             for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
8121               // adjust for implicit parameter
8122               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
8123                 if (MD->isInstance())
8124                   ++PVIndex;
8125               // We also check if the formats are compatible.
8126               // We can't pass a 'scanf' string to a 'printf' function.
8127               if (PVIndex == PVFormat->getFormatIdx() &&
8128                   Type == S.GetFormatStringType(PVFormat))
8129                 return SLCT_UncheckedLiteral;
8130             }
8131           }
8132         }
8133       }
8134     }
8135 
8136     return SLCT_NotALiteral;
8137   }
8138 
8139   case Stmt::CallExprClass:
8140   case Stmt::CXXMemberCallExprClass: {
8141     const CallExpr *CE = cast<CallExpr>(E);
8142     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
8143       bool IsFirst = true;
8144       StringLiteralCheckType CommonResult;
8145       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
8146         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
8147         StringLiteralCheckType Result = checkFormatStringExpr(
8148             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8149             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8150             IgnoreStringsWithoutSpecifiers);
8151         if (IsFirst) {
8152           CommonResult = Result;
8153           IsFirst = false;
8154         }
8155       }
8156       if (!IsFirst)
8157         return CommonResult;
8158 
8159       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
8160         unsigned BuiltinID = FD->getBuiltinID();
8161         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
8162             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
8163           const Expr *Arg = CE->getArg(0);
8164           return checkFormatStringExpr(S, Arg, Args,
8165                                        HasVAListArg, format_idx,
8166                                        firstDataArg, Type, CallType,
8167                                        InFunctionCall, CheckedVarArgs,
8168                                        UncoveredArg, Offset,
8169                                        IgnoreStringsWithoutSpecifiers);
8170         }
8171       }
8172     }
8173 
8174     return SLCT_NotALiteral;
8175   }
8176   case Stmt::ObjCMessageExprClass: {
8177     const auto *ME = cast<ObjCMessageExpr>(E);
8178     if (const auto *MD = ME->getMethodDecl()) {
8179       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
8180         // As a special case heuristic, if we're using the method -[NSBundle
8181         // localizedStringForKey:value:table:], ignore any key strings that lack
8182         // format specifiers. The idea is that if the key doesn't have any
8183         // format specifiers then its probably just a key to map to the
8184         // localized strings. If it does have format specifiers though, then its
8185         // likely that the text of the key is the format string in the
8186         // programmer's language, and should be checked.
8187         const ObjCInterfaceDecl *IFace;
8188         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
8189             IFace->getIdentifier()->isStr("NSBundle") &&
8190             MD->getSelector().isKeywordSelector(
8191                 {"localizedStringForKey", "value", "table"})) {
8192           IgnoreStringsWithoutSpecifiers = true;
8193         }
8194 
8195         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
8196         return checkFormatStringExpr(
8197             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8198             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8199             IgnoreStringsWithoutSpecifiers);
8200       }
8201     }
8202 
8203     return SLCT_NotALiteral;
8204   }
8205   case Stmt::ObjCStringLiteralClass:
8206   case Stmt::StringLiteralClass: {
8207     const StringLiteral *StrE = nullptr;
8208 
8209     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
8210       StrE = ObjCFExpr->getString();
8211     else
8212       StrE = cast<StringLiteral>(E);
8213 
8214     if (StrE) {
8215       if (Offset.isNegative() || Offset > StrE->getLength()) {
8216         // TODO: It would be better to have an explicit warning for out of
8217         // bounds literals.
8218         return SLCT_NotALiteral;
8219       }
8220       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
8221       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
8222                         firstDataArg, Type, InFunctionCall, CallType,
8223                         CheckedVarArgs, UncoveredArg,
8224                         IgnoreStringsWithoutSpecifiers);
8225       return SLCT_CheckedLiteral;
8226     }
8227 
8228     return SLCT_NotALiteral;
8229   }
8230   case Stmt::BinaryOperatorClass: {
8231     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
8232 
8233     // A string literal + an int offset is still a string literal.
8234     if (BinOp->isAdditiveOp()) {
8235       Expr::EvalResult LResult, RResult;
8236 
8237       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
8238           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8239       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
8240           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8241 
8242       if (LIsInt != RIsInt) {
8243         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
8244 
8245         if (LIsInt) {
8246           if (BinOpKind == BO_Add) {
8247             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
8248             E = BinOp->getRHS();
8249             goto tryAgain;
8250           }
8251         } else {
8252           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
8253           E = BinOp->getLHS();
8254           goto tryAgain;
8255         }
8256       }
8257     }
8258 
8259     return SLCT_NotALiteral;
8260   }
8261   case Stmt::UnaryOperatorClass: {
8262     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
8263     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
8264     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
8265       Expr::EvalResult IndexResult;
8266       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
8267                                        Expr::SE_NoSideEffects,
8268                                        S.isConstantEvaluated())) {
8269         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
8270                    /*RHS is int*/ true);
8271         E = ASE->getBase();
8272         goto tryAgain;
8273       }
8274     }
8275 
8276     return SLCT_NotALiteral;
8277   }
8278 
8279   default:
8280     return SLCT_NotALiteral;
8281   }
8282 }
8283 
8284 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
8285   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
8286       .Case("scanf", FST_Scanf)
8287       .Cases("printf", "printf0", FST_Printf)
8288       .Cases("NSString", "CFString", FST_NSString)
8289       .Case("strftime", FST_Strftime)
8290       .Case("strfmon", FST_Strfmon)
8291       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
8292       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
8293       .Case("os_trace", FST_OSLog)
8294       .Case("os_log", FST_OSLog)
8295       .Default(FST_Unknown);
8296 }
8297 
8298 /// CheckFormatArguments - Check calls to printf and scanf (and similar
8299 /// functions) for correct use of format strings.
8300 /// Returns true if a format string has been fully checked.
8301 bool Sema::CheckFormatArguments(const FormatAttr *Format,
8302                                 ArrayRef<const Expr *> Args,
8303                                 bool IsCXXMember,
8304                                 VariadicCallType CallType,
8305                                 SourceLocation Loc, SourceRange Range,
8306                                 llvm::SmallBitVector &CheckedVarArgs) {
8307   FormatStringInfo FSI;
8308   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
8309     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
8310                                 FSI.FirstDataArg, GetFormatStringType(Format),
8311                                 CallType, Loc, Range, CheckedVarArgs);
8312   return false;
8313 }
8314 
8315 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8316                                 bool HasVAListArg, unsigned format_idx,
8317                                 unsigned firstDataArg, FormatStringType Type,
8318                                 VariadicCallType CallType,
8319                                 SourceLocation Loc, SourceRange Range,
8320                                 llvm::SmallBitVector &CheckedVarArgs) {
8321   // CHECK: printf/scanf-like function is called with no format string.
8322   if (format_idx >= Args.size()) {
8323     Diag(Loc, diag::warn_missing_format_string) << Range;
8324     return false;
8325   }
8326 
8327   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8328 
8329   // CHECK: format string is not a string literal.
8330   //
8331   // Dynamically generated format strings are difficult to
8332   // automatically vet at compile time.  Requiring that format strings
8333   // are string literals: (1) permits the checking of format strings by
8334   // the compiler and thereby (2) can practically remove the source of
8335   // many format string exploits.
8336 
8337   // Format string can be either ObjC string (e.g. @"%d") or
8338   // C string (e.g. "%d")
8339   // ObjC string uses the same format specifiers as C string, so we can use
8340   // the same format string checking logic for both ObjC and C strings.
8341   UncoveredArgHandler UncoveredArg;
8342   StringLiteralCheckType CT =
8343       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8344                             format_idx, firstDataArg, Type, CallType,
8345                             /*IsFunctionCall*/ true, CheckedVarArgs,
8346                             UncoveredArg,
8347                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8348 
8349   // Generate a diagnostic where an uncovered argument is detected.
8350   if (UncoveredArg.hasUncoveredArg()) {
8351     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8352     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8353     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8354   }
8355 
8356   if (CT != SLCT_NotALiteral)
8357     // Literal format string found, check done!
8358     return CT == SLCT_CheckedLiteral;
8359 
8360   // Strftime is particular as it always uses a single 'time' argument,
8361   // so it is safe to pass a non-literal string.
8362   if (Type == FST_Strftime)
8363     return false;
8364 
8365   // Do not emit diag when the string param is a macro expansion and the
8366   // format is either NSString or CFString. This is a hack to prevent
8367   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8368   // which are usually used in place of NS and CF string literals.
8369   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8370   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8371     return false;
8372 
8373   // If there are no arguments specified, warn with -Wformat-security, otherwise
8374   // warn only with -Wformat-nonliteral.
8375   if (Args.size() == firstDataArg) {
8376     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8377       << OrigFormatExpr->getSourceRange();
8378     switch (Type) {
8379     default:
8380       break;
8381     case FST_Kprintf:
8382     case FST_FreeBSDKPrintf:
8383     case FST_Printf:
8384       Diag(FormatLoc, diag::note_format_security_fixit)
8385         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8386       break;
8387     case FST_NSString:
8388       Diag(FormatLoc, diag::note_format_security_fixit)
8389         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8390       break;
8391     }
8392   } else {
8393     Diag(FormatLoc, diag::warn_format_nonliteral)
8394       << OrigFormatExpr->getSourceRange();
8395   }
8396   return false;
8397 }
8398 
8399 namespace {
8400 
8401 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8402 protected:
8403   Sema &S;
8404   const FormatStringLiteral *FExpr;
8405   const Expr *OrigFormatExpr;
8406   const Sema::FormatStringType FSType;
8407   const unsigned FirstDataArg;
8408   const unsigned NumDataArgs;
8409   const char *Beg; // Start of format string.
8410   const bool HasVAListArg;
8411   ArrayRef<const Expr *> Args;
8412   unsigned FormatIdx;
8413   llvm::SmallBitVector CoveredArgs;
8414   bool usesPositionalArgs = false;
8415   bool atFirstArg = true;
8416   bool inFunctionCall;
8417   Sema::VariadicCallType CallType;
8418   llvm::SmallBitVector &CheckedVarArgs;
8419   UncoveredArgHandler &UncoveredArg;
8420 
8421 public:
8422   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8423                      const Expr *origFormatExpr,
8424                      const Sema::FormatStringType type, unsigned firstDataArg,
8425                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8426                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8427                      bool inFunctionCall, Sema::VariadicCallType callType,
8428                      llvm::SmallBitVector &CheckedVarArgs,
8429                      UncoveredArgHandler &UncoveredArg)
8430       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8431         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8432         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8433         inFunctionCall(inFunctionCall), CallType(callType),
8434         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8435     CoveredArgs.resize(numDataArgs);
8436     CoveredArgs.reset();
8437   }
8438 
8439   void DoneProcessing();
8440 
8441   void HandleIncompleteSpecifier(const char *startSpecifier,
8442                                  unsigned specifierLen) override;
8443 
8444   void HandleInvalidLengthModifier(
8445                            const analyze_format_string::FormatSpecifier &FS,
8446                            const analyze_format_string::ConversionSpecifier &CS,
8447                            const char *startSpecifier, unsigned specifierLen,
8448                            unsigned DiagID);
8449 
8450   void HandleNonStandardLengthModifier(
8451                     const analyze_format_string::FormatSpecifier &FS,
8452                     const char *startSpecifier, unsigned specifierLen);
8453 
8454   void HandleNonStandardConversionSpecifier(
8455                     const analyze_format_string::ConversionSpecifier &CS,
8456                     const char *startSpecifier, unsigned specifierLen);
8457 
8458   void HandlePosition(const char *startPos, unsigned posLen) override;
8459 
8460   void HandleInvalidPosition(const char *startSpecifier,
8461                              unsigned specifierLen,
8462                              analyze_format_string::PositionContext p) override;
8463 
8464   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8465 
8466   void HandleNullChar(const char *nullCharacter) override;
8467 
8468   template <typename Range>
8469   static void
8470   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8471                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8472                        bool IsStringLocation, Range StringRange,
8473                        ArrayRef<FixItHint> Fixit = None);
8474 
8475 protected:
8476   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8477                                         const char *startSpec,
8478                                         unsigned specifierLen,
8479                                         const char *csStart, unsigned csLen);
8480 
8481   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8482                                          const char *startSpec,
8483                                          unsigned specifierLen);
8484 
8485   SourceRange getFormatStringRange();
8486   CharSourceRange getSpecifierRange(const char *startSpecifier,
8487                                     unsigned specifierLen);
8488   SourceLocation getLocationOfByte(const char *x);
8489 
8490   const Expr *getDataArg(unsigned i) const;
8491 
8492   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8493                     const analyze_format_string::ConversionSpecifier &CS,
8494                     const char *startSpecifier, unsigned specifierLen,
8495                     unsigned argIndex);
8496 
8497   template <typename Range>
8498   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8499                             bool IsStringLocation, Range StringRange,
8500                             ArrayRef<FixItHint> Fixit = None);
8501 };
8502 
8503 } // namespace
8504 
8505 SourceRange CheckFormatHandler::getFormatStringRange() {
8506   return OrigFormatExpr->getSourceRange();
8507 }
8508 
8509 CharSourceRange CheckFormatHandler::
8510 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8511   SourceLocation Start = getLocationOfByte(startSpecifier);
8512   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8513 
8514   // Advance the end SourceLocation by one due to half-open ranges.
8515   End = End.getLocWithOffset(1);
8516 
8517   return CharSourceRange::getCharRange(Start, End);
8518 }
8519 
8520 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8521   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8522                                   S.getLangOpts(), S.Context.getTargetInfo());
8523 }
8524 
8525 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8526                                                    unsigned specifierLen){
8527   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8528                        getLocationOfByte(startSpecifier),
8529                        /*IsStringLocation*/true,
8530                        getSpecifierRange(startSpecifier, specifierLen));
8531 }
8532 
8533 void CheckFormatHandler::HandleInvalidLengthModifier(
8534     const analyze_format_string::FormatSpecifier &FS,
8535     const analyze_format_string::ConversionSpecifier &CS,
8536     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8537   using namespace analyze_format_string;
8538 
8539   const LengthModifier &LM = FS.getLengthModifier();
8540   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8541 
8542   // See if we know how to fix this length modifier.
8543   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8544   if (FixedLM) {
8545     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8546                          getLocationOfByte(LM.getStart()),
8547                          /*IsStringLocation*/true,
8548                          getSpecifierRange(startSpecifier, specifierLen));
8549 
8550     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8551       << FixedLM->toString()
8552       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8553 
8554   } else {
8555     FixItHint Hint;
8556     if (DiagID == diag::warn_format_nonsensical_length)
8557       Hint = FixItHint::CreateRemoval(LMRange);
8558 
8559     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8560                          getLocationOfByte(LM.getStart()),
8561                          /*IsStringLocation*/true,
8562                          getSpecifierRange(startSpecifier, specifierLen),
8563                          Hint);
8564   }
8565 }
8566 
8567 void CheckFormatHandler::HandleNonStandardLengthModifier(
8568     const analyze_format_string::FormatSpecifier &FS,
8569     const char *startSpecifier, unsigned specifierLen) {
8570   using namespace analyze_format_string;
8571 
8572   const LengthModifier &LM = FS.getLengthModifier();
8573   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8574 
8575   // See if we know how to fix this length modifier.
8576   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8577   if (FixedLM) {
8578     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8579                            << LM.toString() << 0,
8580                          getLocationOfByte(LM.getStart()),
8581                          /*IsStringLocation*/true,
8582                          getSpecifierRange(startSpecifier, specifierLen));
8583 
8584     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8585       << FixedLM->toString()
8586       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8587 
8588   } else {
8589     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8590                            << LM.toString() << 0,
8591                          getLocationOfByte(LM.getStart()),
8592                          /*IsStringLocation*/true,
8593                          getSpecifierRange(startSpecifier, specifierLen));
8594   }
8595 }
8596 
8597 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8598     const analyze_format_string::ConversionSpecifier &CS,
8599     const char *startSpecifier, unsigned specifierLen) {
8600   using namespace analyze_format_string;
8601 
8602   // See if we know how to fix this conversion specifier.
8603   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8604   if (FixedCS) {
8605     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8606                           << CS.toString() << /*conversion specifier*/1,
8607                          getLocationOfByte(CS.getStart()),
8608                          /*IsStringLocation*/true,
8609                          getSpecifierRange(startSpecifier, specifierLen));
8610 
8611     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8612     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8613       << FixedCS->toString()
8614       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8615   } else {
8616     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8617                           << CS.toString() << /*conversion specifier*/1,
8618                          getLocationOfByte(CS.getStart()),
8619                          /*IsStringLocation*/true,
8620                          getSpecifierRange(startSpecifier, specifierLen));
8621   }
8622 }
8623 
8624 void CheckFormatHandler::HandlePosition(const char *startPos,
8625                                         unsigned posLen) {
8626   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8627                                getLocationOfByte(startPos),
8628                                /*IsStringLocation*/true,
8629                                getSpecifierRange(startPos, posLen));
8630 }
8631 
8632 void
8633 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8634                                      analyze_format_string::PositionContext p) {
8635   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8636                          << (unsigned) p,
8637                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8638                        getSpecifierRange(startPos, posLen));
8639 }
8640 
8641 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8642                                             unsigned posLen) {
8643   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8644                                getLocationOfByte(startPos),
8645                                /*IsStringLocation*/true,
8646                                getSpecifierRange(startPos, posLen));
8647 }
8648 
8649 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8650   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8651     // The presence of a null character is likely an error.
8652     EmitFormatDiagnostic(
8653       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8654       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8655       getFormatStringRange());
8656   }
8657 }
8658 
8659 // Note that this may return NULL if there was an error parsing or building
8660 // one of the argument expressions.
8661 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8662   return Args[FirstDataArg + i];
8663 }
8664 
8665 void CheckFormatHandler::DoneProcessing() {
8666   // Does the number of data arguments exceed the number of
8667   // format conversions in the format string?
8668   if (!HasVAListArg) {
8669       // Find any arguments that weren't covered.
8670     CoveredArgs.flip();
8671     signed notCoveredArg = CoveredArgs.find_first();
8672     if (notCoveredArg >= 0) {
8673       assert((unsigned)notCoveredArg < NumDataArgs);
8674       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8675     } else {
8676       UncoveredArg.setAllCovered();
8677     }
8678   }
8679 }
8680 
8681 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8682                                    const Expr *ArgExpr) {
8683   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8684          "Invalid state");
8685 
8686   if (!ArgExpr)
8687     return;
8688 
8689   SourceLocation Loc = ArgExpr->getBeginLoc();
8690 
8691   if (S.getSourceManager().isInSystemMacro(Loc))
8692     return;
8693 
8694   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8695   for (auto E : DiagnosticExprs)
8696     PDiag << E->getSourceRange();
8697 
8698   CheckFormatHandler::EmitFormatDiagnostic(
8699                                   S, IsFunctionCall, DiagnosticExprs[0],
8700                                   PDiag, Loc, /*IsStringLocation*/false,
8701                                   DiagnosticExprs[0]->getSourceRange());
8702 }
8703 
8704 bool
8705 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8706                                                      SourceLocation Loc,
8707                                                      const char *startSpec,
8708                                                      unsigned specifierLen,
8709                                                      const char *csStart,
8710                                                      unsigned csLen) {
8711   bool keepGoing = true;
8712   if (argIndex < NumDataArgs) {
8713     // Consider the argument coverered, even though the specifier doesn't
8714     // make sense.
8715     CoveredArgs.set(argIndex);
8716   }
8717   else {
8718     // If argIndex exceeds the number of data arguments we
8719     // don't issue a warning because that is just a cascade of warnings (and
8720     // they may have intended '%%' anyway). We don't want to continue processing
8721     // the format string after this point, however, as we will like just get
8722     // gibberish when trying to match arguments.
8723     keepGoing = false;
8724   }
8725 
8726   StringRef Specifier(csStart, csLen);
8727 
8728   // If the specifier in non-printable, it could be the first byte of a UTF-8
8729   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8730   // hex value.
8731   std::string CodePointStr;
8732   if (!llvm::sys::locale::isPrint(*csStart)) {
8733     llvm::UTF32 CodePoint;
8734     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8735     const llvm::UTF8 *E =
8736         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8737     llvm::ConversionResult Result =
8738         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8739 
8740     if (Result != llvm::conversionOK) {
8741       unsigned char FirstChar = *csStart;
8742       CodePoint = (llvm::UTF32)FirstChar;
8743     }
8744 
8745     llvm::raw_string_ostream OS(CodePointStr);
8746     if (CodePoint < 256)
8747       OS << "\\x" << llvm::format("%02x", CodePoint);
8748     else if (CodePoint <= 0xFFFF)
8749       OS << "\\u" << llvm::format("%04x", CodePoint);
8750     else
8751       OS << "\\U" << llvm::format("%08x", CodePoint);
8752     OS.flush();
8753     Specifier = CodePointStr;
8754   }
8755 
8756   EmitFormatDiagnostic(
8757       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8758       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8759 
8760   return keepGoing;
8761 }
8762 
8763 void
8764 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8765                                                       const char *startSpec,
8766                                                       unsigned specifierLen) {
8767   EmitFormatDiagnostic(
8768     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8769     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8770 }
8771 
8772 bool
8773 CheckFormatHandler::CheckNumArgs(
8774   const analyze_format_string::FormatSpecifier &FS,
8775   const analyze_format_string::ConversionSpecifier &CS,
8776   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8777 
8778   if (argIndex >= NumDataArgs) {
8779     PartialDiagnostic PDiag = FS.usesPositionalArg()
8780       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8781            << (argIndex+1) << NumDataArgs)
8782       : S.PDiag(diag::warn_printf_insufficient_data_args);
8783     EmitFormatDiagnostic(
8784       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8785       getSpecifierRange(startSpecifier, specifierLen));
8786 
8787     // Since more arguments than conversion tokens are given, by extension
8788     // all arguments are covered, so mark this as so.
8789     UncoveredArg.setAllCovered();
8790     return false;
8791   }
8792   return true;
8793 }
8794 
8795 template<typename Range>
8796 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8797                                               SourceLocation Loc,
8798                                               bool IsStringLocation,
8799                                               Range StringRange,
8800                                               ArrayRef<FixItHint> FixIt) {
8801   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8802                        Loc, IsStringLocation, StringRange, FixIt);
8803 }
8804 
8805 /// If the format string is not within the function call, emit a note
8806 /// so that the function call and string are in diagnostic messages.
8807 ///
8808 /// \param InFunctionCall if true, the format string is within the function
8809 /// call and only one diagnostic message will be produced.  Otherwise, an
8810 /// extra note will be emitted pointing to location of the format string.
8811 ///
8812 /// \param ArgumentExpr the expression that is passed as the format string
8813 /// argument in the function call.  Used for getting locations when two
8814 /// diagnostics are emitted.
8815 ///
8816 /// \param PDiag the callee should already have provided any strings for the
8817 /// diagnostic message.  This function only adds locations and fixits
8818 /// to diagnostics.
8819 ///
8820 /// \param Loc primary location for diagnostic.  If two diagnostics are
8821 /// required, one will be at Loc and a new SourceLocation will be created for
8822 /// the other one.
8823 ///
8824 /// \param IsStringLocation if true, Loc points to the format string should be
8825 /// used for the note.  Otherwise, Loc points to the argument list and will
8826 /// be used with PDiag.
8827 ///
8828 /// \param StringRange some or all of the string to highlight.  This is
8829 /// templated so it can accept either a CharSourceRange or a SourceRange.
8830 ///
8831 /// \param FixIt optional fix it hint for the format string.
8832 template <typename Range>
8833 void CheckFormatHandler::EmitFormatDiagnostic(
8834     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8835     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8836     Range StringRange, ArrayRef<FixItHint> FixIt) {
8837   if (InFunctionCall) {
8838     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8839     D << StringRange;
8840     D << FixIt;
8841   } else {
8842     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8843       << ArgumentExpr->getSourceRange();
8844 
8845     const Sema::SemaDiagnosticBuilder &Note =
8846       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8847              diag::note_format_string_defined);
8848 
8849     Note << StringRange;
8850     Note << FixIt;
8851   }
8852 }
8853 
8854 //===--- CHECK: Printf format string checking ------------------------------===//
8855 
8856 namespace {
8857 
8858 class CheckPrintfHandler : public CheckFormatHandler {
8859 public:
8860   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8861                      const Expr *origFormatExpr,
8862                      const Sema::FormatStringType type, unsigned firstDataArg,
8863                      unsigned numDataArgs, bool isObjC, const char *beg,
8864                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8865                      unsigned formatIdx, bool inFunctionCall,
8866                      Sema::VariadicCallType CallType,
8867                      llvm::SmallBitVector &CheckedVarArgs,
8868                      UncoveredArgHandler &UncoveredArg)
8869       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8870                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8871                            inFunctionCall, CallType, CheckedVarArgs,
8872                            UncoveredArg) {}
8873 
8874   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8875 
8876   /// Returns true if '%@' specifiers are allowed in the format string.
8877   bool allowsObjCArg() const {
8878     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8879            FSType == Sema::FST_OSTrace;
8880   }
8881 
8882   bool HandleInvalidPrintfConversionSpecifier(
8883                                       const analyze_printf::PrintfSpecifier &FS,
8884                                       const char *startSpecifier,
8885                                       unsigned specifierLen) override;
8886 
8887   void handleInvalidMaskType(StringRef MaskType) override;
8888 
8889   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8890                              const char *startSpecifier,
8891                              unsigned specifierLen) override;
8892   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8893                        const char *StartSpecifier,
8894                        unsigned SpecifierLen,
8895                        const Expr *E);
8896 
8897   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8898                     const char *startSpecifier, unsigned specifierLen);
8899   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8900                            const analyze_printf::OptionalAmount &Amt,
8901                            unsigned type,
8902                            const char *startSpecifier, unsigned specifierLen);
8903   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8904                   const analyze_printf::OptionalFlag &flag,
8905                   const char *startSpecifier, unsigned specifierLen);
8906   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8907                          const analyze_printf::OptionalFlag &ignoredFlag,
8908                          const analyze_printf::OptionalFlag &flag,
8909                          const char *startSpecifier, unsigned specifierLen);
8910   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8911                            const Expr *E);
8912 
8913   void HandleEmptyObjCModifierFlag(const char *startFlag,
8914                                    unsigned flagLen) override;
8915 
8916   void HandleInvalidObjCModifierFlag(const char *startFlag,
8917                                             unsigned flagLen) override;
8918 
8919   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8920                                            const char *flagsEnd,
8921                                            const char *conversionPosition)
8922                                              override;
8923 };
8924 
8925 } // namespace
8926 
8927 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8928                                       const analyze_printf::PrintfSpecifier &FS,
8929                                       const char *startSpecifier,
8930                                       unsigned specifierLen) {
8931   const analyze_printf::PrintfConversionSpecifier &CS =
8932     FS.getConversionSpecifier();
8933 
8934   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8935                                           getLocationOfByte(CS.getStart()),
8936                                           startSpecifier, specifierLen,
8937                                           CS.getStart(), CS.getLength());
8938 }
8939 
8940 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8941   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8942 }
8943 
8944 bool CheckPrintfHandler::HandleAmount(
8945                                const analyze_format_string::OptionalAmount &Amt,
8946                                unsigned k, const char *startSpecifier,
8947                                unsigned specifierLen) {
8948   if (Amt.hasDataArgument()) {
8949     if (!HasVAListArg) {
8950       unsigned argIndex = Amt.getArgIndex();
8951       if (argIndex >= NumDataArgs) {
8952         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8953                                << k,
8954                              getLocationOfByte(Amt.getStart()),
8955                              /*IsStringLocation*/true,
8956                              getSpecifierRange(startSpecifier, specifierLen));
8957         // Don't do any more checking.  We will just emit
8958         // spurious errors.
8959         return false;
8960       }
8961 
8962       // Type check the data argument.  It should be an 'int'.
8963       // Although not in conformance with C99, we also allow the argument to be
8964       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8965       // doesn't emit a warning for that case.
8966       CoveredArgs.set(argIndex);
8967       const Expr *Arg = getDataArg(argIndex);
8968       if (!Arg)
8969         return false;
8970 
8971       QualType T = Arg->getType();
8972 
8973       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8974       assert(AT.isValid());
8975 
8976       if (!AT.matchesType(S.Context, T)) {
8977         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8978                                << k << AT.getRepresentativeTypeName(S.Context)
8979                                << T << Arg->getSourceRange(),
8980                              getLocationOfByte(Amt.getStart()),
8981                              /*IsStringLocation*/true,
8982                              getSpecifierRange(startSpecifier, specifierLen));
8983         // Don't do any more checking.  We will just emit
8984         // spurious errors.
8985         return false;
8986       }
8987     }
8988   }
8989   return true;
8990 }
8991 
8992 void CheckPrintfHandler::HandleInvalidAmount(
8993                                       const analyze_printf::PrintfSpecifier &FS,
8994                                       const analyze_printf::OptionalAmount &Amt,
8995                                       unsigned type,
8996                                       const char *startSpecifier,
8997                                       unsigned specifierLen) {
8998   const analyze_printf::PrintfConversionSpecifier &CS =
8999     FS.getConversionSpecifier();
9000 
9001   FixItHint fixit =
9002     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
9003       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
9004                                  Amt.getConstantLength()))
9005       : FixItHint();
9006 
9007   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
9008                          << type << CS.toString(),
9009                        getLocationOfByte(Amt.getStart()),
9010                        /*IsStringLocation*/true,
9011                        getSpecifierRange(startSpecifier, specifierLen),
9012                        fixit);
9013 }
9014 
9015 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
9016                                     const analyze_printf::OptionalFlag &flag,
9017                                     const char *startSpecifier,
9018                                     unsigned specifierLen) {
9019   // Warn about pointless flag with a fixit removal.
9020   const analyze_printf::PrintfConversionSpecifier &CS =
9021     FS.getConversionSpecifier();
9022   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
9023                          << flag.toString() << CS.toString(),
9024                        getLocationOfByte(flag.getPosition()),
9025                        /*IsStringLocation*/true,
9026                        getSpecifierRange(startSpecifier, specifierLen),
9027                        FixItHint::CreateRemoval(
9028                          getSpecifierRange(flag.getPosition(), 1)));
9029 }
9030 
9031 void CheckPrintfHandler::HandleIgnoredFlag(
9032                                 const analyze_printf::PrintfSpecifier &FS,
9033                                 const analyze_printf::OptionalFlag &ignoredFlag,
9034                                 const analyze_printf::OptionalFlag &flag,
9035                                 const char *startSpecifier,
9036                                 unsigned specifierLen) {
9037   // Warn about ignored flag with a fixit removal.
9038   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
9039                          << ignoredFlag.toString() << flag.toString(),
9040                        getLocationOfByte(ignoredFlag.getPosition()),
9041                        /*IsStringLocation*/true,
9042                        getSpecifierRange(startSpecifier, specifierLen),
9043                        FixItHint::CreateRemoval(
9044                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
9045 }
9046 
9047 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
9048                                                      unsigned flagLen) {
9049   // Warn about an empty flag.
9050   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
9051                        getLocationOfByte(startFlag),
9052                        /*IsStringLocation*/true,
9053                        getSpecifierRange(startFlag, flagLen));
9054 }
9055 
9056 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
9057                                                        unsigned flagLen) {
9058   // Warn about an invalid flag.
9059   auto Range = getSpecifierRange(startFlag, flagLen);
9060   StringRef flag(startFlag, flagLen);
9061   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
9062                       getLocationOfByte(startFlag),
9063                       /*IsStringLocation*/true,
9064                       Range, FixItHint::CreateRemoval(Range));
9065 }
9066 
9067 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
9068     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
9069     // Warn about using '[...]' without a '@' conversion.
9070     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
9071     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
9072     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
9073                          getLocationOfByte(conversionPosition),
9074                          /*IsStringLocation*/true,
9075                          Range, FixItHint::CreateRemoval(Range));
9076 }
9077 
9078 // Determines if the specified is a C++ class or struct containing
9079 // a member with the specified name and kind (e.g. a CXXMethodDecl named
9080 // "c_str()").
9081 template<typename MemberKind>
9082 static llvm::SmallPtrSet<MemberKind*, 1>
9083 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9084   const RecordType *RT = Ty->getAs<RecordType>();
9085   llvm::SmallPtrSet<MemberKind*, 1> Results;
9086 
9087   if (!RT)
9088     return Results;
9089   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
9090   if (!RD || !RD->getDefinition())
9091     return Results;
9092 
9093   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9094                  Sema::LookupMemberName);
9095   R.suppressDiagnostics();
9096 
9097   // We just need to include all members of the right kind turned up by the
9098   // filter, at this point.
9099   if (S.LookupQualifiedName(R, RT->getDecl()))
9100     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9101       NamedDecl *decl = (*I)->getUnderlyingDecl();
9102       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9103         Results.insert(FK);
9104     }
9105   return Results;
9106 }
9107 
9108 /// Check if we could call '.c_str()' on an object.
9109 ///
9110 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9111 /// allow the call, or if it would be ambiguous).
9112 bool Sema::hasCStrMethod(const Expr *E) {
9113   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9114 
9115   MethodSet Results =
9116       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
9117   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9118        MI != ME; ++MI)
9119     if ((*MI)->getMinRequiredArguments() == 0)
9120       return true;
9121   return false;
9122 }
9123 
9124 // Check if a (w)string was passed when a (w)char* was needed, and offer a
9125 // better diagnostic if so. AT is assumed to be valid.
9126 // Returns true when a c_str() conversion method is found.
9127 bool CheckPrintfHandler::checkForCStrMembers(
9128     const analyze_printf::ArgType &AT, const Expr *E) {
9129   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9130 
9131   MethodSet Results =
9132       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
9133 
9134   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9135        MI != ME; ++MI) {
9136     const CXXMethodDecl *Method = *MI;
9137     if (Method->getMinRequiredArguments() == 0 &&
9138         AT.matchesType(S.Context, Method->getReturnType())) {
9139       // FIXME: Suggest parens if the expression needs them.
9140       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
9141       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
9142           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
9143       return true;
9144     }
9145   }
9146 
9147   return false;
9148 }
9149 
9150 bool
9151 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
9152                                             &FS,
9153                                           const char *startSpecifier,
9154                                           unsigned specifierLen) {
9155   using namespace analyze_format_string;
9156   using namespace analyze_printf;
9157 
9158   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9159 
9160   if (FS.consumesDataArgument()) {
9161     if (atFirstArg) {
9162         atFirstArg = false;
9163         usesPositionalArgs = FS.usesPositionalArg();
9164     }
9165     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9166       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9167                                         startSpecifier, specifierLen);
9168       return false;
9169     }
9170   }
9171 
9172   // First check if the field width, precision, and conversion specifier
9173   // have matching data arguments.
9174   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
9175                     startSpecifier, specifierLen)) {
9176     return false;
9177   }
9178 
9179   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
9180                     startSpecifier, specifierLen)) {
9181     return false;
9182   }
9183 
9184   if (!CS.consumesDataArgument()) {
9185     // FIXME: Technically specifying a precision or field width here
9186     // makes no sense.  Worth issuing a warning at some point.
9187     return true;
9188   }
9189 
9190   // Consume the argument.
9191   unsigned argIndex = FS.getArgIndex();
9192   if (argIndex < NumDataArgs) {
9193     // The check to see if the argIndex is valid will come later.
9194     // We set the bit here because we may exit early from this
9195     // function if we encounter some other error.
9196     CoveredArgs.set(argIndex);
9197   }
9198 
9199   // FreeBSD kernel extensions.
9200   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9201       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9202     // We need at least two arguments.
9203     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9204       return false;
9205 
9206     // Claim the second argument.
9207     CoveredArgs.set(argIndex + 1);
9208 
9209     // Type check the first argument (int for %b, pointer for %D)
9210     const Expr *Ex = getDataArg(argIndex);
9211     const analyze_printf::ArgType &AT =
9212       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
9213         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
9214     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9215       EmitFormatDiagnostic(
9216           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9217               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9218               << false << Ex->getSourceRange(),
9219           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9220           getSpecifierRange(startSpecifier, specifierLen));
9221 
9222     // Type check the second argument (char * for both %b and %D)
9223     Ex = getDataArg(argIndex + 1);
9224     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
9225     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9226       EmitFormatDiagnostic(
9227           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9228               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9229               << false << Ex->getSourceRange(),
9230           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9231           getSpecifierRange(startSpecifier, specifierLen));
9232 
9233      return true;
9234   }
9235 
9236   // Check for using an Objective-C specific conversion specifier
9237   // in a non-ObjC literal.
9238   if (!allowsObjCArg() && CS.isObjCArg()) {
9239     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9240                                                   specifierLen);
9241   }
9242 
9243   // %P can only be used with os_log.
9244   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
9245     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9246                                                   specifierLen);
9247   }
9248 
9249   // %n is not allowed with os_log.
9250   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
9251     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9252                          getLocationOfByte(CS.getStart()),
9253                          /*IsStringLocation*/ false,
9254                          getSpecifierRange(startSpecifier, specifierLen));
9255 
9256     return true;
9257   }
9258 
9259   // Only scalars are allowed for os_trace.
9260   if (FSType == Sema::FST_OSTrace &&
9261       (CS.getKind() == ConversionSpecifier::PArg ||
9262        CS.getKind() == ConversionSpecifier::sArg ||
9263        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9264     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9265                                                   specifierLen);
9266   }
9267 
9268   // Check for use of public/private annotation outside of os_log().
9269   if (FSType != Sema::FST_OSLog) {
9270     if (FS.isPublic().isSet()) {
9271       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9272                                << "public",
9273                            getLocationOfByte(FS.isPublic().getPosition()),
9274                            /*IsStringLocation*/ false,
9275                            getSpecifierRange(startSpecifier, specifierLen));
9276     }
9277     if (FS.isPrivate().isSet()) {
9278       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9279                                << "private",
9280                            getLocationOfByte(FS.isPrivate().getPosition()),
9281                            /*IsStringLocation*/ false,
9282                            getSpecifierRange(startSpecifier, specifierLen));
9283     }
9284   }
9285 
9286   // Check for invalid use of field width
9287   if (!FS.hasValidFieldWidth()) {
9288     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9289         startSpecifier, specifierLen);
9290   }
9291 
9292   // Check for invalid use of precision
9293   if (!FS.hasValidPrecision()) {
9294     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9295         startSpecifier, specifierLen);
9296   }
9297 
9298   // Precision is mandatory for %P specifier.
9299   if (CS.getKind() == ConversionSpecifier::PArg &&
9300       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9301     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9302                          getLocationOfByte(startSpecifier),
9303                          /*IsStringLocation*/ false,
9304                          getSpecifierRange(startSpecifier, specifierLen));
9305   }
9306 
9307   // Check each flag does not conflict with any other component.
9308   if (!FS.hasValidThousandsGroupingPrefix())
9309     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9310   if (!FS.hasValidLeadingZeros())
9311     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9312   if (!FS.hasValidPlusPrefix())
9313     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9314   if (!FS.hasValidSpacePrefix())
9315     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9316   if (!FS.hasValidAlternativeForm())
9317     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9318   if (!FS.hasValidLeftJustified())
9319     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9320 
9321   // Check that flags are not ignored by another flag
9322   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9323     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9324         startSpecifier, specifierLen);
9325   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9326     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9327             startSpecifier, specifierLen);
9328 
9329   // Check the length modifier is valid with the given conversion specifier.
9330   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9331                                  S.getLangOpts()))
9332     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9333                                 diag::warn_format_nonsensical_length);
9334   else if (!FS.hasStandardLengthModifier())
9335     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9336   else if (!FS.hasStandardLengthConversionCombination())
9337     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9338                                 diag::warn_format_non_standard_conversion_spec);
9339 
9340   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9341     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9342 
9343   // The remaining checks depend on the data arguments.
9344   if (HasVAListArg)
9345     return true;
9346 
9347   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9348     return false;
9349 
9350   const Expr *Arg = getDataArg(argIndex);
9351   if (!Arg)
9352     return true;
9353 
9354   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9355 }
9356 
9357 static bool requiresParensToAddCast(const Expr *E) {
9358   // FIXME: We should have a general way to reason about operator
9359   // precedence and whether parens are actually needed here.
9360   // Take care of a few common cases where they aren't.
9361   const Expr *Inside = E->IgnoreImpCasts();
9362   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9363     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9364 
9365   switch (Inside->getStmtClass()) {
9366   case Stmt::ArraySubscriptExprClass:
9367   case Stmt::CallExprClass:
9368   case Stmt::CharacterLiteralClass:
9369   case Stmt::CXXBoolLiteralExprClass:
9370   case Stmt::DeclRefExprClass:
9371   case Stmt::FloatingLiteralClass:
9372   case Stmt::IntegerLiteralClass:
9373   case Stmt::MemberExprClass:
9374   case Stmt::ObjCArrayLiteralClass:
9375   case Stmt::ObjCBoolLiteralExprClass:
9376   case Stmt::ObjCBoxedExprClass:
9377   case Stmt::ObjCDictionaryLiteralClass:
9378   case Stmt::ObjCEncodeExprClass:
9379   case Stmt::ObjCIvarRefExprClass:
9380   case Stmt::ObjCMessageExprClass:
9381   case Stmt::ObjCPropertyRefExprClass:
9382   case Stmt::ObjCStringLiteralClass:
9383   case Stmt::ObjCSubscriptRefExprClass:
9384   case Stmt::ParenExprClass:
9385   case Stmt::StringLiteralClass:
9386   case Stmt::UnaryOperatorClass:
9387     return false;
9388   default:
9389     return true;
9390   }
9391 }
9392 
9393 static std::pair<QualType, StringRef>
9394 shouldNotPrintDirectly(const ASTContext &Context,
9395                        QualType IntendedTy,
9396                        const Expr *E) {
9397   // Use a 'while' to peel off layers of typedefs.
9398   QualType TyTy = IntendedTy;
9399   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9400     StringRef Name = UserTy->getDecl()->getName();
9401     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9402       .Case("CFIndex", Context.getNSIntegerType())
9403       .Case("NSInteger", Context.getNSIntegerType())
9404       .Case("NSUInteger", Context.getNSUIntegerType())
9405       .Case("SInt32", Context.IntTy)
9406       .Case("UInt32", Context.UnsignedIntTy)
9407       .Default(QualType());
9408 
9409     if (!CastTy.isNull())
9410       return std::make_pair(CastTy, Name);
9411 
9412     TyTy = UserTy->desugar();
9413   }
9414 
9415   // Strip parens if necessary.
9416   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9417     return shouldNotPrintDirectly(Context,
9418                                   PE->getSubExpr()->getType(),
9419                                   PE->getSubExpr());
9420 
9421   // If this is a conditional expression, then its result type is constructed
9422   // via usual arithmetic conversions and thus there might be no necessary
9423   // typedef sugar there.  Recurse to operands to check for NSInteger &
9424   // Co. usage condition.
9425   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9426     QualType TrueTy, FalseTy;
9427     StringRef TrueName, FalseName;
9428 
9429     std::tie(TrueTy, TrueName) =
9430       shouldNotPrintDirectly(Context,
9431                              CO->getTrueExpr()->getType(),
9432                              CO->getTrueExpr());
9433     std::tie(FalseTy, FalseName) =
9434       shouldNotPrintDirectly(Context,
9435                              CO->getFalseExpr()->getType(),
9436                              CO->getFalseExpr());
9437 
9438     if (TrueTy == FalseTy)
9439       return std::make_pair(TrueTy, TrueName);
9440     else if (TrueTy.isNull())
9441       return std::make_pair(FalseTy, FalseName);
9442     else if (FalseTy.isNull())
9443       return std::make_pair(TrueTy, TrueName);
9444   }
9445 
9446   return std::make_pair(QualType(), StringRef());
9447 }
9448 
9449 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9450 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9451 /// type do not count.
9452 static bool
9453 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9454   QualType From = ICE->getSubExpr()->getType();
9455   QualType To = ICE->getType();
9456   // It's an integer promotion if the destination type is the promoted
9457   // source type.
9458   if (ICE->getCastKind() == CK_IntegralCast &&
9459       From->isPromotableIntegerType() &&
9460       S.Context.getPromotedIntegerType(From) == To)
9461     return true;
9462   // Look through vector types, since we do default argument promotion for
9463   // those in OpenCL.
9464   if (const auto *VecTy = From->getAs<ExtVectorType>())
9465     From = VecTy->getElementType();
9466   if (const auto *VecTy = To->getAs<ExtVectorType>())
9467     To = VecTy->getElementType();
9468   // It's a floating promotion if the source type is a lower rank.
9469   return ICE->getCastKind() == CK_FloatingCast &&
9470          S.Context.getFloatingTypeOrder(From, To) < 0;
9471 }
9472 
9473 bool
9474 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9475                                     const char *StartSpecifier,
9476                                     unsigned SpecifierLen,
9477                                     const Expr *E) {
9478   using namespace analyze_format_string;
9479   using namespace analyze_printf;
9480 
9481   // Now type check the data expression that matches the
9482   // format specifier.
9483   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9484   if (!AT.isValid())
9485     return true;
9486 
9487   QualType ExprTy = E->getType();
9488   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9489     ExprTy = TET->getUnderlyingExpr()->getType();
9490   }
9491 
9492   // Diagnose attempts to print a boolean value as a character. Unlike other
9493   // -Wformat diagnostics, this is fine from a type perspective, but it still
9494   // doesn't make sense.
9495   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9496       E->isKnownToHaveBooleanValue()) {
9497     const CharSourceRange &CSR =
9498         getSpecifierRange(StartSpecifier, SpecifierLen);
9499     SmallString<4> FSString;
9500     llvm::raw_svector_ostream os(FSString);
9501     FS.toString(os);
9502     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9503                              << FSString,
9504                          E->getExprLoc(), false, CSR);
9505     return true;
9506   }
9507 
9508   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9509   if (Match == analyze_printf::ArgType::Match)
9510     return true;
9511 
9512   // Look through argument promotions for our error message's reported type.
9513   // This includes the integral and floating promotions, but excludes array
9514   // and function pointer decay (seeing that an argument intended to be a
9515   // string has type 'char [6]' is probably more confusing than 'char *') and
9516   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9517   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9518     if (isArithmeticArgumentPromotion(S, ICE)) {
9519       E = ICE->getSubExpr();
9520       ExprTy = E->getType();
9521 
9522       // Check if we didn't match because of an implicit cast from a 'char'
9523       // or 'short' to an 'int'.  This is done because printf is a varargs
9524       // function.
9525       if (ICE->getType() == S.Context.IntTy ||
9526           ICE->getType() == S.Context.UnsignedIntTy) {
9527         // All further checking is done on the subexpression
9528         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9529             AT.matchesType(S.Context, ExprTy);
9530         if (ImplicitMatch == analyze_printf::ArgType::Match)
9531           return true;
9532         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9533             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9534           Match = ImplicitMatch;
9535       }
9536     }
9537   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9538     // Special case for 'a', which has type 'int' in C.
9539     // Note, however, that we do /not/ want to treat multibyte constants like
9540     // 'MooV' as characters! This form is deprecated but still exists. In
9541     // addition, don't treat expressions as of type 'char' if one byte length
9542     // modifier is provided.
9543     if (ExprTy == S.Context.IntTy &&
9544         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9545       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9546         ExprTy = S.Context.CharTy;
9547   }
9548 
9549   // Look through enums to their underlying type.
9550   bool IsEnum = false;
9551   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9552     ExprTy = EnumTy->getDecl()->getIntegerType();
9553     IsEnum = true;
9554   }
9555 
9556   // %C in an Objective-C context prints a unichar, not a wchar_t.
9557   // If the argument is an integer of some kind, believe the %C and suggest
9558   // a cast instead of changing the conversion specifier.
9559   QualType IntendedTy = ExprTy;
9560   if (isObjCContext() &&
9561       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9562     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9563         !ExprTy->isCharType()) {
9564       // 'unichar' is defined as a typedef of unsigned short, but we should
9565       // prefer using the typedef if it is visible.
9566       IntendedTy = S.Context.UnsignedShortTy;
9567 
9568       // While we are here, check if the value is an IntegerLiteral that happens
9569       // to be within the valid range.
9570       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9571         const llvm::APInt &V = IL->getValue();
9572         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9573           return true;
9574       }
9575 
9576       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9577                           Sema::LookupOrdinaryName);
9578       if (S.LookupName(Result, S.getCurScope())) {
9579         NamedDecl *ND = Result.getFoundDecl();
9580         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9581           if (TD->getUnderlyingType() == IntendedTy)
9582             IntendedTy = S.Context.getTypedefType(TD);
9583       }
9584     }
9585   }
9586 
9587   // Special-case some of Darwin's platform-independence types by suggesting
9588   // casts to primitive types that are known to be large enough.
9589   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9590   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9591     QualType CastTy;
9592     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9593     if (!CastTy.isNull()) {
9594       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9595       // (long in ASTContext). Only complain to pedants.
9596       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9597           (AT.isSizeT() || AT.isPtrdiffT()) &&
9598           AT.matchesType(S.Context, CastTy))
9599         Match = ArgType::NoMatchPedantic;
9600       IntendedTy = CastTy;
9601       ShouldNotPrintDirectly = true;
9602     }
9603   }
9604 
9605   // We may be able to offer a FixItHint if it is a supported type.
9606   PrintfSpecifier fixedFS = FS;
9607   bool Success =
9608       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9609 
9610   if (Success) {
9611     // Get the fix string from the fixed format specifier
9612     SmallString<16> buf;
9613     llvm::raw_svector_ostream os(buf);
9614     fixedFS.toString(os);
9615 
9616     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9617 
9618     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9619       unsigned Diag;
9620       switch (Match) {
9621       case ArgType::Match: llvm_unreachable("expected non-matching");
9622       case ArgType::NoMatchPedantic:
9623         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9624         break;
9625       case ArgType::NoMatchTypeConfusion:
9626         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9627         break;
9628       case ArgType::NoMatch:
9629         Diag = diag::warn_format_conversion_argument_type_mismatch;
9630         break;
9631       }
9632 
9633       // In this case, the specifier is wrong and should be changed to match
9634       // the argument.
9635       EmitFormatDiagnostic(S.PDiag(Diag)
9636                                << AT.getRepresentativeTypeName(S.Context)
9637                                << IntendedTy << IsEnum << E->getSourceRange(),
9638                            E->getBeginLoc(),
9639                            /*IsStringLocation*/ false, SpecRange,
9640                            FixItHint::CreateReplacement(SpecRange, os.str()));
9641     } else {
9642       // The canonical type for formatting this value is different from the
9643       // actual type of the expression. (This occurs, for example, with Darwin's
9644       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9645       // should be printed as 'long' for 64-bit compatibility.)
9646       // Rather than emitting a normal format/argument mismatch, we want to
9647       // add a cast to the recommended type (and correct the format string
9648       // if necessary).
9649       SmallString<16> CastBuf;
9650       llvm::raw_svector_ostream CastFix(CastBuf);
9651       CastFix << "(";
9652       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9653       CastFix << ")";
9654 
9655       SmallVector<FixItHint,4> Hints;
9656       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9657         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9658 
9659       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9660         // If there's already a cast present, just replace it.
9661         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9662         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9663 
9664       } else if (!requiresParensToAddCast(E)) {
9665         // If the expression has high enough precedence,
9666         // just write the C-style cast.
9667         Hints.push_back(
9668             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9669       } else {
9670         // Otherwise, add parens around the expression as well as the cast.
9671         CastFix << "(";
9672         Hints.push_back(
9673             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9674 
9675         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9676         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9677       }
9678 
9679       if (ShouldNotPrintDirectly) {
9680         // The expression has a type that should not be printed directly.
9681         // We extract the name from the typedef because we don't want to show
9682         // the underlying type in the diagnostic.
9683         StringRef Name;
9684         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9685           Name = TypedefTy->getDecl()->getName();
9686         else
9687           Name = CastTyName;
9688         unsigned Diag = Match == ArgType::NoMatchPedantic
9689                             ? diag::warn_format_argument_needs_cast_pedantic
9690                             : diag::warn_format_argument_needs_cast;
9691         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9692                                            << E->getSourceRange(),
9693                              E->getBeginLoc(), /*IsStringLocation=*/false,
9694                              SpecRange, Hints);
9695       } else {
9696         // In this case, the expression could be printed using a different
9697         // specifier, but we've decided that the specifier is probably correct
9698         // and we should cast instead. Just use the normal warning message.
9699         EmitFormatDiagnostic(
9700             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9701                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9702                 << E->getSourceRange(),
9703             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9704       }
9705     }
9706   } else {
9707     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9708                                                    SpecifierLen);
9709     // Since the warning for passing non-POD types to variadic functions
9710     // was deferred until now, we emit a warning for non-POD
9711     // arguments here.
9712     switch (S.isValidVarArgType(ExprTy)) {
9713     case Sema::VAK_Valid:
9714     case Sema::VAK_ValidInCXX11: {
9715       unsigned Diag;
9716       switch (Match) {
9717       case ArgType::Match: llvm_unreachable("expected non-matching");
9718       case ArgType::NoMatchPedantic:
9719         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9720         break;
9721       case ArgType::NoMatchTypeConfusion:
9722         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9723         break;
9724       case ArgType::NoMatch:
9725         Diag = diag::warn_format_conversion_argument_type_mismatch;
9726         break;
9727       }
9728 
9729       EmitFormatDiagnostic(
9730           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9731                         << IsEnum << CSR << E->getSourceRange(),
9732           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9733       break;
9734     }
9735     case Sema::VAK_Undefined:
9736     case Sema::VAK_MSVCUndefined:
9737       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9738                                << S.getLangOpts().CPlusPlus11 << ExprTy
9739                                << CallType
9740                                << AT.getRepresentativeTypeName(S.Context) << CSR
9741                                << E->getSourceRange(),
9742                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9743       checkForCStrMembers(AT, E);
9744       break;
9745 
9746     case Sema::VAK_Invalid:
9747       if (ExprTy->isObjCObjectType())
9748         EmitFormatDiagnostic(
9749             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9750                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9751                 << AT.getRepresentativeTypeName(S.Context) << CSR
9752                 << E->getSourceRange(),
9753             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9754       else
9755         // FIXME: If this is an initializer list, suggest removing the braces
9756         // or inserting a cast to the target type.
9757         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9758             << isa<InitListExpr>(E) << ExprTy << CallType
9759             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9760       break;
9761     }
9762 
9763     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9764            "format string specifier index out of range");
9765     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9766   }
9767 
9768   return true;
9769 }
9770 
9771 //===--- CHECK: Scanf format string checking ------------------------------===//
9772 
9773 namespace {
9774 
9775 class CheckScanfHandler : public CheckFormatHandler {
9776 public:
9777   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9778                     const Expr *origFormatExpr, Sema::FormatStringType type,
9779                     unsigned firstDataArg, unsigned numDataArgs,
9780                     const char *beg, bool hasVAListArg,
9781                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9782                     bool inFunctionCall, Sema::VariadicCallType CallType,
9783                     llvm::SmallBitVector &CheckedVarArgs,
9784                     UncoveredArgHandler &UncoveredArg)
9785       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9786                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9787                            inFunctionCall, CallType, CheckedVarArgs,
9788                            UncoveredArg) {}
9789 
9790   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9791                             const char *startSpecifier,
9792                             unsigned specifierLen) override;
9793 
9794   bool HandleInvalidScanfConversionSpecifier(
9795           const analyze_scanf::ScanfSpecifier &FS,
9796           const char *startSpecifier,
9797           unsigned specifierLen) override;
9798 
9799   void HandleIncompleteScanList(const char *start, const char *end) override;
9800 };
9801 
9802 } // namespace
9803 
9804 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9805                                                  const char *end) {
9806   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9807                        getLocationOfByte(end), /*IsStringLocation*/true,
9808                        getSpecifierRange(start, end - start));
9809 }
9810 
9811 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9812                                         const analyze_scanf::ScanfSpecifier &FS,
9813                                         const char *startSpecifier,
9814                                         unsigned specifierLen) {
9815   const analyze_scanf::ScanfConversionSpecifier &CS =
9816     FS.getConversionSpecifier();
9817 
9818   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9819                                           getLocationOfByte(CS.getStart()),
9820                                           startSpecifier, specifierLen,
9821                                           CS.getStart(), CS.getLength());
9822 }
9823 
9824 bool CheckScanfHandler::HandleScanfSpecifier(
9825                                        const analyze_scanf::ScanfSpecifier &FS,
9826                                        const char *startSpecifier,
9827                                        unsigned specifierLen) {
9828   using namespace analyze_scanf;
9829   using namespace analyze_format_string;
9830 
9831   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9832 
9833   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9834   // be used to decide if we are using positional arguments consistently.
9835   if (FS.consumesDataArgument()) {
9836     if (atFirstArg) {
9837       atFirstArg = false;
9838       usesPositionalArgs = FS.usesPositionalArg();
9839     }
9840     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9841       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9842                                         startSpecifier, specifierLen);
9843       return false;
9844     }
9845   }
9846 
9847   // Check if the field with is non-zero.
9848   const OptionalAmount &Amt = FS.getFieldWidth();
9849   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9850     if (Amt.getConstantAmount() == 0) {
9851       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9852                                                    Amt.getConstantLength());
9853       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9854                            getLocationOfByte(Amt.getStart()),
9855                            /*IsStringLocation*/true, R,
9856                            FixItHint::CreateRemoval(R));
9857     }
9858   }
9859 
9860   if (!FS.consumesDataArgument()) {
9861     // FIXME: Technically specifying a precision or field width here
9862     // makes no sense.  Worth issuing a warning at some point.
9863     return true;
9864   }
9865 
9866   // Consume the argument.
9867   unsigned argIndex = FS.getArgIndex();
9868   if (argIndex < NumDataArgs) {
9869       // The check to see if the argIndex is valid will come later.
9870       // We set the bit here because we may exit early from this
9871       // function if we encounter some other error.
9872     CoveredArgs.set(argIndex);
9873   }
9874 
9875   // Check the length modifier is valid with the given conversion specifier.
9876   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9877                                  S.getLangOpts()))
9878     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9879                                 diag::warn_format_nonsensical_length);
9880   else if (!FS.hasStandardLengthModifier())
9881     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9882   else if (!FS.hasStandardLengthConversionCombination())
9883     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9884                                 diag::warn_format_non_standard_conversion_spec);
9885 
9886   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9887     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9888 
9889   // The remaining checks depend on the data arguments.
9890   if (HasVAListArg)
9891     return true;
9892 
9893   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9894     return false;
9895 
9896   // Check that the argument type matches the format specifier.
9897   const Expr *Ex = getDataArg(argIndex);
9898   if (!Ex)
9899     return true;
9900 
9901   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9902 
9903   if (!AT.isValid()) {
9904     return true;
9905   }
9906 
9907   analyze_format_string::ArgType::MatchKind Match =
9908       AT.matchesType(S.Context, Ex->getType());
9909   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9910   if (Match == analyze_format_string::ArgType::Match)
9911     return true;
9912 
9913   ScanfSpecifier fixedFS = FS;
9914   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9915                                  S.getLangOpts(), S.Context);
9916 
9917   unsigned Diag =
9918       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9919                : diag::warn_format_conversion_argument_type_mismatch;
9920 
9921   if (Success) {
9922     // Get the fix string from the fixed format specifier.
9923     SmallString<128> buf;
9924     llvm::raw_svector_ostream os(buf);
9925     fixedFS.toString(os);
9926 
9927     EmitFormatDiagnostic(
9928         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9929                       << Ex->getType() << false << Ex->getSourceRange(),
9930         Ex->getBeginLoc(),
9931         /*IsStringLocation*/ false,
9932         getSpecifierRange(startSpecifier, specifierLen),
9933         FixItHint::CreateReplacement(
9934             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9935   } else {
9936     EmitFormatDiagnostic(S.PDiag(Diag)
9937                              << AT.getRepresentativeTypeName(S.Context)
9938                              << Ex->getType() << false << Ex->getSourceRange(),
9939                          Ex->getBeginLoc(),
9940                          /*IsStringLocation*/ false,
9941                          getSpecifierRange(startSpecifier, specifierLen));
9942   }
9943 
9944   return true;
9945 }
9946 
9947 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9948                               const Expr *OrigFormatExpr,
9949                               ArrayRef<const Expr *> Args,
9950                               bool HasVAListArg, unsigned format_idx,
9951                               unsigned firstDataArg,
9952                               Sema::FormatStringType Type,
9953                               bool inFunctionCall,
9954                               Sema::VariadicCallType CallType,
9955                               llvm::SmallBitVector &CheckedVarArgs,
9956                               UncoveredArgHandler &UncoveredArg,
9957                               bool IgnoreStringsWithoutSpecifiers) {
9958   // CHECK: is the format string a wide literal?
9959   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9960     CheckFormatHandler::EmitFormatDiagnostic(
9961         S, inFunctionCall, Args[format_idx],
9962         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9963         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9964     return;
9965   }
9966 
9967   // Str - The format string.  NOTE: this is NOT null-terminated!
9968   StringRef StrRef = FExpr->getString();
9969   const char *Str = StrRef.data();
9970   // Account for cases where the string literal is truncated in a declaration.
9971   const ConstantArrayType *T =
9972     S.Context.getAsConstantArrayType(FExpr->getType());
9973   assert(T && "String literal not of constant array type!");
9974   size_t TypeSize = T->getSize().getZExtValue();
9975   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9976   const unsigned numDataArgs = Args.size() - firstDataArg;
9977 
9978   if (IgnoreStringsWithoutSpecifiers &&
9979       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9980           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9981     return;
9982 
9983   // Emit a warning if the string literal is truncated and does not contain an
9984   // embedded null character.
9985   if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9986     CheckFormatHandler::EmitFormatDiagnostic(
9987         S, inFunctionCall, Args[format_idx],
9988         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9989         FExpr->getBeginLoc(),
9990         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9991     return;
9992   }
9993 
9994   // CHECK: empty format string?
9995   if (StrLen == 0 && numDataArgs > 0) {
9996     CheckFormatHandler::EmitFormatDiagnostic(
9997         S, inFunctionCall, Args[format_idx],
9998         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9999         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10000     return;
10001   }
10002 
10003   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
10004       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
10005       Type == Sema::FST_OSTrace) {
10006     CheckPrintfHandler H(
10007         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
10008         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
10009         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
10010         CheckedVarArgs, UncoveredArg);
10011 
10012     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
10013                                                   S.getLangOpts(),
10014                                                   S.Context.getTargetInfo(),
10015                                             Type == Sema::FST_FreeBSDKPrintf))
10016       H.DoneProcessing();
10017   } else if (Type == Sema::FST_Scanf) {
10018     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10019                         numDataArgs, Str, HasVAListArg, Args, format_idx,
10020                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
10021 
10022     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
10023                                                  S.getLangOpts(),
10024                                                  S.Context.getTargetInfo()))
10025       H.DoneProcessing();
10026   } // TODO: handle other formats
10027 }
10028 
10029 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
10030   // Str - The format string.  NOTE: this is NOT null-terminated!
10031   StringRef StrRef = FExpr->getString();
10032   const char *Str = StrRef.data();
10033   // Account for cases where the string literal is truncated in a declaration.
10034   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
10035   assert(T && "String literal not of constant array type!");
10036   size_t TypeSize = T->getSize().getZExtValue();
10037   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10038   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
10039                                                          getLangOpts(),
10040                                                          Context.getTargetInfo());
10041 }
10042 
10043 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10044 
10045 // Returns the related absolute value function that is larger, of 0 if one
10046 // does not exist.
10047 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10048   switch (AbsFunction) {
10049   default:
10050     return 0;
10051 
10052   case Builtin::BI__builtin_abs:
10053     return Builtin::BI__builtin_labs;
10054   case Builtin::BI__builtin_labs:
10055     return Builtin::BI__builtin_llabs;
10056   case Builtin::BI__builtin_llabs:
10057     return 0;
10058 
10059   case Builtin::BI__builtin_fabsf:
10060     return Builtin::BI__builtin_fabs;
10061   case Builtin::BI__builtin_fabs:
10062     return Builtin::BI__builtin_fabsl;
10063   case Builtin::BI__builtin_fabsl:
10064     return 0;
10065 
10066   case Builtin::BI__builtin_cabsf:
10067     return Builtin::BI__builtin_cabs;
10068   case Builtin::BI__builtin_cabs:
10069     return Builtin::BI__builtin_cabsl;
10070   case Builtin::BI__builtin_cabsl:
10071     return 0;
10072 
10073   case Builtin::BIabs:
10074     return Builtin::BIlabs;
10075   case Builtin::BIlabs:
10076     return Builtin::BIllabs;
10077   case Builtin::BIllabs:
10078     return 0;
10079 
10080   case Builtin::BIfabsf:
10081     return Builtin::BIfabs;
10082   case Builtin::BIfabs:
10083     return Builtin::BIfabsl;
10084   case Builtin::BIfabsl:
10085     return 0;
10086 
10087   case Builtin::BIcabsf:
10088    return Builtin::BIcabs;
10089   case Builtin::BIcabs:
10090     return Builtin::BIcabsl;
10091   case Builtin::BIcabsl:
10092     return 0;
10093   }
10094 }
10095 
10096 // Returns the argument type of the absolute value function.
10097 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
10098                                              unsigned AbsType) {
10099   if (AbsType == 0)
10100     return QualType();
10101 
10102   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
10103   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10104   if (Error != ASTContext::GE_None)
10105     return QualType();
10106 
10107   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
10108   if (!FT)
10109     return QualType();
10110 
10111   if (FT->getNumParams() != 1)
10112     return QualType();
10113 
10114   return FT->getParamType(0);
10115 }
10116 
10117 // Returns the best absolute value function, or zero, based on type and
10118 // current absolute value function.
10119 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10120                                    unsigned AbsFunctionKind) {
10121   unsigned BestKind = 0;
10122   uint64_t ArgSize = Context.getTypeSize(ArgType);
10123   for (unsigned Kind = AbsFunctionKind; Kind != 0;
10124        Kind = getLargerAbsoluteValueFunction(Kind)) {
10125     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10126     if (Context.getTypeSize(ParamType) >= ArgSize) {
10127       if (BestKind == 0)
10128         BestKind = Kind;
10129       else if (Context.hasSameType(ParamType, ArgType)) {
10130         BestKind = Kind;
10131         break;
10132       }
10133     }
10134   }
10135   return BestKind;
10136 }
10137 
10138 enum AbsoluteValueKind {
10139   AVK_Integer,
10140   AVK_Floating,
10141   AVK_Complex
10142 };
10143 
10144 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
10145   if (T->isIntegralOrEnumerationType())
10146     return AVK_Integer;
10147   if (T->isRealFloatingType())
10148     return AVK_Floating;
10149   if (T->isAnyComplexType())
10150     return AVK_Complex;
10151 
10152   llvm_unreachable("Type not integer, floating, or complex");
10153 }
10154 
10155 // Changes the absolute value function to a different type.  Preserves whether
10156 // the function is a builtin.
10157 static unsigned changeAbsFunction(unsigned AbsKind,
10158                                   AbsoluteValueKind ValueKind) {
10159   switch (ValueKind) {
10160   case AVK_Integer:
10161     switch (AbsKind) {
10162     default:
10163       return 0;
10164     case Builtin::BI__builtin_fabsf:
10165     case Builtin::BI__builtin_fabs:
10166     case Builtin::BI__builtin_fabsl:
10167     case Builtin::BI__builtin_cabsf:
10168     case Builtin::BI__builtin_cabs:
10169     case Builtin::BI__builtin_cabsl:
10170       return Builtin::BI__builtin_abs;
10171     case Builtin::BIfabsf:
10172     case Builtin::BIfabs:
10173     case Builtin::BIfabsl:
10174     case Builtin::BIcabsf:
10175     case Builtin::BIcabs:
10176     case Builtin::BIcabsl:
10177       return Builtin::BIabs;
10178     }
10179   case AVK_Floating:
10180     switch (AbsKind) {
10181     default:
10182       return 0;
10183     case Builtin::BI__builtin_abs:
10184     case Builtin::BI__builtin_labs:
10185     case Builtin::BI__builtin_llabs:
10186     case Builtin::BI__builtin_cabsf:
10187     case Builtin::BI__builtin_cabs:
10188     case Builtin::BI__builtin_cabsl:
10189       return Builtin::BI__builtin_fabsf;
10190     case Builtin::BIabs:
10191     case Builtin::BIlabs:
10192     case Builtin::BIllabs:
10193     case Builtin::BIcabsf:
10194     case Builtin::BIcabs:
10195     case Builtin::BIcabsl:
10196       return Builtin::BIfabsf;
10197     }
10198   case AVK_Complex:
10199     switch (AbsKind) {
10200     default:
10201       return 0;
10202     case Builtin::BI__builtin_abs:
10203     case Builtin::BI__builtin_labs:
10204     case Builtin::BI__builtin_llabs:
10205     case Builtin::BI__builtin_fabsf:
10206     case Builtin::BI__builtin_fabs:
10207     case Builtin::BI__builtin_fabsl:
10208       return Builtin::BI__builtin_cabsf;
10209     case Builtin::BIabs:
10210     case Builtin::BIlabs:
10211     case Builtin::BIllabs:
10212     case Builtin::BIfabsf:
10213     case Builtin::BIfabs:
10214     case Builtin::BIfabsl:
10215       return Builtin::BIcabsf;
10216     }
10217   }
10218   llvm_unreachable("Unable to convert function");
10219 }
10220 
10221 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10222   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10223   if (!FnInfo)
10224     return 0;
10225 
10226   switch (FDecl->getBuiltinID()) {
10227   default:
10228     return 0;
10229   case Builtin::BI__builtin_abs:
10230   case Builtin::BI__builtin_fabs:
10231   case Builtin::BI__builtin_fabsf:
10232   case Builtin::BI__builtin_fabsl:
10233   case Builtin::BI__builtin_labs:
10234   case Builtin::BI__builtin_llabs:
10235   case Builtin::BI__builtin_cabs:
10236   case Builtin::BI__builtin_cabsf:
10237   case Builtin::BI__builtin_cabsl:
10238   case Builtin::BIabs:
10239   case Builtin::BIlabs:
10240   case Builtin::BIllabs:
10241   case Builtin::BIfabs:
10242   case Builtin::BIfabsf:
10243   case Builtin::BIfabsl:
10244   case Builtin::BIcabs:
10245   case Builtin::BIcabsf:
10246   case Builtin::BIcabsl:
10247     return FDecl->getBuiltinID();
10248   }
10249   llvm_unreachable("Unknown Builtin type");
10250 }
10251 
10252 // If the replacement is valid, emit a note with replacement function.
10253 // Additionally, suggest including the proper header if not already included.
10254 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10255                             unsigned AbsKind, QualType ArgType) {
10256   bool EmitHeaderHint = true;
10257   const char *HeaderName = nullptr;
10258   const char *FunctionName = nullptr;
10259   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10260     FunctionName = "std::abs";
10261     if (ArgType->isIntegralOrEnumerationType()) {
10262       HeaderName = "cstdlib";
10263     } else if (ArgType->isRealFloatingType()) {
10264       HeaderName = "cmath";
10265     } else {
10266       llvm_unreachable("Invalid Type");
10267     }
10268 
10269     // Lookup all std::abs
10270     if (NamespaceDecl *Std = S.getStdNamespace()) {
10271       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10272       R.suppressDiagnostics();
10273       S.LookupQualifiedName(R, Std);
10274 
10275       for (const auto *I : R) {
10276         const FunctionDecl *FDecl = nullptr;
10277         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10278           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10279         } else {
10280           FDecl = dyn_cast<FunctionDecl>(I);
10281         }
10282         if (!FDecl)
10283           continue;
10284 
10285         // Found std::abs(), check that they are the right ones.
10286         if (FDecl->getNumParams() != 1)
10287           continue;
10288 
10289         // Check that the parameter type can handle the argument.
10290         QualType ParamType = FDecl->getParamDecl(0)->getType();
10291         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10292             S.Context.getTypeSize(ArgType) <=
10293                 S.Context.getTypeSize(ParamType)) {
10294           // Found a function, don't need the header hint.
10295           EmitHeaderHint = false;
10296           break;
10297         }
10298       }
10299     }
10300   } else {
10301     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10302     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10303 
10304     if (HeaderName) {
10305       DeclarationName DN(&S.Context.Idents.get(FunctionName));
10306       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10307       R.suppressDiagnostics();
10308       S.LookupName(R, S.getCurScope());
10309 
10310       if (R.isSingleResult()) {
10311         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10312         if (FD && FD->getBuiltinID() == AbsKind) {
10313           EmitHeaderHint = false;
10314         } else {
10315           return;
10316         }
10317       } else if (!R.empty()) {
10318         return;
10319       }
10320     }
10321   }
10322 
10323   S.Diag(Loc, diag::note_replace_abs_function)
10324       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10325 
10326   if (!HeaderName)
10327     return;
10328 
10329   if (!EmitHeaderHint)
10330     return;
10331 
10332   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10333                                                     << FunctionName;
10334 }
10335 
10336 template <std::size_t StrLen>
10337 static bool IsStdFunction(const FunctionDecl *FDecl,
10338                           const char (&Str)[StrLen]) {
10339   if (!FDecl)
10340     return false;
10341   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10342     return false;
10343   if (!FDecl->isInStdNamespace())
10344     return false;
10345 
10346   return true;
10347 }
10348 
10349 // Warn when using the wrong abs() function.
10350 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10351                                       const FunctionDecl *FDecl) {
10352   if (Call->getNumArgs() != 1)
10353     return;
10354 
10355   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10356   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10357   if (AbsKind == 0 && !IsStdAbs)
10358     return;
10359 
10360   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10361   QualType ParamType = Call->getArg(0)->getType();
10362 
10363   // Unsigned types cannot be negative.  Suggest removing the absolute value
10364   // function call.
10365   if (ArgType->isUnsignedIntegerType()) {
10366     const char *FunctionName =
10367         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10368     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10369     Diag(Call->getExprLoc(), diag::note_remove_abs)
10370         << FunctionName
10371         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10372     return;
10373   }
10374 
10375   // Taking the absolute value of a pointer is very suspicious, they probably
10376   // wanted to index into an array, dereference a pointer, call a function, etc.
10377   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10378     unsigned DiagType = 0;
10379     if (ArgType->isFunctionType())
10380       DiagType = 1;
10381     else if (ArgType->isArrayType())
10382       DiagType = 2;
10383 
10384     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10385     return;
10386   }
10387 
10388   // std::abs has overloads which prevent most of the absolute value problems
10389   // from occurring.
10390   if (IsStdAbs)
10391     return;
10392 
10393   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10394   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10395 
10396   // The argument and parameter are the same kind.  Check if they are the right
10397   // size.
10398   if (ArgValueKind == ParamValueKind) {
10399     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10400       return;
10401 
10402     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10403     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10404         << FDecl << ArgType << ParamType;
10405 
10406     if (NewAbsKind == 0)
10407       return;
10408 
10409     emitReplacement(*this, Call->getExprLoc(),
10410                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10411     return;
10412   }
10413 
10414   // ArgValueKind != ParamValueKind
10415   // The wrong type of absolute value function was used.  Attempt to find the
10416   // proper one.
10417   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10418   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10419   if (NewAbsKind == 0)
10420     return;
10421 
10422   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10423       << FDecl << ParamValueKind << ArgValueKind;
10424 
10425   emitReplacement(*this, Call->getExprLoc(),
10426                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10427 }
10428 
10429 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10430 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10431                                 const FunctionDecl *FDecl) {
10432   if (!Call || !FDecl) return;
10433 
10434   // Ignore template specializations and macros.
10435   if (inTemplateInstantiation()) return;
10436   if (Call->getExprLoc().isMacroID()) return;
10437 
10438   // Only care about the one template argument, two function parameter std::max
10439   if (Call->getNumArgs() != 2) return;
10440   if (!IsStdFunction(FDecl, "max")) return;
10441   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10442   if (!ArgList) return;
10443   if (ArgList->size() != 1) return;
10444 
10445   // Check that template type argument is unsigned integer.
10446   const auto& TA = ArgList->get(0);
10447   if (TA.getKind() != TemplateArgument::Type) return;
10448   QualType ArgType = TA.getAsType();
10449   if (!ArgType->isUnsignedIntegerType()) return;
10450 
10451   // See if either argument is a literal zero.
10452   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10453     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10454     if (!MTE) return false;
10455     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10456     if (!Num) return false;
10457     if (Num->getValue() != 0) return false;
10458     return true;
10459   };
10460 
10461   const Expr *FirstArg = Call->getArg(0);
10462   const Expr *SecondArg = Call->getArg(1);
10463   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10464   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10465 
10466   // Only warn when exactly one argument is zero.
10467   if (IsFirstArgZero == IsSecondArgZero) return;
10468 
10469   SourceRange FirstRange = FirstArg->getSourceRange();
10470   SourceRange SecondRange = SecondArg->getSourceRange();
10471 
10472   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10473 
10474   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10475       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10476 
10477   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10478   SourceRange RemovalRange;
10479   if (IsFirstArgZero) {
10480     RemovalRange = SourceRange(FirstRange.getBegin(),
10481                                SecondRange.getBegin().getLocWithOffset(-1));
10482   } else {
10483     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10484                                SecondRange.getEnd());
10485   }
10486 
10487   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10488         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10489         << FixItHint::CreateRemoval(RemovalRange);
10490 }
10491 
10492 //===--- CHECK: Standard memory functions ---------------------------------===//
10493 
10494 /// Takes the expression passed to the size_t parameter of functions
10495 /// such as memcmp, strncat, etc and warns if it's a comparison.
10496 ///
10497 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10498 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10499                                            IdentifierInfo *FnName,
10500                                            SourceLocation FnLoc,
10501                                            SourceLocation RParenLoc) {
10502   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10503   if (!Size)
10504     return false;
10505 
10506   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10507   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10508     return false;
10509 
10510   SourceRange SizeRange = Size->getSourceRange();
10511   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10512       << SizeRange << FnName;
10513   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10514       << FnName
10515       << FixItHint::CreateInsertion(
10516              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10517       << FixItHint::CreateRemoval(RParenLoc);
10518   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10519       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10520       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10521                                     ")");
10522 
10523   return true;
10524 }
10525 
10526 /// Determine whether the given type is or contains a dynamic class type
10527 /// (e.g., whether it has a vtable).
10528 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10529                                                      bool &IsContained) {
10530   // Look through array types while ignoring qualifiers.
10531   const Type *Ty = T->getBaseElementTypeUnsafe();
10532   IsContained = false;
10533 
10534   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10535   RD = RD ? RD->getDefinition() : nullptr;
10536   if (!RD || RD->isInvalidDecl())
10537     return nullptr;
10538 
10539   if (RD->isDynamicClass())
10540     return RD;
10541 
10542   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10543   // It's impossible for a class to transitively contain itself by value, so
10544   // infinite recursion is impossible.
10545   for (auto *FD : RD->fields()) {
10546     bool SubContained;
10547     if (const CXXRecordDecl *ContainedRD =
10548             getContainedDynamicClass(FD->getType(), SubContained)) {
10549       IsContained = true;
10550       return ContainedRD;
10551     }
10552   }
10553 
10554   return nullptr;
10555 }
10556 
10557 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10558   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10559     if (Unary->getKind() == UETT_SizeOf)
10560       return Unary;
10561   return nullptr;
10562 }
10563 
10564 /// If E is a sizeof expression, returns its argument expression,
10565 /// otherwise returns NULL.
10566 static const Expr *getSizeOfExprArg(const Expr *E) {
10567   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10568     if (!SizeOf->isArgumentType())
10569       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10570   return nullptr;
10571 }
10572 
10573 /// If E is a sizeof expression, returns its argument type.
10574 static QualType getSizeOfArgType(const Expr *E) {
10575   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10576     return SizeOf->getTypeOfArgument();
10577   return QualType();
10578 }
10579 
10580 namespace {
10581 
10582 struct SearchNonTrivialToInitializeField
10583     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10584   using Super =
10585       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10586 
10587   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10588 
10589   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10590                      SourceLocation SL) {
10591     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10592       asDerived().visitArray(PDIK, AT, SL);
10593       return;
10594     }
10595 
10596     Super::visitWithKind(PDIK, FT, SL);
10597   }
10598 
10599   void visitARCStrong(QualType FT, SourceLocation SL) {
10600     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10601   }
10602   void visitARCWeak(QualType FT, SourceLocation SL) {
10603     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10604   }
10605   void visitStruct(QualType FT, SourceLocation SL) {
10606     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10607       visit(FD->getType(), FD->getLocation());
10608   }
10609   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10610                   const ArrayType *AT, SourceLocation SL) {
10611     visit(getContext().getBaseElementType(AT), SL);
10612   }
10613   void visitTrivial(QualType FT, SourceLocation SL) {}
10614 
10615   static void diag(QualType RT, const Expr *E, Sema &S) {
10616     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10617   }
10618 
10619   ASTContext &getContext() { return S.getASTContext(); }
10620 
10621   const Expr *E;
10622   Sema &S;
10623 };
10624 
10625 struct SearchNonTrivialToCopyField
10626     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10627   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10628 
10629   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10630 
10631   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10632                      SourceLocation SL) {
10633     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10634       asDerived().visitArray(PCK, AT, SL);
10635       return;
10636     }
10637 
10638     Super::visitWithKind(PCK, FT, SL);
10639   }
10640 
10641   void visitARCStrong(QualType FT, SourceLocation SL) {
10642     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10643   }
10644   void visitARCWeak(QualType FT, SourceLocation SL) {
10645     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10646   }
10647   void visitStruct(QualType FT, SourceLocation SL) {
10648     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10649       visit(FD->getType(), FD->getLocation());
10650   }
10651   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10652                   SourceLocation SL) {
10653     visit(getContext().getBaseElementType(AT), SL);
10654   }
10655   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10656                 SourceLocation SL) {}
10657   void visitTrivial(QualType FT, SourceLocation SL) {}
10658   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10659 
10660   static void diag(QualType RT, const Expr *E, Sema &S) {
10661     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10662   }
10663 
10664   ASTContext &getContext() { return S.getASTContext(); }
10665 
10666   const Expr *E;
10667   Sema &S;
10668 };
10669 
10670 }
10671 
10672 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10673 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10674   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10675 
10676   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10677     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10678       return false;
10679 
10680     return doesExprLikelyComputeSize(BO->getLHS()) ||
10681            doesExprLikelyComputeSize(BO->getRHS());
10682   }
10683 
10684   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10685 }
10686 
10687 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10688 ///
10689 /// \code
10690 ///   #define MACRO 0
10691 ///   foo(MACRO);
10692 ///   foo(0);
10693 /// \endcode
10694 ///
10695 /// This should return true for the first call to foo, but not for the second
10696 /// (regardless of whether foo is a macro or function).
10697 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10698                                         SourceLocation CallLoc,
10699                                         SourceLocation ArgLoc) {
10700   if (!CallLoc.isMacroID())
10701     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10702 
10703   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10704          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10705 }
10706 
10707 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10708 /// last two arguments transposed.
10709 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10710   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10711     return;
10712 
10713   const Expr *SizeArg =
10714     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10715 
10716   auto isLiteralZero = [](const Expr *E) {
10717     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10718   };
10719 
10720   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10721   SourceLocation CallLoc = Call->getRParenLoc();
10722   SourceManager &SM = S.getSourceManager();
10723   if (isLiteralZero(SizeArg) &&
10724       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10725 
10726     SourceLocation DiagLoc = SizeArg->getExprLoc();
10727 
10728     // Some platforms #define bzero to __builtin_memset. See if this is the
10729     // case, and if so, emit a better diagnostic.
10730     if (BId == Builtin::BIbzero ||
10731         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10732                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10733       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10734       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10735     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10736       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10737       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10738     }
10739     return;
10740   }
10741 
10742   // If the second argument to a memset is a sizeof expression and the third
10743   // isn't, this is also likely an error. This should catch
10744   // 'memset(buf, sizeof(buf), 0xff)'.
10745   if (BId == Builtin::BImemset &&
10746       doesExprLikelyComputeSize(Call->getArg(1)) &&
10747       !doesExprLikelyComputeSize(Call->getArg(2))) {
10748     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10749     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10750     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10751     return;
10752   }
10753 }
10754 
10755 /// Check for dangerous or invalid arguments to memset().
10756 ///
10757 /// This issues warnings on known problematic, dangerous or unspecified
10758 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10759 /// function calls.
10760 ///
10761 /// \param Call The call expression to diagnose.
10762 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10763                                    unsigned BId,
10764                                    IdentifierInfo *FnName) {
10765   assert(BId != 0);
10766 
10767   // It is possible to have a non-standard definition of memset.  Validate
10768   // we have enough arguments, and if not, abort further checking.
10769   unsigned ExpectedNumArgs =
10770       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10771   if (Call->getNumArgs() < ExpectedNumArgs)
10772     return;
10773 
10774   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10775                       BId == Builtin::BIstrndup ? 1 : 2);
10776   unsigned LenArg =
10777       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10778   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10779 
10780   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10781                                      Call->getBeginLoc(), Call->getRParenLoc()))
10782     return;
10783 
10784   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10785   CheckMemaccessSize(*this, BId, Call);
10786 
10787   // We have special checking when the length is a sizeof expression.
10788   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10789   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10790   llvm::FoldingSetNodeID SizeOfArgID;
10791 
10792   // Although widely used, 'bzero' is not a standard function. Be more strict
10793   // with the argument types before allowing diagnostics and only allow the
10794   // form bzero(ptr, sizeof(...)).
10795   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10796   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10797     return;
10798 
10799   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10800     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10801     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10802 
10803     QualType DestTy = Dest->getType();
10804     QualType PointeeTy;
10805     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10806       PointeeTy = DestPtrTy->getPointeeType();
10807 
10808       // Never warn about void type pointers. This can be used to suppress
10809       // false positives.
10810       if (PointeeTy->isVoidType())
10811         continue;
10812 
10813       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10814       // actually comparing the expressions for equality. Because computing the
10815       // expression IDs can be expensive, we only do this if the diagnostic is
10816       // enabled.
10817       if (SizeOfArg &&
10818           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10819                            SizeOfArg->getExprLoc())) {
10820         // We only compute IDs for expressions if the warning is enabled, and
10821         // cache the sizeof arg's ID.
10822         if (SizeOfArgID == llvm::FoldingSetNodeID())
10823           SizeOfArg->Profile(SizeOfArgID, Context, true);
10824         llvm::FoldingSetNodeID DestID;
10825         Dest->Profile(DestID, Context, true);
10826         if (DestID == SizeOfArgID) {
10827           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10828           //       over sizeof(src) as well.
10829           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10830           StringRef ReadableName = FnName->getName();
10831 
10832           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10833             if (UnaryOp->getOpcode() == UO_AddrOf)
10834               ActionIdx = 1; // If its an address-of operator, just remove it.
10835           if (!PointeeTy->isIncompleteType() &&
10836               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10837             ActionIdx = 2; // If the pointee's size is sizeof(char),
10838                            // suggest an explicit length.
10839 
10840           // If the function is defined as a builtin macro, do not show macro
10841           // expansion.
10842           SourceLocation SL = SizeOfArg->getExprLoc();
10843           SourceRange DSR = Dest->getSourceRange();
10844           SourceRange SSR = SizeOfArg->getSourceRange();
10845           SourceManager &SM = getSourceManager();
10846 
10847           if (SM.isMacroArgExpansion(SL)) {
10848             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10849             SL = SM.getSpellingLoc(SL);
10850             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10851                              SM.getSpellingLoc(DSR.getEnd()));
10852             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10853                              SM.getSpellingLoc(SSR.getEnd()));
10854           }
10855 
10856           DiagRuntimeBehavior(SL, SizeOfArg,
10857                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10858                                 << ReadableName
10859                                 << PointeeTy
10860                                 << DestTy
10861                                 << DSR
10862                                 << SSR);
10863           DiagRuntimeBehavior(SL, SizeOfArg,
10864                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10865                                 << ActionIdx
10866                                 << SSR);
10867 
10868           break;
10869         }
10870       }
10871 
10872       // Also check for cases where the sizeof argument is the exact same
10873       // type as the memory argument, and where it points to a user-defined
10874       // record type.
10875       if (SizeOfArgTy != QualType()) {
10876         if (PointeeTy->isRecordType() &&
10877             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10878           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10879                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10880                                 << FnName << SizeOfArgTy << ArgIdx
10881                                 << PointeeTy << Dest->getSourceRange()
10882                                 << LenExpr->getSourceRange());
10883           break;
10884         }
10885       }
10886     } else if (DestTy->isArrayType()) {
10887       PointeeTy = DestTy;
10888     }
10889 
10890     if (PointeeTy == QualType())
10891       continue;
10892 
10893     // Always complain about dynamic classes.
10894     bool IsContained;
10895     if (const CXXRecordDecl *ContainedRD =
10896             getContainedDynamicClass(PointeeTy, IsContained)) {
10897 
10898       unsigned OperationType = 0;
10899       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10900       // "overwritten" if we're warning about the destination for any call
10901       // but memcmp; otherwise a verb appropriate to the call.
10902       if (ArgIdx != 0 || IsCmp) {
10903         if (BId == Builtin::BImemcpy)
10904           OperationType = 1;
10905         else if(BId == Builtin::BImemmove)
10906           OperationType = 2;
10907         else if (IsCmp)
10908           OperationType = 3;
10909       }
10910 
10911       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10912                           PDiag(diag::warn_dyn_class_memaccess)
10913                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10914                               << IsContained << ContainedRD << OperationType
10915                               << Call->getCallee()->getSourceRange());
10916     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10917              BId != Builtin::BImemset)
10918       DiagRuntimeBehavior(
10919         Dest->getExprLoc(), Dest,
10920         PDiag(diag::warn_arc_object_memaccess)
10921           << ArgIdx << FnName << PointeeTy
10922           << Call->getCallee()->getSourceRange());
10923     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10924       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10925           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10926         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10927                             PDiag(diag::warn_cstruct_memaccess)
10928                                 << ArgIdx << FnName << PointeeTy << 0);
10929         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10930       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10931                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10932         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10933                             PDiag(diag::warn_cstruct_memaccess)
10934                                 << ArgIdx << FnName << PointeeTy << 1);
10935         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10936       } else {
10937         continue;
10938       }
10939     } else
10940       continue;
10941 
10942     DiagRuntimeBehavior(
10943       Dest->getExprLoc(), Dest,
10944       PDiag(diag::note_bad_memaccess_silence)
10945         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10946     break;
10947   }
10948 }
10949 
10950 // A little helper routine: ignore addition and subtraction of integer literals.
10951 // This intentionally does not ignore all integer constant expressions because
10952 // we don't want to remove sizeof().
10953 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10954   Ex = Ex->IgnoreParenCasts();
10955 
10956   while (true) {
10957     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10958     if (!BO || !BO->isAdditiveOp())
10959       break;
10960 
10961     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10962     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10963 
10964     if (isa<IntegerLiteral>(RHS))
10965       Ex = LHS;
10966     else if (isa<IntegerLiteral>(LHS))
10967       Ex = RHS;
10968     else
10969       break;
10970   }
10971 
10972   return Ex;
10973 }
10974 
10975 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10976                                                       ASTContext &Context) {
10977   // Only handle constant-sized or VLAs, but not flexible members.
10978   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10979     // Only issue the FIXIT for arrays of size > 1.
10980     if (CAT->getSize().getSExtValue() <= 1)
10981       return false;
10982   } else if (!Ty->isVariableArrayType()) {
10983     return false;
10984   }
10985   return true;
10986 }
10987 
10988 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10989 // be the size of the source, instead of the destination.
10990 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10991                                     IdentifierInfo *FnName) {
10992 
10993   // Don't crash if the user has the wrong number of arguments
10994   unsigned NumArgs = Call->getNumArgs();
10995   if ((NumArgs != 3) && (NumArgs != 4))
10996     return;
10997 
10998   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10999   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
11000   const Expr *CompareWithSrc = nullptr;
11001 
11002   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
11003                                      Call->getBeginLoc(), Call->getRParenLoc()))
11004     return;
11005 
11006   // Look for 'strlcpy(dst, x, sizeof(x))'
11007   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
11008     CompareWithSrc = Ex;
11009   else {
11010     // Look for 'strlcpy(dst, x, strlen(x))'
11011     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11012       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11013           SizeCall->getNumArgs() == 1)
11014         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
11015     }
11016   }
11017 
11018   if (!CompareWithSrc)
11019     return;
11020 
11021   // Determine if the argument to sizeof/strlen is equal to the source
11022   // argument.  In principle there's all kinds of things you could do
11023   // here, for instance creating an == expression and evaluating it with
11024   // EvaluateAsBooleanCondition, but this uses a more direct technique:
11025   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11026   if (!SrcArgDRE)
11027     return;
11028 
11029   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11030   if (!CompareWithSrcDRE ||
11031       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11032     return;
11033 
11034   const Expr *OriginalSizeArg = Call->getArg(2);
11035   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11036       << OriginalSizeArg->getSourceRange() << FnName;
11037 
11038   // Output a FIXIT hint if the destination is an array (rather than a
11039   // pointer to an array).  This could be enhanced to handle some
11040   // pointers if we know the actual size, like if DstArg is 'array+2'
11041   // we could say 'sizeof(array)-2'.
11042   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
11043   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
11044     return;
11045 
11046   SmallString<128> sizeString;
11047   llvm::raw_svector_ostream OS(sizeString);
11048   OS << "sizeof(";
11049   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11050   OS << ")";
11051 
11052   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
11053       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
11054                                       OS.str());
11055 }
11056 
11057 /// Check if two expressions refer to the same declaration.
11058 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11059   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11060     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11061       return D1->getDecl() == D2->getDecl();
11062   return false;
11063 }
11064 
11065 static const Expr *getStrlenExprArg(const Expr *E) {
11066   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11067     const FunctionDecl *FD = CE->getDirectCallee();
11068     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11069       return nullptr;
11070     return CE->getArg(0)->IgnoreParenCasts();
11071   }
11072   return nullptr;
11073 }
11074 
11075 // Warn on anti-patterns as the 'size' argument to strncat.
11076 // The correct size argument should look like following:
11077 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
11078 void Sema::CheckStrncatArguments(const CallExpr *CE,
11079                                  IdentifierInfo *FnName) {
11080   // Don't crash if the user has the wrong number of arguments.
11081   if (CE->getNumArgs() < 3)
11082     return;
11083   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11084   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11085   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11086 
11087   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11088                                      CE->getRParenLoc()))
11089     return;
11090 
11091   // Identify common expressions, which are wrongly used as the size argument
11092   // to strncat and may lead to buffer overflows.
11093   unsigned PatternType = 0;
11094   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11095     // - sizeof(dst)
11096     if (referToTheSameDecl(SizeOfArg, DstArg))
11097       PatternType = 1;
11098     // - sizeof(src)
11099     else if (referToTheSameDecl(SizeOfArg, SrcArg))
11100       PatternType = 2;
11101   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11102     if (BE->getOpcode() == BO_Sub) {
11103       const Expr *L = BE->getLHS()->IgnoreParenCasts();
11104       const Expr *R = BE->getRHS()->IgnoreParenCasts();
11105       // - sizeof(dst) - strlen(dst)
11106       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11107           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
11108         PatternType = 1;
11109       // - sizeof(src) - (anything)
11110       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11111         PatternType = 2;
11112     }
11113   }
11114 
11115   if (PatternType == 0)
11116     return;
11117 
11118   // Generate the diagnostic.
11119   SourceLocation SL = LenArg->getBeginLoc();
11120   SourceRange SR = LenArg->getSourceRange();
11121   SourceManager &SM = getSourceManager();
11122 
11123   // If the function is defined as a builtin macro, do not show macro expansion.
11124   if (SM.isMacroArgExpansion(SL)) {
11125     SL = SM.getSpellingLoc(SL);
11126     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11127                      SM.getSpellingLoc(SR.getEnd()));
11128   }
11129 
11130   // Check if the destination is an array (rather than a pointer to an array).
11131   QualType DstTy = DstArg->getType();
11132   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11133                                                                     Context);
11134   if (!isKnownSizeArray) {
11135     if (PatternType == 1)
11136       Diag(SL, diag::warn_strncat_wrong_size) << SR;
11137     else
11138       Diag(SL, diag::warn_strncat_src_size) << SR;
11139     return;
11140   }
11141 
11142   if (PatternType == 1)
11143     Diag(SL, diag::warn_strncat_large_size) << SR;
11144   else
11145     Diag(SL, diag::warn_strncat_src_size) << SR;
11146 
11147   SmallString<128> sizeString;
11148   llvm::raw_svector_ostream OS(sizeString);
11149   OS << "sizeof(";
11150   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11151   OS << ") - ";
11152   OS << "strlen(";
11153   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11154   OS << ") - 1";
11155 
11156   Diag(SL, diag::note_strncat_wrong_size)
11157     << FixItHint::CreateReplacement(SR, OS.str());
11158 }
11159 
11160 namespace {
11161 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11162                                 const UnaryOperator *UnaryExpr, const Decl *D) {
11163   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
11164     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11165         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11166     return;
11167   }
11168 }
11169 
11170 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11171                                  const UnaryOperator *UnaryExpr) {
11172   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11173     const Decl *D = Lvalue->getDecl();
11174     if (isa<DeclaratorDecl>(D))
11175       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
11176         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11177   }
11178 
11179   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11180     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11181                                       Lvalue->getMemberDecl());
11182 }
11183 
11184 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11185                             const UnaryOperator *UnaryExpr) {
11186   const auto *Lambda = dyn_cast<LambdaExpr>(
11187       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11188   if (!Lambda)
11189     return;
11190 
11191   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11192       << CalleeName << 2 /*object: lambda expression*/;
11193 }
11194 
11195 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11196                                   const DeclRefExpr *Lvalue) {
11197   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11198   if (Var == nullptr)
11199     return;
11200 
11201   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11202       << CalleeName << 0 /*object: */ << Var;
11203 }
11204 
11205 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11206                             const CastExpr *Cast) {
11207   SmallString<128> SizeString;
11208   llvm::raw_svector_ostream OS(SizeString);
11209 
11210   clang::CastKind Kind = Cast->getCastKind();
11211   if (Kind == clang::CK_BitCast &&
11212       !Cast->getSubExpr()->getType()->isFunctionPointerType())
11213     return;
11214   if (Kind == clang::CK_IntegralToPointer &&
11215       !isa<IntegerLiteral>(
11216           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11217     return;
11218 
11219   switch (Cast->getCastKind()) {
11220   case clang::CK_BitCast:
11221   case clang::CK_IntegralToPointer:
11222   case clang::CK_FunctionToPointerDecay:
11223     OS << '\'';
11224     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11225     OS << '\'';
11226     break;
11227   default:
11228     return;
11229   }
11230 
11231   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11232       << CalleeName << 0 /*object: */ << OS.str();
11233 }
11234 } // namespace
11235 
11236 /// Alerts the user that they are attempting to free a non-malloc'd object.
11237 void Sema::CheckFreeArguments(const CallExpr *E) {
11238   const std::string CalleeName =
11239       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11240 
11241   { // Prefer something that doesn't involve a cast to make things simpler.
11242     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11243     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11244       switch (UnaryExpr->getOpcode()) {
11245       case UnaryOperator::Opcode::UO_AddrOf:
11246         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11247       case UnaryOperator::Opcode::UO_Plus:
11248         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11249       default:
11250         break;
11251       }
11252 
11253     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11254       if (Lvalue->getType()->isArrayType())
11255         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11256 
11257     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11258       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11259           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11260       return;
11261     }
11262 
11263     if (isa<BlockExpr>(Arg)) {
11264       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11265           << CalleeName << 1 /*object: block*/;
11266       return;
11267     }
11268   }
11269   // Maybe the cast was important, check after the other cases.
11270   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11271     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11272 }
11273 
11274 void
11275 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11276                          SourceLocation ReturnLoc,
11277                          bool isObjCMethod,
11278                          const AttrVec *Attrs,
11279                          const FunctionDecl *FD) {
11280   // Check if the return value is null but should not be.
11281   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11282        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
11283       CheckNonNullExpr(*this, RetValExp))
11284     Diag(ReturnLoc, diag::warn_null_ret)
11285       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11286 
11287   // C++11 [basic.stc.dynamic.allocation]p4:
11288   //   If an allocation function declared with a non-throwing
11289   //   exception-specification fails to allocate storage, it shall return
11290   //   a null pointer. Any other allocation function that fails to allocate
11291   //   storage shall indicate failure only by throwing an exception [...]
11292   if (FD) {
11293     OverloadedOperatorKind Op = FD->getOverloadedOperator();
11294     if (Op == OO_New || Op == OO_Array_New) {
11295       const FunctionProtoType *Proto
11296         = FD->getType()->castAs<FunctionProtoType>();
11297       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11298           CheckNonNullExpr(*this, RetValExp))
11299         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11300           << FD << getLangOpts().CPlusPlus11;
11301     }
11302   }
11303 
11304   // PPC MMA non-pointer types are not allowed as return type. Checking the type
11305   // here prevent the user from using a PPC MMA type as trailing return type.
11306   if (Context.getTargetInfo().getTriple().isPPC64())
11307     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11308 }
11309 
11310 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
11311 
11312 /// Check for comparisons of floating point operands using != and ==.
11313 /// Issue a warning if these are no self-comparisons, as they are not likely
11314 /// to do what the programmer intended.
11315 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
11316   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
11317   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
11318 
11319   // Special case: check for x == x (which is OK).
11320   // Do not emit warnings for such cases.
11321   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11322     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11323       if (DRL->getDecl() == DRR->getDecl())
11324         return;
11325 
11326   // Special case: check for comparisons against literals that can be exactly
11327   //  represented by APFloat.  In such cases, do not emit a warning.  This
11328   //  is a heuristic: often comparison against such literals are used to
11329   //  detect if a value in a variable has not changed.  This clearly can
11330   //  lead to false negatives.
11331   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11332     if (FLL->isExact())
11333       return;
11334   } else
11335     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11336       if (FLR->isExact())
11337         return;
11338 
11339   // Check for comparisons with builtin types.
11340   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11341     if (CL->getBuiltinCallee())
11342       return;
11343 
11344   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11345     if (CR->getBuiltinCallee())
11346       return;
11347 
11348   // Emit the diagnostic.
11349   Diag(Loc, diag::warn_floatingpoint_eq)
11350     << LHS->getSourceRange() << RHS->getSourceRange();
11351 }
11352 
11353 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11354 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11355 
11356 namespace {
11357 
11358 /// Structure recording the 'active' range of an integer-valued
11359 /// expression.
11360 struct IntRange {
11361   /// The number of bits active in the int. Note that this includes exactly one
11362   /// sign bit if !NonNegative.
11363   unsigned Width;
11364 
11365   /// True if the int is known not to have negative values. If so, all leading
11366   /// bits before Width are known zero, otherwise they are known to be the
11367   /// same as the MSB within Width.
11368   bool NonNegative;
11369 
11370   IntRange(unsigned Width, bool NonNegative)
11371       : Width(Width), NonNegative(NonNegative) {}
11372 
11373   /// Number of bits excluding the sign bit.
11374   unsigned valueBits() const {
11375     return NonNegative ? Width : Width - 1;
11376   }
11377 
11378   /// Returns the range of the bool type.
11379   static IntRange forBoolType() {
11380     return IntRange(1, true);
11381   }
11382 
11383   /// Returns the range of an opaque value of the given integral type.
11384   static IntRange forValueOfType(ASTContext &C, QualType T) {
11385     return forValueOfCanonicalType(C,
11386                           T->getCanonicalTypeInternal().getTypePtr());
11387   }
11388 
11389   /// Returns the range of an opaque value of a canonical integral type.
11390   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11391     assert(T->isCanonicalUnqualified());
11392 
11393     if (const VectorType *VT = dyn_cast<VectorType>(T))
11394       T = VT->getElementType().getTypePtr();
11395     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11396       T = CT->getElementType().getTypePtr();
11397     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11398       T = AT->getValueType().getTypePtr();
11399 
11400     if (!C.getLangOpts().CPlusPlus) {
11401       // For enum types in C code, use the underlying datatype.
11402       if (const EnumType *ET = dyn_cast<EnumType>(T))
11403         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11404     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11405       // For enum types in C++, use the known bit width of the enumerators.
11406       EnumDecl *Enum = ET->getDecl();
11407       // In C++11, enums can have a fixed underlying type. Use this type to
11408       // compute the range.
11409       if (Enum->isFixed()) {
11410         return IntRange(C.getIntWidth(QualType(T, 0)),
11411                         !ET->isSignedIntegerOrEnumerationType());
11412       }
11413 
11414       unsigned NumPositive = Enum->getNumPositiveBits();
11415       unsigned NumNegative = Enum->getNumNegativeBits();
11416 
11417       if (NumNegative == 0)
11418         return IntRange(NumPositive, true/*NonNegative*/);
11419       else
11420         return IntRange(std::max(NumPositive + 1, NumNegative),
11421                         false/*NonNegative*/);
11422     }
11423 
11424     if (const auto *EIT = dyn_cast<BitIntType>(T))
11425       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11426 
11427     const BuiltinType *BT = cast<BuiltinType>(T);
11428     assert(BT->isInteger());
11429 
11430     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11431   }
11432 
11433   /// Returns the "target" range of a canonical integral type, i.e.
11434   /// the range of values expressible in the type.
11435   ///
11436   /// This matches forValueOfCanonicalType except that enums have the
11437   /// full range of their type, not the range of their enumerators.
11438   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11439     assert(T->isCanonicalUnqualified());
11440 
11441     if (const VectorType *VT = dyn_cast<VectorType>(T))
11442       T = VT->getElementType().getTypePtr();
11443     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11444       T = CT->getElementType().getTypePtr();
11445     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11446       T = AT->getValueType().getTypePtr();
11447     if (const EnumType *ET = dyn_cast<EnumType>(T))
11448       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11449 
11450     if (const auto *EIT = dyn_cast<BitIntType>(T))
11451       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11452 
11453     const BuiltinType *BT = cast<BuiltinType>(T);
11454     assert(BT->isInteger());
11455 
11456     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11457   }
11458 
11459   /// Returns the supremum of two ranges: i.e. their conservative merge.
11460   static IntRange join(IntRange L, IntRange R) {
11461     bool Unsigned = L.NonNegative && R.NonNegative;
11462     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11463                     L.NonNegative && R.NonNegative);
11464   }
11465 
11466   /// Return the range of a bitwise-AND of the two ranges.
11467   static IntRange bit_and(IntRange L, IntRange R) {
11468     unsigned Bits = std::max(L.Width, R.Width);
11469     bool NonNegative = false;
11470     if (L.NonNegative) {
11471       Bits = std::min(Bits, L.Width);
11472       NonNegative = true;
11473     }
11474     if (R.NonNegative) {
11475       Bits = std::min(Bits, R.Width);
11476       NonNegative = true;
11477     }
11478     return IntRange(Bits, NonNegative);
11479   }
11480 
11481   /// Return the range of a sum of the two ranges.
11482   static IntRange sum(IntRange L, IntRange R) {
11483     bool Unsigned = L.NonNegative && R.NonNegative;
11484     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11485                     Unsigned);
11486   }
11487 
11488   /// Return the range of a difference of the two ranges.
11489   static IntRange difference(IntRange L, IntRange R) {
11490     // We need a 1-bit-wider range if:
11491     //   1) LHS can be negative: least value can be reduced.
11492     //   2) RHS can be negative: greatest value can be increased.
11493     bool CanWiden = !L.NonNegative || !R.NonNegative;
11494     bool Unsigned = L.NonNegative && R.Width == 0;
11495     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11496                         !Unsigned,
11497                     Unsigned);
11498   }
11499 
11500   /// Return the range of a product of the two ranges.
11501   static IntRange product(IntRange L, IntRange R) {
11502     // If both LHS and RHS can be negative, we can form
11503     //   -2^L * -2^R = 2^(L + R)
11504     // which requires L + R + 1 value bits to represent.
11505     bool CanWiden = !L.NonNegative && !R.NonNegative;
11506     bool Unsigned = L.NonNegative && R.NonNegative;
11507     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11508                     Unsigned);
11509   }
11510 
11511   /// Return the range of a remainder operation between the two ranges.
11512   static IntRange rem(IntRange L, IntRange R) {
11513     // The result of a remainder can't be larger than the result of
11514     // either side. The sign of the result is the sign of the LHS.
11515     bool Unsigned = L.NonNegative;
11516     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11517                     Unsigned);
11518   }
11519 };
11520 
11521 } // namespace
11522 
11523 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11524                               unsigned MaxWidth) {
11525   if (value.isSigned() && value.isNegative())
11526     return IntRange(value.getMinSignedBits(), false);
11527 
11528   if (value.getBitWidth() > MaxWidth)
11529     value = value.trunc(MaxWidth);
11530 
11531   // isNonNegative() just checks the sign bit without considering
11532   // signedness.
11533   return IntRange(value.getActiveBits(), true);
11534 }
11535 
11536 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11537                               unsigned MaxWidth) {
11538   if (result.isInt())
11539     return GetValueRange(C, result.getInt(), MaxWidth);
11540 
11541   if (result.isVector()) {
11542     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11543     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11544       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11545       R = IntRange::join(R, El);
11546     }
11547     return R;
11548   }
11549 
11550   if (result.isComplexInt()) {
11551     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11552     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11553     return IntRange::join(R, I);
11554   }
11555 
11556   // This can happen with lossless casts to intptr_t of "based" lvalues.
11557   // Assume it might use arbitrary bits.
11558   // FIXME: The only reason we need to pass the type in here is to get
11559   // the sign right on this one case.  It would be nice if APValue
11560   // preserved this.
11561   assert(result.isLValue() || result.isAddrLabelDiff());
11562   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11563 }
11564 
11565 static QualType GetExprType(const Expr *E) {
11566   QualType Ty = E->getType();
11567   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11568     Ty = AtomicRHS->getValueType();
11569   return Ty;
11570 }
11571 
11572 /// Pseudo-evaluate the given integer expression, estimating the
11573 /// range of values it might take.
11574 ///
11575 /// \param MaxWidth The width to which the value will be truncated.
11576 /// \param Approximate If \c true, return a likely range for the result: in
11577 ///        particular, assume that arithmetic on narrower types doesn't leave
11578 ///        those types. If \c false, return a range including all possible
11579 ///        result values.
11580 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11581                              bool InConstantContext, bool Approximate) {
11582   E = E->IgnoreParens();
11583 
11584   // Try a full evaluation first.
11585   Expr::EvalResult result;
11586   if (E->EvaluateAsRValue(result, C, InConstantContext))
11587     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11588 
11589   // I think we only want to look through implicit casts here; if the
11590   // user has an explicit widening cast, we should treat the value as
11591   // being of the new, wider type.
11592   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11593     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11594       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11595                           Approximate);
11596 
11597     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11598 
11599     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11600                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11601 
11602     // Assume that non-integer casts can span the full range of the type.
11603     if (!isIntegerCast)
11604       return OutputTypeRange;
11605 
11606     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11607                                      std::min(MaxWidth, OutputTypeRange.Width),
11608                                      InConstantContext, Approximate);
11609 
11610     // Bail out if the subexpr's range is as wide as the cast type.
11611     if (SubRange.Width >= OutputTypeRange.Width)
11612       return OutputTypeRange;
11613 
11614     // Otherwise, we take the smaller width, and we're non-negative if
11615     // either the output type or the subexpr is.
11616     return IntRange(SubRange.Width,
11617                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11618   }
11619 
11620   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11621     // If we can fold the condition, just take that operand.
11622     bool CondResult;
11623     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11624       return GetExprRange(C,
11625                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11626                           MaxWidth, InConstantContext, Approximate);
11627 
11628     // Otherwise, conservatively merge.
11629     // GetExprRange requires an integer expression, but a throw expression
11630     // results in a void type.
11631     Expr *E = CO->getTrueExpr();
11632     IntRange L = E->getType()->isVoidType()
11633                      ? IntRange{0, true}
11634                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11635     E = CO->getFalseExpr();
11636     IntRange R = E->getType()->isVoidType()
11637                      ? IntRange{0, true}
11638                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11639     return IntRange::join(L, R);
11640   }
11641 
11642   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11643     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11644 
11645     switch (BO->getOpcode()) {
11646     case BO_Cmp:
11647       llvm_unreachable("builtin <=> should have class type");
11648 
11649     // Boolean-valued operations are single-bit and positive.
11650     case BO_LAnd:
11651     case BO_LOr:
11652     case BO_LT:
11653     case BO_GT:
11654     case BO_LE:
11655     case BO_GE:
11656     case BO_EQ:
11657     case BO_NE:
11658       return IntRange::forBoolType();
11659 
11660     // The type of the assignments is the type of the LHS, so the RHS
11661     // is not necessarily the same type.
11662     case BO_MulAssign:
11663     case BO_DivAssign:
11664     case BO_RemAssign:
11665     case BO_AddAssign:
11666     case BO_SubAssign:
11667     case BO_XorAssign:
11668     case BO_OrAssign:
11669       // TODO: bitfields?
11670       return IntRange::forValueOfType(C, GetExprType(E));
11671 
11672     // Simple assignments just pass through the RHS, which will have
11673     // been coerced to the LHS type.
11674     case BO_Assign:
11675       // TODO: bitfields?
11676       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11677                           Approximate);
11678 
11679     // Operations with opaque sources are black-listed.
11680     case BO_PtrMemD:
11681     case BO_PtrMemI:
11682       return IntRange::forValueOfType(C, GetExprType(E));
11683 
11684     // Bitwise-and uses the *infinum* of the two source ranges.
11685     case BO_And:
11686     case BO_AndAssign:
11687       Combine = IntRange::bit_and;
11688       break;
11689 
11690     // Left shift gets black-listed based on a judgement call.
11691     case BO_Shl:
11692       // ...except that we want to treat '1 << (blah)' as logically
11693       // positive.  It's an important idiom.
11694       if (IntegerLiteral *I
11695             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11696         if (I->getValue() == 1) {
11697           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11698           return IntRange(R.Width, /*NonNegative*/ true);
11699         }
11700       }
11701       LLVM_FALLTHROUGH;
11702 
11703     case BO_ShlAssign:
11704       return IntRange::forValueOfType(C, GetExprType(E));
11705 
11706     // Right shift by a constant can narrow its left argument.
11707     case BO_Shr:
11708     case BO_ShrAssign: {
11709       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11710                                 Approximate);
11711 
11712       // If the shift amount is a positive constant, drop the width by
11713       // that much.
11714       if (Optional<llvm::APSInt> shift =
11715               BO->getRHS()->getIntegerConstantExpr(C)) {
11716         if (shift->isNonNegative()) {
11717           unsigned zext = shift->getZExtValue();
11718           if (zext >= L.Width)
11719             L.Width = (L.NonNegative ? 0 : 1);
11720           else
11721             L.Width -= zext;
11722         }
11723       }
11724 
11725       return L;
11726     }
11727 
11728     // Comma acts as its right operand.
11729     case BO_Comma:
11730       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11731                           Approximate);
11732 
11733     case BO_Add:
11734       if (!Approximate)
11735         Combine = IntRange::sum;
11736       break;
11737 
11738     case BO_Sub:
11739       if (BO->getLHS()->getType()->isPointerType())
11740         return IntRange::forValueOfType(C, GetExprType(E));
11741       if (!Approximate)
11742         Combine = IntRange::difference;
11743       break;
11744 
11745     case BO_Mul:
11746       if (!Approximate)
11747         Combine = IntRange::product;
11748       break;
11749 
11750     // The width of a division result is mostly determined by the size
11751     // of the LHS.
11752     case BO_Div: {
11753       // Don't 'pre-truncate' the operands.
11754       unsigned opWidth = C.getIntWidth(GetExprType(E));
11755       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11756                                 Approximate);
11757 
11758       // If the divisor is constant, use that.
11759       if (Optional<llvm::APSInt> divisor =
11760               BO->getRHS()->getIntegerConstantExpr(C)) {
11761         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11762         if (log2 >= L.Width)
11763           L.Width = (L.NonNegative ? 0 : 1);
11764         else
11765           L.Width = std::min(L.Width - log2, MaxWidth);
11766         return L;
11767       }
11768 
11769       // Otherwise, just use the LHS's width.
11770       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11771       // could be -1.
11772       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11773                                 Approximate);
11774       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11775     }
11776 
11777     case BO_Rem:
11778       Combine = IntRange::rem;
11779       break;
11780 
11781     // The default behavior is okay for these.
11782     case BO_Xor:
11783     case BO_Or:
11784       break;
11785     }
11786 
11787     // Combine the two ranges, but limit the result to the type in which we
11788     // performed the computation.
11789     QualType T = GetExprType(E);
11790     unsigned opWidth = C.getIntWidth(T);
11791     IntRange L =
11792         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11793     IntRange R =
11794         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11795     IntRange C = Combine(L, R);
11796     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11797     C.Width = std::min(C.Width, MaxWidth);
11798     return C;
11799   }
11800 
11801   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11802     switch (UO->getOpcode()) {
11803     // Boolean-valued operations are white-listed.
11804     case UO_LNot:
11805       return IntRange::forBoolType();
11806 
11807     // Operations with opaque sources are black-listed.
11808     case UO_Deref:
11809     case UO_AddrOf: // should be impossible
11810       return IntRange::forValueOfType(C, GetExprType(E));
11811 
11812     default:
11813       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11814                           Approximate);
11815     }
11816   }
11817 
11818   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11819     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11820                         Approximate);
11821 
11822   if (const auto *BitField = E->getSourceBitField())
11823     return IntRange(BitField->getBitWidthValue(C),
11824                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11825 
11826   return IntRange::forValueOfType(C, GetExprType(E));
11827 }
11828 
11829 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11830                              bool InConstantContext, bool Approximate) {
11831   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11832                       Approximate);
11833 }
11834 
11835 /// Checks whether the given value, which currently has the given
11836 /// source semantics, has the same value when coerced through the
11837 /// target semantics.
11838 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11839                                  const llvm::fltSemantics &Src,
11840                                  const llvm::fltSemantics &Tgt) {
11841   llvm::APFloat truncated = value;
11842 
11843   bool ignored;
11844   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11845   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11846 
11847   return truncated.bitwiseIsEqual(value);
11848 }
11849 
11850 /// Checks whether the given value, which currently has the given
11851 /// source semantics, has the same value when coerced through the
11852 /// target semantics.
11853 ///
11854 /// The value might be a vector of floats (or a complex number).
11855 static bool IsSameFloatAfterCast(const APValue &value,
11856                                  const llvm::fltSemantics &Src,
11857                                  const llvm::fltSemantics &Tgt) {
11858   if (value.isFloat())
11859     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11860 
11861   if (value.isVector()) {
11862     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11863       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11864         return false;
11865     return true;
11866   }
11867 
11868   assert(value.isComplexFloat());
11869   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11870           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11871 }
11872 
11873 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11874                                        bool IsListInit = false);
11875 
11876 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11877   // Suppress cases where we are comparing against an enum constant.
11878   if (const DeclRefExpr *DR =
11879       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11880     if (isa<EnumConstantDecl>(DR->getDecl()))
11881       return true;
11882 
11883   // Suppress cases where the value is expanded from a macro, unless that macro
11884   // is how a language represents a boolean literal. This is the case in both C
11885   // and Objective-C.
11886   SourceLocation BeginLoc = E->getBeginLoc();
11887   if (BeginLoc.isMacroID()) {
11888     StringRef MacroName = Lexer::getImmediateMacroName(
11889         BeginLoc, S.getSourceManager(), S.getLangOpts());
11890     return MacroName != "YES" && MacroName != "NO" &&
11891            MacroName != "true" && MacroName != "false";
11892   }
11893 
11894   return false;
11895 }
11896 
11897 static bool isKnownToHaveUnsignedValue(Expr *E) {
11898   return E->getType()->isIntegerType() &&
11899          (!E->getType()->isSignedIntegerType() ||
11900           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11901 }
11902 
11903 namespace {
11904 /// The promoted range of values of a type. In general this has the
11905 /// following structure:
11906 ///
11907 ///     |-----------| . . . |-----------|
11908 ///     ^           ^       ^           ^
11909 ///    Min       HoleMin  HoleMax      Max
11910 ///
11911 /// ... where there is only a hole if a signed type is promoted to unsigned
11912 /// (in which case Min and Max are the smallest and largest representable
11913 /// values).
11914 struct PromotedRange {
11915   // Min, or HoleMax if there is a hole.
11916   llvm::APSInt PromotedMin;
11917   // Max, or HoleMin if there is a hole.
11918   llvm::APSInt PromotedMax;
11919 
11920   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11921     if (R.Width == 0)
11922       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11923     else if (R.Width >= BitWidth && !Unsigned) {
11924       // Promotion made the type *narrower*. This happens when promoting
11925       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11926       // Treat all values of 'signed int' as being in range for now.
11927       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11928       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11929     } else {
11930       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11931                         .extOrTrunc(BitWidth);
11932       PromotedMin.setIsUnsigned(Unsigned);
11933 
11934       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11935                         .extOrTrunc(BitWidth);
11936       PromotedMax.setIsUnsigned(Unsigned);
11937     }
11938   }
11939 
11940   // Determine whether this range is contiguous (has no hole).
11941   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11942 
11943   // Where a constant value is within the range.
11944   enum ComparisonResult {
11945     LT = 0x1,
11946     LE = 0x2,
11947     GT = 0x4,
11948     GE = 0x8,
11949     EQ = 0x10,
11950     NE = 0x20,
11951     InRangeFlag = 0x40,
11952 
11953     Less = LE | LT | NE,
11954     Min = LE | InRangeFlag,
11955     InRange = InRangeFlag,
11956     Max = GE | InRangeFlag,
11957     Greater = GE | GT | NE,
11958 
11959     OnlyValue = LE | GE | EQ | InRangeFlag,
11960     InHole = NE
11961   };
11962 
11963   ComparisonResult compare(const llvm::APSInt &Value) const {
11964     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11965            Value.isUnsigned() == PromotedMin.isUnsigned());
11966     if (!isContiguous()) {
11967       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11968       if (Value.isMinValue()) return Min;
11969       if (Value.isMaxValue()) return Max;
11970       if (Value >= PromotedMin) return InRange;
11971       if (Value <= PromotedMax) return InRange;
11972       return InHole;
11973     }
11974 
11975     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11976     case -1: return Less;
11977     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11978     case 1:
11979       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11980       case -1: return InRange;
11981       case 0: return Max;
11982       case 1: return Greater;
11983       }
11984     }
11985 
11986     llvm_unreachable("impossible compare result");
11987   }
11988 
11989   static llvm::Optional<StringRef>
11990   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11991     if (Op == BO_Cmp) {
11992       ComparisonResult LTFlag = LT, GTFlag = GT;
11993       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11994 
11995       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11996       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11997       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11998       return llvm::None;
11999     }
12000 
12001     ComparisonResult TrueFlag, FalseFlag;
12002     if (Op == BO_EQ) {
12003       TrueFlag = EQ;
12004       FalseFlag = NE;
12005     } else if (Op == BO_NE) {
12006       TrueFlag = NE;
12007       FalseFlag = EQ;
12008     } else {
12009       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12010         TrueFlag = LT;
12011         FalseFlag = GE;
12012       } else {
12013         TrueFlag = GT;
12014         FalseFlag = LE;
12015       }
12016       if (Op == BO_GE || Op == BO_LE)
12017         std::swap(TrueFlag, FalseFlag);
12018     }
12019     if (R & TrueFlag)
12020       return StringRef("true");
12021     if (R & FalseFlag)
12022       return StringRef("false");
12023     return llvm::None;
12024   }
12025 };
12026 }
12027 
12028 static bool HasEnumType(Expr *E) {
12029   // Strip off implicit integral promotions.
12030   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12031     if (ICE->getCastKind() != CK_IntegralCast &&
12032         ICE->getCastKind() != CK_NoOp)
12033       break;
12034     E = ICE->getSubExpr();
12035   }
12036 
12037   return E->getType()->isEnumeralType();
12038 }
12039 
12040 static int classifyConstantValue(Expr *Constant) {
12041   // The values of this enumeration are used in the diagnostics
12042   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12043   enum ConstantValueKind {
12044     Miscellaneous = 0,
12045     LiteralTrue,
12046     LiteralFalse
12047   };
12048   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12049     return BL->getValue() ? ConstantValueKind::LiteralTrue
12050                           : ConstantValueKind::LiteralFalse;
12051   return ConstantValueKind::Miscellaneous;
12052 }
12053 
12054 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
12055                                         Expr *Constant, Expr *Other,
12056                                         const llvm::APSInt &Value,
12057                                         bool RhsConstant) {
12058   if (S.inTemplateInstantiation())
12059     return false;
12060 
12061   Expr *OriginalOther = Other;
12062 
12063   Constant = Constant->IgnoreParenImpCasts();
12064   Other = Other->IgnoreParenImpCasts();
12065 
12066   // Suppress warnings on tautological comparisons between values of the same
12067   // enumeration type. There are only two ways we could warn on this:
12068   //  - If the constant is outside the range of representable values of
12069   //    the enumeration. In such a case, we should warn about the cast
12070   //    to enumeration type, not about the comparison.
12071   //  - If the constant is the maximum / minimum in-range value. For an
12072   //    enumeratin type, such comparisons can be meaningful and useful.
12073   if (Constant->getType()->isEnumeralType() &&
12074       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12075     return false;
12076 
12077   IntRange OtherValueRange = GetExprRange(
12078       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
12079 
12080   QualType OtherT = Other->getType();
12081   if (const auto *AT = OtherT->getAs<AtomicType>())
12082     OtherT = AT->getValueType();
12083   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12084 
12085   // Special case for ObjC BOOL on targets where its a typedef for a signed char
12086   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12087   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12088                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
12089                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12090 
12091   // Whether we're treating Other as being a bool because of the form of
12092   // expression despite it having another type (typically 'int' in C).
12093   bool OtherIsBooleanDespiteType =
12094       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12095   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12096     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
12097 
12098   // Check if all values in the range of possible values of this expression
12099   // lead to the same comparison outcome.
12100   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
12101                                         Value.isUnsigned());
12102   auto Cmp = OtherPromotedValueRange.compare(Value);
12103   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12104   if (!Result)
12105     return false;
12106 
12107   // Also consider the range determined by the type alone. This allows us to
12108   // classify the warning under the proper diagnostic group.
12109   bool TautologicalTypeCompare = false;
12110   {
12111     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12112                                          Value.isUnsigned());
12113     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12114     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12115                                                        RhsConstant)) {
12116       TautologicalTypeCompare = true;
12117       Cmp = TypeCmp;
12118       Result = TypeResult;
12119     }
12120   }
12121 
12122   // Don't warn if the non-constant operand actually always evaluates to the
12123   // same value.
12124   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
12125     return false;
12126 
12127   // Suppress the diagnostic for an in-range comparison if the constant comes
12128   // from a macro or enumerator. We don't want to diagnose
12129   //
12130   //   some_long_value <= INT_MAX
12131   //
12132   // when sizeof(int) == sizeof(long).
12133   bool InRange = Cmp & PromotedRange::InRangeFlag;
12134   if (InRange && IsEnumConstOrFromMacro(S, Constant))
12135     return false;
12136 
12137   // A comparison of an unsigned bit-field against 0 is really a type problem,
12138   // even though at the type level the bit-field might promote to 'signed int'.
12139   if (Other->refersToBitField() && InRange && Value == 0 &&
12140       Other->getType()->isUnsignedIntegerOrEnumerationType())
12141     TautologicalTypeCompare = true;
12142 
12143   // If this is a comparison to an enum constant, include that
12144   // constant in the diagnostic.
12145   const EnumConstantDecl *ED = nullptr;
12146   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
12147     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12148 
12149   // Should be enough for uint128 (39 decimal digits)
12150   SmallString<64> PrettySourceValue;
12151   llvm::raw_svector_ostream OS(PrettySourceValue);
12152   if (ED) {
12153     OS << '\'' << *ED << "' (" << Value << ")";
12154   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12155                Constant->IgnoreParenImpCasts())) {
12156     OS << (BL->getValue() ? "YES" : "NO");
12157   } else {
12158     OS << Value;
12159   }
12160 
12161   if (!TautologicalTypeCompare) {
12162     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12163         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
12164         << E->getOpcodeStr() << OS.str() << *Result
12165         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12166     return true;
12167   }
12168 
12169   if (IsObjCSignedCharBool) {
12170     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12171                           S.PDiag(diag::warn_tautological_compare_objc_bool)
12172                               << OS.str() << *Result);
12173     return true;
12174   }
12175 
12176   // FIXME: We use a somewhat different formatting for the in-range cases and
12177   // cases involving boolean values for historical reasons. We should pick a
12178   // consistent way of presenting these diagnostics.
12179   if (!InRange || Other->isKnownToHaveBooleanValue()) {
12180 
12181     S.DiagRuntimeBehavior(
12182         E->getOperatorLoc(), E,
12183         S.PDiag(!InRange ? diag::warn_out_of_range_compare
12184                          : diag::warn_tautological_bool_compare)
12185             << OS.str() << classifyConstantValue(Constant) << OtherT
12186             << OtherIsBooleanDespiteType << *Result
12187             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12188   } else {
12189     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12190     unsigned Diag =
12191         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12192             ? (HasEnumType(OriginalOther)
12193                    ? diag::warn_unsigned_enum_always_true_comparison
12194                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12195                               : diag::warn_unsigned_always_true_comparison)
12196             : diag::warn_tautological_constant_compare;
12197 
12198     S.Diag(E->getOperatorLoc(), Diag)
12199         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12200         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12201   }
12202 
12203   return true;
12204 }
12205 
12206 /// Analyze the operands of the given comparison.  Implements the
12207 /// fallback case from AnalyzeComparison.
12208 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12209   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12210   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12211 }
12212 
12213 /// Implements -Wsign-compare.
12214 ///
12215 /// \param E the binary operator to check for warnings
12216 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12217   // The type the comparison is being performed in.
12218   QualType T = E->getLHS()->getType();
12219 
12220   // Only analyze comparison operators where both sides have been converted to
12221   // the same type.
12222   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12223     return AnalyzeImpConvsInComparison(S, E);
12224 
12225   // Don't analyze value-dependent comparisons directly.
12226   if (E->isValueDependent())
12227     return AnalyzeImpConvsInComparison(S, E);
12228 
12229   Expr *LHS = E->getLHS();
12230   Expr *RHS = E->getRHS();
12231 
12232   if (T->isIntegralType(S.Context)) {
12233     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
12234     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
12235 
12236     // We don't care about expressions whose result is a constant.
12237     if (RHSValue && LHSValue)
12238       return AnalyzeImpConvsInComparison(S, E);
12239 
12240     // We only care about expressions where just one side is literal
12241     if ((bool)RHSValue ^ (bool)LHSValue) {
12242       // Is the constant on the RHS or LHS?
12243       const bool RhsConstant = (bool)RHSValue;
12244       Expr *Const = RhsConstant ? RHS : LHS;
12245       Expr *Other = RhsConstant ? LHS : RHS;
12246       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12247 
12248       // Check whether an integer constant comparison results in a value
12249       // of 'true' or 'false'.
12250       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12251         return AnalyzeImpConvsInComparison(S, E);
12252     }
12253   }
12254 
12255   if (!T->hasUnsignedIntegerRepresentation()) {
12256     // We don't do anything special if this isn't an unsigned integral
12257     // comparison:  we're only interested in integral comparisons, and
12258     // signed comparisons only happen in cases we don't care to warn about.
12259     return AnalyzeImpConvsInComparison(S, E);
12260   }
12261 
12262   LHS = LHS->IgnoreParenImpCasts();
12263   RHS = RHS->IgnoreParenImpCasts();
12264 
12265   if (!S.getLangOpts().CPlusPlus) {
12266     // Avoid warning about comparison of integers with different signs when
12267     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12268     // the type of `E`.
12269     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12270       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12271     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12272       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12273   }
12274 
12275   // Check to see if one of the (unmodified) operands is of different
12276   // signedness.
12277   Expr *signedOperand, *unsignedOperand;
12278   if (LHS->getType()->hasSignedIntegerRepresentation()) {
12279     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12280            "unsigned comparison between two signed integer expressions?");
12281     signedOperand = LHS;
12282     unsignedOperand = RHS;
12283   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12284     signedOperand = RHS;
12285     unsignedOperand = LHS;
12286   } else {
12287     return AnalyzeImpConvsInComparison(S, E);
12288   }
12289 
12290   // Otherwise, calculate the effective range of the signed operand.
12291   IntRange signedRange = GetExprRange(
12292       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
12293 
12294   // Go ahead and analyze implicit conversions in the operands.  Note
12295   // that we skip the implicit conversions on both sides.
12296   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
12297   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
12298 
12299   // If the signed range is non-negative, -Wsign-compare won't fire.
12300   if (signedRange.NonNegative)
12301     return;
12302 
12303   // For (in)equality comparisons, if the unsigned operand is a
12304   // constant which cannot collide with a overflowed signed operand,
12305   // then reinterpreting the signed operand as unsigned will not
12306   // change the result of the comparison.
12307   if (E->isEqualityOp()) {
12308     unsigned comparisonWidth = S.Context.getIntWidth(T);
12309     IntRange unsignedRange =
12310         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
12311                      /*Approximate*/ true);
12312 
12313     // We should never be unable to prove that the unsigned operand is
12314     // non-negative.
12315     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
12316 
12317     if (unsignedRange.Width < comparisonWidth)
12318       return;
12319   }
12320 
12321   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12322                         S.PDiag(diag::warn_mixed_sign_comparison)
12323                             << LHS->getType() << RHS->getType()
12324                             << LHS->getSourceRange() << RHS->getSourceRange());
12325 }
12326 
12327 /// Analyzes an attempt to assign the given value to a bitfield.
12328 ///
12329 /// Returns true if there was something fishy about the attempt.
12330 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12331                                       SourceLocation InitLoc) {
12332   assert(Bitfield->isBitField());
12333   if (Bitfield->isInvalidDecl())
12334     return false;
12335 
12336   // White-list bool bitfields.
12337   QualType BitfieldType = Bitfield->getType();
12338   if (BitfieldType->isBooleanType())
12339      return false;
12340 
12341   if (BitfieldType->isEnumeralType()) {
12342     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12343     // If the underlying enum type was not explicitly specified as an unsigned
12344     // type and the enum contain only positive values, MSVC++ will cause an
12345     // inconsistency by storing this as a signed type.
12346     if (S.getLangOpts().CPlusPlus11 &&
12347         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12348         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12349         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12350       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12351           << BitfieldEnumDecl;
12352     }
12353   }
12354 
12355   if (Bitfield->getType()->isBooleanType())
12356     return false;
12357 
12358   // Ignore value- or type-dependent expressions.
12359   if (Bitfield->getBitWidth()->isValueDependent() ||
12360       Bitfield->getBitWidth()->isTypeDependent() ||
12361       Init->isValueDependent() ||
12362       Init->isTypeDependent())
12363     return false;
12364 
12365   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12366   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12367 
12368   Expr::EvalResult Result;
12369   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12370                                    Expr::SE_AllowSideEffects)) {
12371     // The RHS is not constant.  If the RHS has an enum type, make sure the
12372     // bitfield is wide enough to hold all the values of the enum without
12373     // truncation.
12374     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12375       EnumDecl *ED = EnumTy->getDecl();
12376       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12377 
12378       // Enum types are implicitly signed on Windows, so check if there are any
12379       // negative enumerators to see if the enum was intended to be signed or
12380       // not.
12381       bool SignedEnum = ED->getNumNegativeBits() > 0;
12382 
12383       // Check for surprising sign changes when assigning enum values to a
12384       // bitfield of different signedness.  If the bitfield is signed and we
12385       // have exactly the right number of bits to store this unsigned enum,
12386       // suggest changing the enum to an unsigned type. This typically happens
12387       // on Windows where unfixed enums always use an underlying type of 'int'.
12388       unsigned DiagID = 0;
12389       if (SignedEnum && !SignedBitfield) {
12390         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12391       } else if (SignedBitfield && !SignedEnum &&
12392                  ED->getNumPositiveBits() == FieldWidth) {
12393         DiagID = diag::warn_signed_bitfield_enum_conversion;
12394       }
12395 
12396       if (DiagID) {
12397         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12398         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12399         SourceRange TypeRange =
12400             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12401         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12402             << SignedEnum << TypeRange;
12403       }
12404 
12405       // Compute the required bitwidth. If the enum has negative values, we need
12406       // one more bit than the normal number of positive bits to represent the
12407       // sign bit.
12408       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12409                                                   ED->getNumNegativeBits())
12410                                        : ED->getNumPositiveBits();
12411 
12412       // Check the bitwidth.
12413       if (BitsNeeded > FieldWidth) {
12414         Expr *WidthExpr = Bitfield->getBitWidth();
12415         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12416             << Bitfield << ED;
12417         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12418             << BitsNeeded << ED << WidthExpr->getSourceRange();
12419       }
12420     }
12421 
12422     return false;
12423   }
12424 
12425   llvm::APSInt Value = Result.Val.getInt();
12426 
12427   unsigned OriginalWidth = Value.getBitWidth();
12428 
12429   if (!Value.isSigned() || Value.isNegative())
12430     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12431       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12432         OriginalWidth = Value.getMinSignedBits();
12433 
12434   if (OriginalWidth <= FieldWidth)
12435     return false;
12436 
12437   // Compute the value which the bitfield will contain.
12438   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12439   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12440 
12441   // Check whether the stored value is equal to the original value.
12442   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12443   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12444     return false;
12445 
12446   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12447   // therefore don't strictly fit into a signed bitfield of width 1.
12448   if (FieldWidth == 1 && Value == 1)
12449     return false;
12450 
12451   std::string PrettyValue = toString(Value, 10);
12452   std::string PrettyTrunc = toString(TruncatedValue, 10);
12453 
12454   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12455     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12456     << Init->getSourceRange();
12457 
12458   return true;
12459 }
12460 
12461 /// Analyze the given simple or compound assignment for warning-worthy
12462 /// operations.
12463 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12464   // Just recurse on the LHS.
12465   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12466 
12467   // We want to recurse on the RHS as normal unless we're assigning to
12468   // a bitfield.
12469   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12470     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12471                                   E->getOperatorLoc())) {
12472       // Recurse, ignoring any implicit conversions on the RHS.
12473       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12474                                         E->getOperatorLoc());
12475     }
12476   }
12477 
12478   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12479 
12480   // Diagnose implicitly sequentially-consistent atomic assignment.
12481   if (E->getLHS()->getType()->isAtomicType())
12482     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12483 }
12484 
12485 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12486 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12487                             SourceLocation CContext, unsigned diag,
12488                             bool pruneControlFlow = false) {
12489   if (pruneControlFlow) {
12490     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12491                           S.PDiag(diag)
12492                               << SourceType << T << E->getSourceRange()
12493                               << SourceRange(CContext));
12494     return;
12495   }
12496   S.Diag(E->getExprLoc(), diag)
12497     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12498 }
12499 
12500 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12501 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12502                             SourceLocation CContext,
12503                             unsigned diag, bool pruneControlFlow = false) {
12504   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12505 }
12506 
12507 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12508   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12509       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12510 }
12511 
12512 static void adornObjCBoolConversionDiagWithTernaryFixit(
12513     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12514   Expr *Ignored = SourceExpr->IgnoreImplicit();
12515   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12516     Ignored = OVE->getSourceExpr();
12517   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12518                      isa<BinaryOperator>(Ignored) ||
12519                      isa<CXXOperatorCallExpr>(Ignored);
12520   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12521   if (NeedsParens)
12522     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12523             << FixItHint::CreateInsertion(EndLoc, ")");
12524   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12525 }
12526 
12527 /// Diagnose an implicit cast from a floating point value to an integer value.
12528 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12529                                     SourceLocation CContext) {
12530   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12531   const bool PruneWarnings = S.inTemplateInstantiation();
12532 
12533   Expr *InnerE = E->IgnoreParenImpCasts();
12534   // We also want to warn on, e.g., "int i = -1.234"
12535   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12536     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12537       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12538 
12539   const bool IsLiteral =
12540       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12541 
12542   llvm::APFloat Value(0.0);
12543   bool IsConstant =
12544     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12545   if (!IsConstant) {
12546     if (isObjCSignedCharBool(S, T)) {
12547       return adornObjCBoolConversionDiagWithTernaryFixit(
12548           S, E,
12549           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12550               << E->getType());
12551     }
12552 
12553     return DiagnoseImpCast(S, E, T, CContext,
12554                            diag::warn_impcast_float_integer, PruneWarnings);
12555   }
12556 
12557   bool isExact = false;
12558 
12559   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12560                             T->hasUnsignedIntegerRepresentation());
12561   llvm::APFloat::opStatus Result = Value.convertToInteger(
12562       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12563 
12564   // FIXME: Force the precision of the source value down so we don't print
12565   // digits which are usually useless (we don't really care here if we
12566   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12567   // would automatically print the shortest representation, but it's a bit
12568   // tricky to implement.
12569   SmallString<16> PrettySourceValue;
12570   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12571   precision = (precision * 59 + 195) / 196;
12572   Value.toString(PrettySourceValue, precision);
12573 
12574   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12575     return adornObjCBoolConversionDiagWithTernaryFixit(
12576         S, E,
12577         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12578             << PrettySourceValue);
12579   }
12580 
12581   if (Result == llvm::APFloat::opOK && isExact) {
12582     if (IsLiteral) return;
12583     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12584                            PruneWarnings);
12585   }
12586 
12587   // Conversion of a floating-point value to a non-bool integer where the
12588   // integral part cannot be represented by the integer type is undefined.
12589   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12590     return DiagnoseImpCast(
12591         S, E, T, CContext,
12592         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12593                   : diag::warn_impcast_float_to_integer_out_of_range,
12594         PruneWarnings);
12595 
12596   unsigned DiagID = 0;
12597   if (IsLiteral) {
12598     // Warn on floating point literal to integer.
12599     DiagID = diag::warn_impcast_literal_float_to_integer;
12600   } else if (IntegerValue == 0) {
12601     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12602       return DiagnoseImpCast(S, E, T, CContext,
12603                              diag::warn_impcast_float_integer, PruneWarnings);
12604     }
12605     // Warn on non-zero to zero conversion.
12606     DiagID = diag::warn_impcast_float_to_integer_zero;
12607   } else {
12608     if (IntegerValue.isUnsigned()) {
12609       if (!IntegerValue.isMaxValue()) {
12610         return DiagnoseImpCast(S, E, T, CContext,
12611                                diag::warn_impcast_float_integer, PruneWarnings);
12612       }
12613     } else {  // IntegerValue.isSigned()
12614       if (!IntegerValue.isMaxSignedValue() &&
12615           !IntegerValue.isMinSignedValue()) {
12616         return DiagnoseImpCast(S, E, T, CContext,
12617                                diag::warn_impcast_float_integer, PruneWarnings);
12618       }
12619     }
12620     // Warn on evaluatable floating point expression to integer conversion.
12621     DiagID = diag::warn_impcast_float_to_integer;
12622   }
12623 
12624   SmallString<16> PrettyTargetValue;
12625   if (IsBool)
12626     PrettyTargetValue = Value.isZero() ? "false" : "true";
12627   else
12628     IntegerValue.toString(PrettyTargetValue);
12629 
12630   if (PruneWarnings) {
12631     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12632                           S.PDiag(DiagID)
12633                               << E->getType() << T.getUnqualifiedType()
12634                               << PrettySourceValue << PrettyTargetValue
12635                               << E->getSourceRange() << SourceRange(CContext));
12636   } else {
12637     S.Diag(E->getExprLoc(), DiagID)
12638         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12639         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12640   }
12641 }
12642 
12643 /// Analyze the given compound assignment for the possible losing of
12644 /// floating-point precision.
12645 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12646   assert(isa<CompoundAssignOperator>(E) &&
12647          "Must be compound assignment operation");
12648   // Recurse on the LHS and RHS in here
12649   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12650   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12651 
12652   if (E->getLHS()->getType()->isAtomicType())
12653     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12654 
12655   // Now check the outermost expression
12656   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12657   const auto *RBT = cast<CompoundAssignOperator>(E)
12658                         ->getComputationResultType()
12659                         ->getAs<BuiltinType>();
12660 
12661   // The below checks assume source is floating point.
12662   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12663 
12664   // If source is floating point but target is an integer.
12665   if (ResultBT->isInteger())
12666     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12667                            E->getExprLoc(), diag::warn_impcast_float_integer);
12668 
12669   if (!ResultBT->isFloatingPoint())
12670     return;
12671 
12672   // If both source and target are floating points, warn about losing precision.
12673   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12674       QualType(ResultBT, 0), QualType(RBT, 0));
12675   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12676     // warn about dropping FP rank.
12677     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12678                     diag::warn_impcast_float_result_precision);
12679 }
12680 
12681 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12682                                       IntRange Range) {
12683   if (!Range.Width) return "0";
12684 
12685   llvm::APSInt ValueInRange = Value;
12686   ValueInRange.setIsSigned(!Range.NonNegative);
12687   ValueInRange = ValueInRange.trunc(Range.Width);
12688   return toString(ValueInRange, 10);
12689 }
12690 
12691 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12692   if (!isa<ImplicitCastExpr>(Ex))
12693     return false;
12694 
12695   Expr *InnerE = Ex->IgnoreParenImpCasts();
12696   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12697   const Type *Source =
12698     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12699   if (Target->isDependentType())
12700     return false;
12701 
12702   const BuiltinType *FloatCandidateBT =
12703     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12704   const Type *BoolCandidateType = ToBool ? Target : Source;
12705 
12706   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12707           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12708 }
12709 
12710 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12711                                              SourceLocation CC) {
12712   unsigned NumArgs = TheCall->getNumArgs();
12713   for (unsigned i = 0; i < NumArgs; ++i) {
12714     Expr *CurrA = TheCall->getArg(i);
12715     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12716       continue;
12717 
12718     bool IsSwapped = ((i > 0) &&
12719         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12720     IsSwapped |= ((i < (NumArgs - 1)) &&
12721         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12722     if (IsSwapped) {
12723       // Warn on this floating-point to bool conversion.
12724       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12725                       CurrA->getType(), CC,
12726                       diag::warn_impcast_floating_point_to_bool);
12727     }
12728   }
12729 }
12730 
12731 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12732                                    SourceLocation CC) {
12733   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12734                         E->getExprLoc()))
12735     return;
12736 
12737   // Don't warn on functions which have return type nullptr_t.
12738   if (isa<CallExpr>(E))
12739     return;
12740 
12741   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12742   const Expr::NullPointerConstantKind NullKind =
12743       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12744   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12745     return;
12746 
12747   // Return if target type is a safe conversion.
12748   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12749       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12750     return;
12751 
12752   SourceLocation Loc = E->getSourceRange().getBegin();
12753 
12754   // Venture through the macro stacks to get to the source of macro arguments.
12755   // The new location is a better location than the complete location that was
12756   // passed in.
12757   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12758   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12759 
12760   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12761   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12762     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12763         Loc, S.SourceMgr, S.getLangOpts());
12764     if (MacroName == "NULL")
12765       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12766   }
12767 
12768   // Only warn if the null and context location are in the same macro expansion.
12769   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12770     return;
12771 
12772   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12773       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12774       << FixItHint::CreateReplacement(Loc,
12775                                       S.getFixItZeroLiteralForType(T, Loc));
12776 }
12777 
12778 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12779                                   ObjCArrayLiteral *ArrayLiteral);
12780 
12781 static void
12782 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12783                            ObjCDictionaryLiteral *DictionaryLiteral);
12784 
12785 /// Check a single element within a collection literal against the
12786 /// target element type.
12787 static void checkObjCCollectionLiteralElement(Sema &S,
12788                                               QualType TargetElementType,
12789                                               Expr *Element,
12790                                               unsigned ElementKind) {
12791   // Skip a bitcast to 'id' or qualified 'id'.
12792   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12793     if (ICE->getCastKind() == CK_BitCast &&
12794         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12795       Element = ICE->getSubExpr();
12796   }
12797 
12798   QualType ElementType = Element->getType();
12799   ExprResult ElementResult(Element);
12800   if (ElementType->getAs<ObjCObjectPointerType>() &&
12801       S.CheckSingleAssignmentConstraints(TargetElementType,
12802                                          ElementResult,
12803                                          false, false)
12804         != Sema::Compatible) {
12805     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12806         << ElementType << ElementKind << TargetElementType
12807         << Element->getSourceRange();
12808   }
12809 
12810   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12811     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12812   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12813     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12814 }
12815 
12816 /// Check an Objective-C array literal being converted to the given
12817 /// target type.
12818 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12819                                   ObjCArrayLiteral *ArrayLiteral) {
12820   if (!S.NSArrayDecl)
12821     return;
12822 
12823   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12824   if (!TargetObjCPtr)
12825     return;
12826 
12827   if (TargetObjCPtr->isUnspecialized() ||
12828       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12829         != S.NSArrayDecl->getCanonicalDecl())
12830     return;
12831 
12832   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12833   if (TypeArgs.size() != 1)
12834     return;
12835 
12836   QualType TargetElementType = TypeArgs[0];
12837   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12838     checkObjCCollectionLiteralElement(S, TargetElementType,
12839                                       ArrayLiteral->getElement(I),
12840                                       0);
12841   }
12842 }
12843 
12844 /// Check an Objective-C dictionary literal being converted to the given
12845 /// target type.
12846 static void
12847 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12848                            ObjCDictionaryLiteral *DictionaryLiteral) {
12849   if (!S.NSDictionaryDecl)
12850     return;
12851 
12852   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12853   if (!TargetObjCPtr)
12854     return;
12855 
12856   if (TargetObjCPtr->isUnspecialized() ||
12857       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12858         != S.NSDictionaryDecl->getCanonicalDecl())
12859     return;
12860 
12861   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12862   if (TypeArgs.size() != 2)
12863     return;
12864 
12865   QualType TargetKeyType = TypeArgs[0];
12866   QualType TargetObjectType = TypeArgs[1];
12867   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12868     auto Element = DictionaryLiteral->getKeyValueElement(I);
12869     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12870     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12871   }
12872 }
12873 
12874 // Helper function to filter out cases for constant width constant conversion.
12875 // Don't warn on char array initialization or for non-decimal values.
12876 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12877                                           SourceLocation CC) {
12878   // If initializing from a constant, and the constant starts with '0',
12879   // then it is a binary, octal, or hexadecimal.  Allow these constants
12880   // to fill all the bits, even if there is a sign change.
12881   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12882     const char FirstLiteralCharacter =
12883         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12884     if (FirstLiteralCharacter == '0')
12885       return false;
12886   }
12887 
12888   // If the CC location points to a '{', and the type is char, then assume
12889   // assume it is an array initialization.
12890   if (CC.isValid() && T->isCharType()) {
12891     const char FirstContextCharacter =
12892         S.getSourceManager().getCharacterData(CC)[0];
12893     if (FirstContextCharacter == '{')
12894       return false;
12895   }
12896 
12897   return true;
12898 }
12899 
12900 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12901   const auto *IL = dyn_cast<IntegerLiteral>(E);
12902   if (!IL) {
12903     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12904       if (UO->getOpcode() == UO_Minus)
12905         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12906     }
12907   }
12908 
12909   return IL;
12910 }
12911 
12912 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12913   E = E->IgnoreParenImpCasts();
12914   SourceLocation ExprLoc = E->getExprLoc();
12915 
12916   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12917     BinaryOperator::Opcode Opc = BO->getOpcode();
12918     Expr::EvalResult Result;
12919     // Do not diagnose unsigned shifts.
12920     if (Opc == BO_Shl) {
12921       const auto *LHS = getIntegerLiteral(BO->getLHS());
12922       const auto *RHS = getIntegerLiteral(BO->getRHS());
12923       if (LHS && LHS->getValue() == 0)
12924         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12925       else if (!E->isValueDependent() && LHS && RHS &&
12926                RHS->getValue().isNonNegative() &&
12927                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12928         S.Diag(ExprLoc, diag::warn_left_shift_always)
12929             << (Result.Val.getInt() != 0);
12930       else if (E->getType()->isSignedIntegerType())
12931         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12932     }
12933   }
12934 
12935   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12936     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12937     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12938     if (!LHS || !RHS)
12939       return;
12940     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12941         (RHS->getValue() == 0 || RHS->getValue() == 1))
12942       // Do not diagnose common idioms.
12943       return;
12944     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12945       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12946   }
12947 }
12948 
12949 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12950                                     SourceLocation CC,
12951                                     bool *ICContext = nullptr,
12952                                     bool IsListInit = false) {
12953   if (E->isTypeDependent() || E->isValueDependent()) return;
12954 
12955   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12956   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12957   if (Source == Target) return;
12958   if (Target->isDependentType()) return;
12959 
12960   // If the conversion context location is invalid don't complain. We also
12961   // don't want to emit a warning if the issue occurs from the expansion of
12962   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12963   // delay this check as long as possible. Once we detect we are in that
12964   // scenario, we just return.
12965   if (CC.isInvalid())
12966     return;
12967 
12968   if (Source->isAtomicType())
12969     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12970 
12971   // Diagnose implicit casts to bool.
12972   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12973     if (isa<StringLiteral>(E))
12974       // Warn on string literal to bool.  Checks for string literals in logical
12975       // and expressions, for instance, assert(0 && "error here"), are
12976       // prevented by a check in AnalyzeImplicitConversions().
12977       return DiagnoseImpCast(S, E, T, CC,
12978                              diag::warn_impcast_string_literal_to_bool);
12979     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12980         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12981       // This covers the literal expressions that evaluate to Objective-C
12982       // objects.
12983       return DiagnoseImpCast(S, E, T, CC,
12984                              diag::warn_impcast_objective_c_literal_to_bool);
12985     }
12986     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12987       // Warn on pointer to bool conversion that is always true.
12988       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12989                                      SourceRange(CC));
12990     }
12991   }
12992 
12993   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12994   // is a typedef for signed char (macOS), then that constant value has to be 1
12995   // or 0.
12996   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12997     Expr::EvalResult Result;
12998     if (E->EvaluateAsInt(Result, S.getASTContext(),
12999                          Expr::SE_AllowSideEffects)) {
13000       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13001         adornObjCBoolConversionDiagWithTernaryFixit(
13002             S, E,
13003             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13004                 << toString(Result.Val.getInt(), 10));
13005       }
13006       return;
13007     }
13008   }
13009 
13010   // Check implicit casts from Objective-C collection literals to specialized
13011   // collection types, e.g., NSArray<NSString *> *.
13012   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13013     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
13014   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13015     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
13016 
13017   // Strip vector types.
13018   if (isa<VectorType>(Source)) {
13019     if (Target->isVLSTBuiltinType() &&
13020         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
13021                                          QualType(Source, 0)) ||
13022          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
13023                                             QualType(Source, 0))))
13024       return;
13025 
13026     if (!isa<VectorType>(Target)) {
13027       if (S.SourceMgr.isInSystemMacro(CC))
13028         return;
13029       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
13030     }
13031 
13032     // If the vector cast is cast between two vectors of the same size, it is
13033     // a bitcast, not a conversion.
13034     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
13035       return;
13036 
13037     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13038     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13039   }
13040   if (auto VecTy = dyn_cast<VectorType>(Target))
13041     Target = VecTy->getElementType().getTypePtr();
13042 
13043   // Strip complex types.
13044   if (isa<ComplexType>(Source)) {
13045     if (!isa<ComplexType>(Target)) {
13046       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13047         return;
13048 
13049       return DiagnoseImpCast(S, E, T, CC,
13050                              S.getLangOpts().CPlusPlus
13051                                  ? diag::err_impcast_complex_scalar
13052                                  : diag::warn_impcast_complex_scalar);
13053     }
13054 
13055     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13056     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13057   }
13058 
13059   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13060   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13061 
13062   // If the source is floating point...
13063   if (SourceBT && SourceBT->isFloatingPoint()) {
13064     // ...and the target is floating point...
13065     if (TargetBT && TargetBT->isFloatingPoint()) {
13066       // ...then warn if we're dropping FP rank.
13067 
13068       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
13069           QualType(SourceBT, 0), QualType(TargetBT, 0));
13070       if (Order > 0) {
13071         // Don't warn about float constants that are precisely
13072         // representable in the target type.
13073         Expr::EvalResult result;
13074         if (E->EvaluateAsRValue(result, S.Context)) {
13075           // Value might be a float, a float vector, or a float complex.
13076           if (IsSameFloatAfterCast(result.Val,
13077                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13078                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13079             return;
13080         }
13081 
13082         if (S.SourceMgr.isInSystemMacro(CC))
13083           return;
13084 
13085         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
13086       }
13087       // ... or possibly if we're increasing rank, too
13088       else if (Order < 0) {
13089         if (S.SourceMgr.isInSystemMacro(CC))
13090           return;
13091 
13092         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
13093       }
13094       return;
13095     }
13096 
13097     // If the target is integral, always warn.
13098     if (TargetBT && TargetBT->isInteger()) {
13099       if (S.SourceMgr.isInSystemMacro(CC))
13100         return;
13101 
13102       DiagnoseFloatingImpCast(S, E, T, CC);
13103     }
13104 
13105     // Detect the case where a call result is converted from floating-point to
13106     // to bool, and the final argument to the call is converted from bool, to
13107     // discover this typo:
13108     //
13109     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
13110     //
13111     // FIXME: This is an incredibly special case; is there some more general
13112     // way to detect this class of misplaced-parentheses bug?
13113     if (Target->isBooleanType() && isa<CallExpr>(E)) {
13114       // Check last argument of function call to see if it is an
13115       // implicit cast from a type matching the type the result
13116       // is being cast to.
13117       CallExpr *CEx = cast<CallExpr>(E);
13118       if (unsigned NumArgs = CEx->getNumArgs()) {
13119         Expr *LastA = CEx->getArg(NumArgs - 1);
13120         Expr *InnerE = LastA->IgnoreParenImpCasts();
13121         if (isa<ImplicitCastExpr>(LastA) &&
13122             InnerE->getType()->isBooleanType()) {
13123           // Warn on this floating-point to bool conversion
13124           DiagnoseImpCast(S, E, T, CC,
13125                           diag::warn_impcast_floating_point_to_bool);
13126         }
13127       }
13128     }
13129     return;
13130   }
13131 
13132   // Valid casts involving fixed point types should be accounted for here.
13133   if (Source->isFixedPointType()) {
13134     if (Target->isUnsaturatedFixedPointType()) {
13135       Expr::EvalResult Result;
13136       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
13137                                   S.isConstantEvaluated())) {
13138         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13139         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
13140         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
13141         if (Value > MaxVal || Value < MinVal) {
13142           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13143                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13144                                     << Value.toString() << T
13145                                     << E->getSourceRange()
13146                                     << clang::SourceRange(CC));
13147           return;
13148         }
13149       }
13150     } else if (Target->isIntegerType()) {
13151       Expr::EvalResult Result;
13152       if (!S.isConstantEvaluated() &&
13153           E->EvaluateAsFixedPoint(Result, S.Context,
13154                                   Expr::SE_AllowSideEffects)) {
13155         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13156 
13157         bool Overflowed;
13158         llvm::APSInt IntResult = FXResult.convertToInt(
13159             S.Context.getIntWidth(T),
13160             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
13161 
13162         if (Overflowed) {
13163           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13164                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13165                                     << FXResult.toString() << T
13166                                     << E->getSourceRange()
13167                                     << clang::SourceRange(CC));
13168           return;
13169         }
13170       }
13171     }
13172   } else if (Target->isUnsaturatedFixedPointType()) {
13173     if (Source->isIntegerType()) {
13174       Expr::EvalResult Result;
13175       if (!S.isConstantEvaluated() &&
13176           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
13177         llvm::APSInt Value = Result.Val.getInt();
13178 
13179         bool Overflowed;
13180         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13181             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
13182 
13183         if (Overflowed) {
13184           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13185                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13186                                     << toString(Value, /*Radix=*/10) << T
13187                                     << E->getSourceRange()
13188                                     << clang::SourceRange(CC));
13189           return;
13190         }
13191       }
13192     }
13193   }
13194 
13195   // If we are casting an integer type to a floating point type without
13196   // initialization-list syntax, we might lose accuracy if the floating
13197   // point type has a narrower significand than the integer type.
13198   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13199       TargetBT->isFloatingType() && !IsListInit) {
13200     // Determine the number of precision bits in the source integer type.
13201     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
13202                                         /*Approximate*/ true);
13203     unsigned int SourcePrecision = SourceRange.Width;
13204 
13205     // Determine the number of precision bits in the
13206     // target floating point type.
13207     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13208         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13209 
13210     if (SourcePrecision > 0 && TargetPrecision > 0 &&
13211         SourcePrecision > TargetPrecision) {
13212 
13213       if (Optional<llvm::APSInt> SourceInt =
13214               E->getIntegerConstantExpr(S.Context)) {
13215         // If the source integer is a constant, convert it to the target
13216         // floating point type. Issue a warning if the value changes
13217         // during the whole conversion.
13218         llvm::APFloat TargetFloatValue(
13219             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13220         llvm::APFloat::opStatus ConversionStatus =
13221             TargetFloatValue.convertFromAPInt(
13222                 *SourceInt, SourceBT->isSignedInteger(),
13223                 llvm::APFloat::rmNearestTiesToEven);
13224 
13225         if (ConversionStatus != llvm::APFloat::opOK) {
13226           SmallString<32> PrettySourceValue;
13227           SourceInt->toString(PrettySourceValue, 10);
13228           SmallString<32> PrettyTargetValue;
13229           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13230 
13231           S.DiagRuntimeBehavior(
13232               E->getExprLoc(), E,
13233               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
13234                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
13235                   << E->getSourceRange() << clang::SourceRange(CC));
13236         }
13237       } else {
13238         // Otherwise, the implicit conversion may lose precision.
13239         DiagnoseImpCast(S, E, T, CC,
13240                         diag::warn_impcast_integer_float_precision);
13241       }
13242     }
13243   }
13244 
13245   DiagnoseNullConversion(S, E, T, CC);
13246 
13247   S.DiscardMisalignedMemberAddress(Target, E);
13248 
13249   if (Target->isBooleanType())
13250     DiagnoseIntInBoolContext(S, E);
13251 
13252   if (!Source->isIntegerType() || !Target->isIntegerType())
13253     return;
13254 
13255   // TODO: remove this early return once the false positives for constant->bool
13256   // in templates, macros, etc, are reduced or removed.
13257   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13258     return;
13259 
13260   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
13261       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13262     return adornObjCBoolConversionDiagWithTernaryFixit(
13263         S, E,
13264         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13265             << E->getType());
13266   }
13267 
13268   IntRange SourceTypeRange =
13269       IntRange::forTargetOfCanonicalType(S.Context, Source);
13270   IntRange LikelySourceRange =
13271       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
13272   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
13273 
13274   if (LikelySourceRange.Width > TargetRange.Width) {
13275     // If the source is a constant, use a default-on diagnostic.
13276     // TODO: this should happen for bitfield stores, too.
13277     Expr::EvalResult Result;
13278     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
13279                          S.isConstantEvaluated())) {
13280       llvm::APSInt Value(32);
13281       Value = Result.Val.getInt();
13282 
13283       if (S.SourceMgr.isInSystemMacro(CC))
13284         return;
13285 
13286       std::string PrettySourceValue = toString(Value, 10);
13287       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13288 
13289       S.DiagRuntimeBehavior(
13290           E->getExprLoc(), E,
13291           S.PDiag(diag::warn_impcast_integer_precision_constant)
13292               << PrettySourceValue << PrettyTargetValue << E->getType() << T
13293               << E->getSourceRange() << SourceRange(CC));
13294       return;
13295     }
13296 
13297     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13298     if (S.SourceMgr.isInSystemMacro(CC))
13299       return;
13300 
13301     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
13302       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
13303                              /* pruneControlFlow */ true);
13304     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
13305   }
13306 
13307   if (TargetRange.Width > SourceTypeRange.Width) {
13308     if (auto *UO = dyn_cast<UnaryOperator>(E))
13309       if (UO->getOpcode() == UO_Minus)
13310         if (Source->isUnsignedIntegerType()) {
13311           if (Target->isUnsignedIntegerType())
13312             return DiagnoseImpCast(S, E, T, CC,
13313                                    diag::warn_impcast_high_order_zero_bits);
13314           if (Target->isSignedIntegerType())
13315             return DiagnoseImpCast(S, E, T, CC,
13316                                    diag::warn_impcast_nonnegative_result);
13317         }
13318   }
13319 
13320   if (TargetRange.Width == LikelySourceRange.Width &&
13321       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13322       Source->isSignedIntegerType()) {
13323     // Warn when doing a signed to signed conversion, warn if the positive
13324     // source value is exactly the width of the target type, which will
13325     // cause a negative value to be stored.
13326 
13327     Expr::EvalResult Result;
13328     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
13329         !S.SourceMgr.isInSystemMacro(CC)) {
13330       llvm::APSInt Value = Result.Val.getInt();
13331       if (isSameWidthConstantConversion(S, E, T, CC)) {
13332         std::string PrettySourceValue = toString(Value, 10);
13333         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13334 
13335         S.DiagRuntimeBehavior(
13336             E->getExprLoc(), E,
13337             S.PDiag(diag::warn_impcast_integer_precision_constant)
13338                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13339                 << E->getSourceRange() << SourceRange(CC));
13340         return;
13341       }
13342     }
13343 
13344     // Fall through for non-constants to give a sign conversion warning.
13345   }
13346 
13347   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13348       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13349        LikelySourceRange.Width == TargetRange.Width)) {
13350     if (S.SourceMgr.isInSystemMacro(CC))
13351       return;
13352 
13353     unsigned DiagID = diag::warn_impcast_integer_sign;
13354 
13355     // Traditionally, gcc has warned about this under -Wsign-compare.
13356     // We also want to warn about it in -Wconversion.
13357     // So if -Wconversion is off, use a completely identical diagnostic
13358     // in the sign-compare group.
13359     // The conditional-checking code will
13360     if (ICContext) {
13361       DiagID = diag::warn_impcast_integer_sign_conditional;
13362       *ICContext = true;
13363     }
13364 
13365     return DiagnoseImpCast(S, E, T, CC, DiagID);
13366   }
13367 
13368   // Diagnose conversions between different enumeration types.
13369   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13370   // type, to give us better diagnostics.
13371   QualType SourceType = E->getType();
13372   if (!S.getLangOpts().CPlusPlus) {
13373     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13374       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13375         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13376         SourceType = S.Context.getTypeDeclType(Enum);
13377         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13378       }
13379   }
13380 
13381   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13382     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13383       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13384           TargetEnum->getDecl()->hasNameForLinkage() &&
13385           SourceEnum != TargetEnum) {
13386         if (S.SourceMgr.isInSystemMacro(CC))
13387           return;
13388 
13389         return DiagnoseImpCast(S, E, SourceType, T, CC,
13390                                diag::warn_impcast_different_enum_types);
13391       }
13392 }
13393 
13394 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13395                                      SourceLocation CC, QualType T);
13396 
13397 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13398                                     SourceLocation CC, bool &ICContext) {
13399   E = E->IgnoreParenImpCasts();
13400 
13401   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13402     return CheckConditionalOperator(S, CO, CC, T);
13403 
13404   AnalyzeImplicitConversions(S, E, CC);
13405   if (E->getType() != T)
13406     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13407 }
13408 
13409 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13410                                      SourceLocation CC, QualType T) {
13411   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13412 
13413   Expr *TrueExpr = E->getTrueExpr();
13414   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13415     TrueExpr = BCO->getCommon();
13416 
13417   bool Suspicious = false;
13418   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13419   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13420 
13421   if (T->isBooleanType())
13422     DiagnoseIntInBoolContext(S, E);
13423 
13424   // If -Wconversion would have warned about either of the candidates
13425   // for a signedness conversion to the context type...
13426   if (!Suspicious) return;
13427 
13428   // ...but it's currently ignored...
13429   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13430     return;
13431 
13432   // ...then check whether it would have warned about either of the
13433   // candidates for a signedness conversion to the condition type.
13434   if (E->getType() == T) return;
13435 
13436   Suspicious = false;
13437   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13438                           E->getType(), CC, &Suspicious);
13439   if (!Suspicious)
13440     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13441                             E->getType(), CC, &Suspicious);
13442 }
13443 
13444 /// Check conversion of given expression to boolean.
13445 /// Input argument E is a logical expression.
13446 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13447   if (S.getLangOpts().Bool)
13448     return;
13449   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13450     return;
13451   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13452 }
13453 
13454 namespace {
13455 struct AnalyzeImplicitConversionsWorkItem {
13456   Expr *E;
13457   SourceLocation CC;
13458   bool IsListInit;
13459 };
13460 }
13461 
13462 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13463 /// that should be visited are added to WorkList.
13464 static void AnalyzeImplicitConversions(
13465     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13466     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13467   Expr *OrigE = Item.E;
13468   SourceLocation CC = Item.CC;
13469 
13470   QualType T = OrigE->getType();
13471   Expr *E = OrigE->IgnoreParenImpCasts();
13472 
13473   // Propagate whether we are in a C++ list initialization expression.
13474   // If so, we do not issue warnings for implicit int-float conversion
13475   // precision loss, because C++11 narrowing already handles it.
13476   bool IsListInit = Item.IsListInit ||
13477                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13478 
13479   if (E->isTypeDependent() || E->isValueDependent())
13480     return;
13481 
13482   Expr *SourceExpr = E;
13483   // Examine, but don't traverse into the source expression of an
13484   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13485   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13486   // evaluate it in the context of checking the specific conversion to T though.
13487   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13488     if (auto *Src = OVE->getSourceExpr())
13489       SourceExpr = Src;
13490 
13491   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13492     if (UO->getOpcode() == UO_Not &&
13493         UO->getSubExpr()->isKnownToHaveBooleanValue())
13494       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13495           << OrigE->getSourceRange() << T->isBooleanType()
13496           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13497 
13498   if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
13499     if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13500         BO->getLHS()->isKnownToHaveBooleanValue() &&
13501         BO->getRHS()->isKnownToHaveBooleanValue() &&
13502         BO->getLHS()->HasSideEffects(S.Context) &&
13503         BO->getRHS()->HasSideEffects(S.Context)) {
13504       S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13505           << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange()
13506           << FixItHint::CreateReplacement(
13507                  BO->getOperatorLoc(),
13508                  (BO->getOpcode() == BO_And ? "&&" : "||"));
13509       S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13510     }
13511 
13512   // For conditional operators, we analyze the arguments as if they
13513   // were being fed directly into the output.
13514   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13515     CheckConditionalOperator(S, CO, CC, T);
13516     return;
13517   }
13518 
13519   // Check implicit argument conversions for function calls.
13520   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13521     CheckImplicitArgumentConversions(S, Call, CC);
13522 
13523   // Go ahead and check any implicit conversions we might have skipped.
13524   // The non-canonical typecheck is just an optimization;
13525   // CheckImplicitConversion will filter out dead implicit conversions.
13526   if (SourceExpr->getType() != T)
13527     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13528 
13529   // Now continue drilling into this expression.
13530 
13531   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13532     // The bound subexpressions in a PseudoObjectExpr are not reachable
13533     // as transitive children.
13534     // FIXME: Use a more uniform representation for this.
13535     for (auto *SE : POE->semantics())
13536       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13537         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13538   }
13539 
13540   // Skip past explicit casts.
13541   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13542     E = CE->getSubExpr()->IgnoreParenImpCasts();
13543     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13544       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13545     WorkList.push_back({E, CC, IsListInit});
13546     return;
13547   }
13548 
13549   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13550     // Do a somewhat different check with comparison operators.
13551     if (BO->isComparisonOp())
13552       return AnalyzeComparison(S, BO);
13553 
13554     // And with simple assignments.
13555     if (BO->getOpcode() == BO_Assign)
13556       return AnalyzeAssignment(S, BO);
13557     // And with compound assignments.
13558     if (BO->isAssignmentOp())
13559       return AnalyzeCompoundAssignment(S, BO);
13560   }
13561 
13562   // These break the otherwise-useful invariant below.  Fortunately,
13563   // we don't really need to recurse into them, because any internal
13564   // expressions should have been analyzed already when they were
13565   // built into statements.
13566   if (isa<StmtExpr>(E)) return;
13567 
13568   // Don't descend into unevaluated contexts.
13569   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13570 
13571   // Now just recurse over the expression's children.
13572   CC = E->getExprLoc();
13573   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13574   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13575   for (Stmt *SubStmt : E->children()) {
13576     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13577     if (!ChildExpr)
13578       continue;
13579 
13580     if (IsLogicalAndOperator &&
13581         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13582       // Ignore checking string literals that are in logical and operators.
13583       // This is a common pattern for asserts.
13584       continue;
13585     WorkList.push_back({ChildExpr, CC, IsListInit});
13586   }
13587 
13588   if (BO && BO->isLogicalOp()) {
13589     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13590     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13591       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13592 
13593     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13594     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13595       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13596   }
13597 
13598   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13599     if (U->getOpcode() == UO_LNot) {
13600       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13601     } else if (U->getOpcode() != UO_AddrOf) {
13602       if (U->getSubExpr()->getType()->isAtomicType())
13603         S.Diag(U->getSubExpr()->getBeginLoc(),
13604                diag::warn_atomic_implicit_seq_cst);
13605     }
13606   }
13607 }
13608 
13609 /// AnalyzeImplicitConversions - Find and report any interesting
13610 /// implicit conversions in the given expression.  There are a couple
13611 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13612 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13613                                        bool IsListInit/*= false*/) {
13614   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13615   WorkList.push_back({OrigE, CC, IsListInit});
13616   while (!WorkList.empty())
13617     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13618 }
13619 
13620 /// Diagnose integer type and any valid implicit conversion to it.
13621 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13622   // Taking into account implicit conversions,
13623   // allow any integer.
13624   if (!E->getType()->isIntegerType()) {
13625     S.Diag(E->getBeginLoc(),
13626            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13627     return true;
13628   }
13629   // Potentially emit standard warnings for implicit conversions if enabled
13630   // using -Wconversion.
13631   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13632   return false;
13633 }
13634 
13635 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13636 // Returns true when emitting a warning about taking the address of a reference.
13637 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13638                               const PartialDiagnostic &PD) {
13639   E = E->IgnoreParenImpCasts();
13640 
13641   const FunctionDecl *FD = nullptr;
13642 
13643   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13644     if (!DRE->getDecl()->getType()->isReferenceType())
13645       return false;
13646   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13647     if (!M->getMemberDecl()->getType()->isReferenceType())
13648       return false;
13649   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13650     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13651       return false;
13652     FD = Call->getDirectCallee();
13653   } else {
13654     return false;
13655   }
13656 
13657   SemaRef.Diag(E->getExprLoc(), PD);
13658 
13659   // If possible, point to location of function.
13660   if (FD) {
13661     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13662   }
13663 
13664   return true;
13665 }
13666 
13667 // Returns true if the SourceLocation is expanded from any macro body.
13668 // Returns false if the SourceLocation is invalid, is from not in a macro
13669 // expansion, or is from expanded from a top-level macro argument.
13670 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13671   if (Loc.isInvalid())
13672     return false;
13673 
13674   while (Loc.isMacroID()) {
13675     if (SM.isMacroBodyExpansion(Loc))
13676       return true;
13677     Loc = SM.getImmediateMacroCallerLoc(Loc);
13678   }
13679 
13680   return false;
13681 }
13682 
13683 /// Diagnose pointers that are always non-null.
13684 /// \param E the expression containing the pointer
13685 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13686 /// compared to a null pointer
13687 /// \param IsEqual True when the comparison is equal to a null pointer
13688 /// \param Range Extra SourceRange to highlight in the diagnostic
13689 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13690                                         Expr::NullPointerConstantKind NullKind,
13691                                         bool IsEqual, SourceRange Range) {
13692   if (!E)
13693     return;
13694 
13695   // Don't warn inside macros.
13696   if (E->getExprLoc().isMacroID()) {
13697     const SourceManager &SM = getSourceManager();
13698     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13699         IsInAnyMacroBody(SM, Range.getBegin()))
13700       return;
13701   }
13702   E = E->IgnoreImpCasts();
13703 
13704   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13705 
13706   if (isa<CXXThisExpr>(E)) {
13707     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13708                                 : diag::warn_this_bool_conversion;
13709     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13710     return;
13711   }
13712 
13713   bool IsAddressOf = false;
13714 
13715   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13716     if (UO->getOpcode() != UO_AddrOf)
13717       return;
13718     IsAddressOf = true;
13719     E = UO->getSubExpr();
13720   }
13721 
13722   if (IsAddressOf) {
13723     unsigned DiagID = IsCompare
13724                           ? diag::warn_address_of_reference_null_compare
13725                           : diag::warn_address_of_reference_bool_conversion;
13726     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13727                                          << IsEqual;
13728     if (CheckForReference(*this, E, PD)) {
13729       return;
13730     }
13731   }
13732 
13733   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13734     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13735     std::string Str;
13736     llvm::raw_string_ostream S(Str);
13737     E->printPretty(S, nullptr, getPrintingPolicy());
13738     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13739                                 : diag::warn_cast_nonnull_to_bool;
13740     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13741       << E->getSourceRange() << Range << IsEqual;
13742     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13743   };
13744 
13745   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13746   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13747     if (auto *Callee = Call->getDirectCallee()) {
13748       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13749         ComplainAboutNonnullParamOrCall(A);
13750         return;
13751       }
13752     }
13753   }
13754 
13755   // Expect to find a single Decl.  Skip anything more complicated.
13756   ValueDecl *D = nullptr;
13757   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13758     D = R->getDecl();
13759   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13760     D = M->getMemberDecl();
13761   }
13762 
13763   // Weak Decls can be null.
13764   if (!D || D->isWeak())
13765     return;
13766 
13767   // Check for parameter decl with nonnull attribute
13768   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13769     if (getCurFunction() &&
13770         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13771       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13772         ComplainAboutNonnullParamOrCall(A);
13773         return;
13774       }
13775 
13776       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13777         // Skip function template not specialized yet.
13778         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13779           return;
13780         auto ParamIter = llvm::find(FD->parameters(), PV);
13781         assert(ParamIter != FD->param_end());
13782         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13783 
13784         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13785           if (!NonNull->args_size()) {
13786               ComplainAboutNonnullParamOrCall(NonNull);
13787               return;
13788           }
13789 
13790           for (const ParamIdx &ArgNo : NonNull->args()) {
13791             if (ArgNo.getASTIndex() == ParamNo) {
13792               ComplainAboutNonnullParamOrCall(NonNull);
13793               return;
13794             }
13795           }
13796         }
13797       }
13798     }
13799   }
13800 
13801   QualType T = D->getType();
13802   const bool IsArray = T->isArrayType();
13803   const bool IsFunction = T->isFunctionType();
13804 
13805   // Address of function is used to silence the function warning.
13806   if (IsAddressOf && IsFunction) {
13807     return;
13808   }
13809 
13810   // Found nothing.
13811   if (!IsAddressOf && !IsFunction && !IsArray)
13812     return;
13813 
13814   // Pretty print the expression for the diagnostic.
13815   std::string Str;
13816   llvm::raw_string_ostream S(Str);
13817   E->printPretty(S, nullptr, getPrintingPolicy());
13818 
13819   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13820                               : diag::warn_impcast_pointer_to_bool;
13821   enum {
13822     AddressOf,
13823     FunctionPointer,
13824     ArrayPointer
13825   } DiagType;
13826   if (IsAddressOf)
13827     DiagType = AddressOf;
13828   else if (IsFunction)
13829     DiagType = FunctionPointer;
13830   else if (IsArray)
13831     DiagType = ArrayPointer;
13832   else
13833     llvm_unreachable("Could not determine diagnostic.");
13834   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13835                                 << Range << IsEqual;
13836 
13837   if (!IsFunction)
13838     return;
13839 
13840   // Suggest '&' to silence the function warning.
13841   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13842       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13843 
13844   // Check to see if '()' fixit should be emitted.
13845   QualType ReturnType;
13846   UnresolvedSet<4> NonTemplateOverloads;
13847   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13848   if (ReturnType.isNull())
13849     return;
13850 
13851   if (IsCompare) {
13852     // There are two cases here.  If there is null constant, the only suggest
13853     // for a pointer return type.  If the null is 0, then suggest if the return
13854     // type is a pointer or an integer type.
13855     if (!ReturnType->isPointerType()) {
13856       if (NullKind == Expr::NPCK_ZeroExpression ||
13857           NullKind == Expr::NPCK_ZeroLiteral) {
13858         if (!ReturnType->isIntegerType())
13859           return;
13860       } else {
13861         return;
13862       }
13863     }
13864   } else { // !IsCompare
13865     // For function to bool, only suggest if the function pointer has bool
13866     // return type.
13867     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13868       return;
13869   }
13870   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13871       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13872 }
13873 
13874 /// Diagnoses "dangerous" implicit conversions within the given
13875 /// expression (which is a full expression).  Implements -Wconversion
13876 /// and -Wsign-compare.
13877 ///
13878 /// \param CC the "context" location of the implicit conversion, i.e.
13879 ///   the most location of the syntactic entity requiring the implicit
13880 ///   conversion
13881 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13882   // Don't diagnose in unevaluated contexts.
13883   if (isUnevaluatedContext())
13884     return;
13885 
13886   // Don't diagnose for value- or type-dependent expressions.
13887   if (E->isTypeDependent() || E->isValueDependent())
13888     return;
13889 
13890   // Check for array bounds violations in cases where the check isn't triggered
13891   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13892   // ArraySubscriptExpr is on the RHS of a variable initialization.
13893   CheckArrayAccess(E);
13894 
13895   // This is not the right CC for (e.g.) a variable initialization.
13896   AnalyzeImplicitConversions(*this, E, CC);
13897 }
13898 
13899 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13900 /// Input argument E is a logical expression.
13901 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13902   ::CheckBoolLikeConversion(*this, E, CC);
13903 }
13904 
13905 /// Diagnose when expression is an integer constant expression and its evaluation
13906 /// results in integer overflow
13907 void Sema::CheckForIntOverflow (Expr *E) {
13908   // Use a work list to deal with nested struct initializers.
13909   SmallVector<Expr *, 2> Exprs(1, E);
13910 
13911   do {
13912     Expr *OriginalE = Exprs.pop_back_val();
13913     Expr *E = OriginalE->IgnoreParenCasts();
13914 
13915     if (isa<BinaryOperator>(E)) {
13916       E->EvaluateForOverflow(Context);
13917       continue;
13918     }
13919 
13920     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13921       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13922     else if (isa<ObjCBoxedExpr>(OriginalE))
13923       E->EvaluateForOverflow(Context);
13924     else if (auto Call = dyn_cast<CallExpr>(E))
13925       Exprs.append(Call->arg_begin(), Call->arg_end());
13926     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13927       Exprs.append(Message->arg_begin(), Message->arg_end());
13928   } while (!Exprs.empty());
13929 }
13930 
13931 namespace {
13932 
13933 /// Visitor for expressions which looks for unsequenced operations on the
13934 /// same object.
13935 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13936   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13937 
13938   /// A tree of sequenced regions within an expression. Two regions are
13939   /// unsequenced if one is an ancestor or a descendent of the other. When we
13940   /// finish processing an expression with sequencing, such as a comma
13941   /// expression, we fold its tree nodes into its parent, since they are
13942   /// unsequenced with respect to nodes we will visit later.
13943   class SequenceTree {
13944     struct Value {
13945       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13946       unsigned Parent : 31;
13947       unsigned Merged : 1;
13948     };
13949     SmallVector<Value, 8> Values;
13950 
13951   public:
13952     /// A region within an expression which may be sequenced with respect
13953     /// to some other region.
13954     class Seq {
13955       friend class SequenceTree;
13956 
13957       unsigned Index;
13958 
13959       explicit Seq(unsigned N) : Index(N) {}
13960 
13961     public:
13962       Seq() : Index(0) {}
13963     };
13964 
13965     SequenceTree() { Values.push_back(Value(0)); }
13966     Seq root() const { return Seq(0); }
13967 
13968     /// Create a new sequence of operations, which is an unsequenced
13969     /// subset of \p Parent. This sequence of operations is sequenced with
13970     /// respect to other children of \p Parent.
13971     Seq allocate(Seq Parent) {
13972       Values.push_back(Value(Parent.Index));
13973       return Seq(Values.size() - 1);
13974     }
13975 
13976     /// Merge a sequence of operations into its parent.
13977     void merge(Seq S) {
13978       Values[S.Index].Merged = true;
13979     }
13980 
13981     /// Determine whether two operations are unsequenced. This operation
13982     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13983     /// should have been merged into its parent as appropriate.
13984     bool isUnsequenced(Seq Cur, Seq Old) {
13985       unsigned C = representative(Cur.Index);
13986       unsigned Target = representative(Old.Index);
13987       while (C >= Target) {
13988         if (C == Target)
13989           return true;
13990         C = Values[C].Parent;
13991       }
13992       return false;
13993     }
13994 
13995   private:
13996     /// Pick a representative for a sequence.
13997     unsigned representative(unsigned K) {
13998       if (Values[K].Merged)
13999         // Perform path compression as we go.
14000         return Values[K].Parent = representative(Values[K].Parent);
14001       return K;
14002     }
14003   };
14004 
14005   /// An object for which we can track unsequenced uses.
14006   using Object = const NamedDecl *;
14007 
14008   /// Different flavors of object usage which we track. We only track the
14009   /// least-sequenced usage of each kind.
14010   enum UsageKind {
14011     /// A read of an object. Multiple unsequenced reads are OK.
14012     UK_Use,
14013 
14014     /// A modification of an object which is sequenced before the value
14015     /// computation of the expression, such as ++n in C++.
14016     UK_ModAsValue,
14017 
14018     /// A modification of an object which is not sequenced before the value
14019     /// computation of the expression, such as n++.
14020     UK_ModAsSideEffect,
14021 
14022     UK_Count = UK_ModAsSideEffect + 1
14023   };
14024 
14025   /// Bundle together a sequencing region and the expression corresponding
14026   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14027   struct Usage {
14028     const Expr *UsageExpr;
14029     SequenceTree::Seq Seq;
14030 
14031     Usage() : UsageExpr(nullptr) {}
14032   };
14033 
14034   struct UsageInfo {
14035     Usage Uses[UK_Count];
14036 
14037     /// Have we issued a diagnostic for this object already?
14038     bool Diagnosed;
14039 
14040     UsageInfo() : Diagnosed(false) {}
14041   };
14042   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14043 
14044   Sema &SemaRef;
14045 
14046   /// Sequenced regions within the expression.
14047   SequenceTree Tree;
14048 
14049   /// Declaration modifications and references which we have seen.
14050   UsageInfoMap UsageMap;
14051 
14052   /// The region we are currently within.
14053   SequenceTree::Seq Region;
14054 
14055   /// Filled in with declarations which were modified as a side-effect
14056   /// (that is, post-increment operations).
14057   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14058 
14059   /// Expressions to check later. We defer checking these to reduce
14060   /// stack usage.
14061   SmallVectorImpl<const Expr *> &WorkList;
14062 
14063   /// RAII object wrapping the visitation of a sequenced subexpression of an
14064   /// expression. At the end of this process, the side-effects of the evaluation
14065   /// become sequenced with respect to the value computation of the result, so
14066   /// we downgrade any UK_ModAsSideEffect within the evaluation to
14067   /// UK_ModAsValue.
14068   struct SequencedSubexpression {
14069     SequencedSubexpression(SequenceChecker &Self)
14070       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14071       Self.ModAsSideEffect = &ModAsSideEffect;
14072     }
14073 
14074     ~SequencedSubexpression() {
14075       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14076         // Add a new usage with usage kind UK_ModAsValue, and then restore
14077         // the previous usage with UK_ModAsSideEffect (thus clearing it if
14078         // the previous one was empty).
14079         UsageInfo &UI = Self.UsageMap[M.first];
14080         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14081         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14082         SideEffectUsage = M.second;
14083       }
14084       Self.ModAsSideEffect = OldModAsSideEffect;
14085     }
14086 
14087     SequenceChecker &Self;
14088     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14089     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14090   };
14091 
14092   /// RAII object wrapping the visitation of a subexpression which we might
14093   /// choose to evaluate as a constant. If any subexpression is evaluated and
14094   /// found to be non-constant, this allows us to suppress the evaluation of
14095   /// the outer expression.
14096   class EvaluationTracker {
14097   public:
14098     EvaluationTracker(SequenceChecker &Self)
14099         : Self(Self), Prev(Self.EvalTracker) {
14100       Self.EvalTracker = this;
14101     }
14102 
14103     ~EvaluationTracker() {
14104       Self.EvalTracker = Prev;
14105       if (Prev)
14106         Prev->EvalOK &= EvalOK;
14107     }
14108 
14109     bool evaluate(const Expr *E, bool &Result) {
14110       if (!EvalOK || E->isValueDependent())
14111         return false;
14112       EvalOK = E->EvaluateAsBooleanCondition(
14113           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
14114       return EvalOK;
14115     }
14116 
14117   private:
14118     SequenceChecker &Self;
14119     EvaluationTracker *Prev;
14120     bool EvalOK = true;
14121   } *EvalTracker = nullptr;
14122 
14123   /// Find the object which is produced by the specified expression,
14124   /// if any.
14125   Object getObject(const Expr *E, bool Mod) const {
14126     E = E->IgnoreParenCasts();
14127     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14128       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14129         return getObject(UO->getSubExpr(), Mod);
14130     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14131       if (BO->getOpcode() == BO_Comma)
14132         return getObject(BO->getRHS(), Mod);
14133       if (Mod && BO->isAssignmentOp())
14134         return getObject(BO->getLHS(), Mod);
14135     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14136       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14137       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14138         return ME->getMemberDecl();
14139     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14140       // FIXME: If this is a reference, map through to its value.
14141       return DRE->getDecl();
14142     return nullptr;
14143   }
14144 
14145   /// Note that an object \p O was modified or used by an expression
14146   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14147   /// the object \p O as obtained via the \p UsageMap.
14148   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14149     // Get the old usage for the given object and usage kind.
14150     Usage &U = UI.Uses[UK];
14151     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14152       // If we have a modification as side effect and are in a sequenced
14153       // subexpression, save the old Usage so that we can restore it later
14154       // in SequencedSubexpression::~SequencedSubexpression.
14155       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14156         ModAsSideEffect->push_back(std::make_pair(O, U));
14157       // Then record the new usage with the current sequencing region.
14158       U.UsageExpr = UsageExpr;
14159       U.Seq = Region;
14160     }
14161   }
14162 
14163   /// Check whether a modification or use of an object \p O in an expression
14164   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14165   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14166   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14167   /// usage and false we are checking for a mod-use unsequenced usage.
14168   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14169                   UsageKind OtherKind, bool IsModMod) {
14170     if (UI.Diagnosed)
14171       return;
14172 
14173     const Usage &U = UI.Uses[OtherKind];
14174     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14175       return;
14176 
14177     const Expr *Mod = U.UsageExpr;
14178     const Expr *ModOrUse = UsageExpr;
14179     if (OtherKind == UK_Use)
14180       std::swap(Mod, ModOrUse);
14181 
14182     SemaRef.DiagRuntimeBehavior(
14183         Mod->getExprLoc(), {Mod, ModOrUse},
14184         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14185                                : diag::warn_unsequenced_mod_use)
14186             << O << SourceRange(ModOrUse->getExprLoc()));
14187     UI.Diagnosed = true;
14188   }
14189 
14190   // A note on note{Pre, Post}{Use, Mod}:
14191   //
14192   // (It helps to follow the algorithm with an expression such as
14193   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14194   //  operations before C++17 and both are well-defined in C++17).
14195   //
14196   // When visiting a node which uses/modify an object we first call notePreUse
14197   // or notePreMod before visiting its sub-expression(s). At this point the
14198   // children of the current node have not yet been visited and so the eventual
14199   // uses/modifications resulting from the children of the current node have not
14200   // been recorded yet.
14201   //
14202   // We then visit the children of the current node. After that notePostUse or
14203   // notePostMod is called. These will 1) detect an unsequenced modification
14204   // as side effect (as in "k++ + k") and 2) add a new usage with the
14205   // appropriate usage kind.
14206   //
14207   // We also have to be careful that some operation sequences modification as
14208   // side effect as well (for example: || or ,). To account for this we wrap
14209   // the visitation of such a sub-expression (for example: the LHS of || or ,)
14210   // with SequencedSubexpression. SequencedSubexpression is an RAII object
14211   // which record usages which are modifications as side effect, and then
14212   // downgrade them (or more accurately restore the previous usage which was a
14213   // modification as side effect) when exiting the scope of the sequenced
14214   // subexpression.
14215 
14216   void notePreUse(Object O, const Expr *UseExpr) {
14217     UsageInfo &UI = UsageMap[O];
14218     // Uses conflict with other modifications.
14219     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14220   }
14221 
14222   void notePostUse(Object O, const Expr *UseExpr) {
14223     UsageInfo &UI = UsageMap[O];
14224     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14225                /*IsModMod=*/false);
14226     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14227   }
14228 
14229   void notePreMod(Object O, const Expr *ModExpr) {
14230     UsageInfo &UI = UsageMap[O];
14231     // Modifications conflict with other modifications and with uses.
14232     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14233     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14234   }
14235 
14236   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14237     UsageInfo &UI = UsageMap[O];
14238     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14239                /*IsModMod=*/true);
14240     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14241   }
14242 
14243 public:
14244   SequenceChecker(Sema &S, const Expr *E,
14245                   SmallVectorImpl<const Expr *> &WorkList)
14246       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14247     Visit(E);
14248     // Silence a -Wunused-private-field since WorkList is now unused.
14249     // TODO: Evaluate if it can be used, and if not remove it.
14250     (void)this->WorkList;
14251   }
14252 
14253   void VisitStmt(const Stmt *S) {
14254     // Skip all statements which aren't expressions for now.
14255   }
14256 
14257   void VisitExpr(const Expr *E) {
14258     // By default, just recurse to evaluated subexpressions.
14259     Base::VisitStmt(E);
14260   }
14261 
14262   void VisitCastExpr(const CastExpr *E) {
14263     Object O = Object();
14264     if (E->getCastKind() == CK_LValueToRValue)
14265       O = getObject(E->getSubExpr(), false);
14266 
14267     if (O)
14268       notePreUse(O, E);
14269     VisitExpr(E);
14270     if (O)
14271       notePostUse(O, E);
14272   }
14273 
14274   void VisitSequencedExpressions(const Expr *SequencedBefore,
14275                                  const Expr *SequencedAfter) {
14276     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14277     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14278     SequenceTree::Seq OldRegion = Region;
14279 
14280     {
14281       SequencedSubexpression SeqBefore(*this);
14282       Region = BeforeRegion;
14283       Visit(SequencedBefore);
14284     }
14285 
14286     Region = AfterRegion;
14287     Visit(SequencedAfter);
14288 
14289     Region = OldRegion;
14290 
14291     Tree.merge(BeforeRegion);
14292     Tree.merge(AfterRegion);
14293   }
14294 
14295   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14296     // C++17 [expr.sub]p1:
14297     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14298     //   expression E1 is sequenced before the expression E2.
14299     if (SemaRef.getLangOpts().CPlusPlus17)
14300       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14301     else {
14302       Visit(ASE->getLHS());
14303       Visit(ASE->getRHS());
14304     }
14305   }
14306 
14307   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14308   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14309   void VisitBinPtrMem(const BinaryOperator *BO) {
14310     // C++17 [expr.mptr.oper]p4:
14311     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14312     //  the expression E1 is sequenced before the expression E2.
14313     if (SemaRef.getLangOpts().CPlusPlus17)
14314       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14315     else {
14316       Visit(BO->getLHS());
14317       Visit(BO->getRHS());
14318     }
14319   }
14320 
14321   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14322   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14323   void VisitBinShlShr(const BinaryOperator *BO) {
14324     // C++17 [expr.shift]p4:
14325     //  The expression E1 is sequenced before the expression E2.
14326     if (SemaRef.getLangOpts().CPlusPlus17)
14327       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14328     else {
14329       Visit(BO->getLHS());
14330       Visit(BO->getRHS());
14331     }
14332   }
14333 
14334   void VisitBinComma(const BinaryOperator *BO) {
14335     // C++11 [expr.comma]p1:
14336     //   Every value computation and side effect associated with the left
14337     //   expression is sequenced before every value computation and side
14338     //   effect associated with the right expression.
14339     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14340   }
14341 
14342   void VisitBinAssign(const BinaryOperator *BO) {
14343     SequenceTree::Seq RHSRegion;
14344     SequenceTree::Seq LHSRegion;
14345     if (SemaRef.getLangOpts().CPlusPlus17) {
14346       RHSRegion = Tree.allocate(Region);
14347       LHSRegion = Tree.allocate(Region);
14348     } else {
14349       RHSRegion = Region;
14350       LHSRegion = Region;
14351     }
14352     SequenceTree::Seq OldRegion = Region;
14353 
14354     // C++11 [expr.ass]p1:
14355     //  [...] the assignment is sequenced after the value computation
14356     //  of the right and left operands, [...]
14357     //
14358     // so check it before inspecting the operands and update the
14359     // map afterwards.
14360     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14361     if (O)
14362       notePreMod(O, BO);
14363 
14364     if (SemaRef.getLangOpts().CPlusPlus17) {
14365       // C++17 [expr.ass]p1:
14366       //  [...] The right operand is sequenced before the left operand. [...]
14367       {
14368         SequencedSubexpression SeqBefore(*this);
14369         Region = RHSRegion;
14370         Visit(BO->getRHS());
14371       }
14372 
14373       Region = LHSRegion;
14374       Visit(BO->getLHS());
14375 
14376       if (O && isa<CompoundAssignOperator>(BO))
14377         notePostUse(O, BO);
14378 
14379     } else {
14380       // C++11 does not specify any sequencing between the LHS and RHS.
14381       Region = LHSRegion;
14382       Visit(BO->getLHS());
14383 
14384       if (O && isa<CompoundAssignOperator>(BO))
14385         notePostUse(O, BO);
14386 
14387       Region = RHSRegion;
14388       Visit(BO->getRHS());
14389     }
14390 
14391     // C++11 [expr.ass]p1:
14392     //  the assignment is sequenced [...] before the value computation of the
14393     //  assignment expression.
14394     // C11 6.5.16/3 has no such rule.
14395     Region = OldRegion;
14396     if (O)
14397       notePostMod(O, BO,
14398                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14399                                                   : UK_ModAsSideEffect);
14400     if (SemaRef.getLangOpts().CPlusPlus17) {
14401       Tree.merge(RHSRegion);
14402       Tree.merge(LHSRegion);
14403     }
14404   }
14405 
14406   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14407     VisitBinAssign(CAO);
14408   }
14409 
14410   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14411   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14412   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14413     Object O = getObject(UO->getSubExpr(), true);
14414     if (!O)
14415       return VisitExpr(UO);
14416 
14417     notePreMod(O, UO);
14418     Visit(UO->getSubExpr());
14419     // C++11 [expr.pre.incr]p1:
14420     //   the expression ++x is equivalent to x+=1
14421     notePostMod(O, UO,
14422                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14423                                                 : UK_ModAsSideEffect);
14424   }
14425 
14426   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14427   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14428   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14429     Object O = getObject(UO->getSubExpr(), true);
14430     if (!O)
14431       return VisitExpr(UO);
14432 
14433     notePreMod(O, UO);
14434     Visit(UO->getSubExpr());
14435     notePostMod(O, UO, UK_ModAsSideEffect);
14436   }
14437 
14438   void VisitBinLOr(const BinaryOperator *BO) {
14439     // C++11 [expr.log.or]p2:
14440     //  If the second expression is evaluated, every value computation and
14441     //  side effect associated with the first expression is sequenced before
14442     //  every value computation and side effect associated with the
14443     //  second expression.
14444     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14445     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14446     SequenceTree::Seq OldRegion = Region;
14447 
14448     EvaluationTracker Eval(*this);
14449     {
14450       SequencedSubexpression Sequenced(*this);
14451       Region = LHSRegion;
14452       Visit(BO->getLHS());
14453     }
14454 
14455     // C++11 [expr.log.or]p1:
14456     //  [...] the second operand is not evaluated if the first operand
14457     //  evaluates to true.
14458     bool EvalResult = false;
14459     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14460     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14461     if (ShouldVisitRHS) {
14462       Region = RHSRegion;
14463       Visit(BO->getRHS());
14464     }
14465 
14466     Region = OldRegion;
14467     Tree.merge(LHSRegion);
14468     Tree.merge(RHSRegion);
14469   }
14470 
14471   void VisitBinLAnd(const BinaryOperator *BO) {
14472     // C++11 [expr.log.and]p2:
14473     //  If the second expression is evaluated, every value computation and
14474     //  side effect associated with the first expression is sequenced before
14475     //  every value computation and side effect associated with the
14476     //  second expression.
14477     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14478     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14479     SequenceTree::Seq OldRegion = Region;
14480 
14481     EvaluationTracker Eval(*this);
14482     {
14483       SequencedSubexpression Sequenced(*this);
14484       Region = LHSRegion;
14485       Visit(BO->getLHS());
14486     }
14487 
14488     // C++11 [expr.log.and]p1:
14489     //  [...] the second operand is not evaluated if the first operand is false.
14490     bool EvalResult = false;
14491     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14492     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14493     if (ShouldVisitRHS) {
14494       Region = RHSRegion;
14495       Visit(BO->getRHS());
14496     }
14497 
14498     Region = OldRegion;
14499     Tree.merge(LHSRegion);
14500     Tree.merge(RHSRegion);
14501   }
14502 
14503   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14504     // C++11 [expr.cond]p1:
14505     //  [...] Every value computation and side effect associated with the first
14506     //  expression is sequenced before every value computation and side effect
14507     //  associated with the second or third expression.
14508     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14509 
14510     // No sequencing is specified between the true and false expression.
14511     // However since exactly one of both is going to be evaluated we can
14512     // consider them to be sequenced. This is needed to avoid warning on
14513     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14514     // both the true and false expressions because we can't evaluate x.
14515     // This will still allow us to detect an expression like (pre C++17)
14516     // "(x ? y += 1 : y += 2) = y".
14517     //
14518     // We don't wrap the visitation of the true and false expression with
14519     // SequencedSubexpression because we don't want to downgrade modifications
14520     // as side effect in the true and false expressions after the visition
14521     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14522     // not warn between the two "y++", but we should warn between the "y++"
14523     // and the "y".
14524     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14525     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14526     SequenceTree::Seq OldRegion = Region;
14527 
14528     EvaluationTracker Eval(*this);
14529     {
14530       SequencedSubexpression Sequenced(*this);
14531       Region = ConditionRegion;
14532       Visit(CO->getCond());
14533     }
14534 
14535     // C++11 [expr.cond]p1:
14536     // [...] The first expression is contextually converted to bool (Clause 4).
14537     // It is evaluated and if it is true, the result of the conditional
14538     // expression is the value of the second expression, otherwise that of the
14539     // third expression. Only one of the second and third expressions is
14540     // evaluated. [...]
14541     bool EvalResult = false;
14542     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14543     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14544     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14545     if (ShouldVisitTrueExpr) {
14546       Region = TrueRegion;
14547       Visit(CO->getTrueExpr());
14548     }
14549     if (ShouldVisitFalseExpr) {
14550       Region = FalseRegion;
14551       Visit(CO->getFalseExpr());
14552     }
14553 
14554     Region = OldRegion;
14555     Tree.merge(ConditionRegion);
14556     Tree.merge(TrueRegion);
14557     Tree.merge(FalseRegion);
14558   }
14559 
14560   void VisitCallExpr(const CallExpr *CE) {
14561     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14562 
14563     if (CE->isUnevaluatedBuiltinCall(Context))
14564       return;
14565 
14566     // C++11 [intro.execution]p15:
14567     //   When calling a function [...], every value computation and side effect
14568     //   associated with any argument expression, or with the postfix expression
14569     //   designating the called function, is sequenced before execution of every
14570     //   expression or statement in the body of the function [and thus before
14571     //   the value computation of its result].
14572     SequencedSubexpression Sequenced(*this);
14573     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14574       // C++17 [expr.call]p5
14575       //   The postfix-expression is sequenced before each expression in the
14576       //   expression-list and any default argument. [...]
14577       SequenceTree::Seq CalleeRegion;
14578       SequenceTree::Seq OtherRegion;
14579       if (SemaRef.getLangOpts().CPlusPlus17) {
14580         CalleeRegion = Tree.allocate(Region);
14581         OtherRegion = Tree.allocate(Region);
14582       } else {
14583         CalleeRegion = Region;
14584         OtherRegion = Region;
14585       }
14586       SequenceTree::Seq OldRegion = Region;
14587 
14588       // Visit the callee expression first.
14589       Region = CalleeRegion;
14590       if (SemaRef.getLangOpts().CPlusPlus17) {
14591         SequencedSubexpression Sequenced(*this);
14592         Visit(CE->getCallee());
14593       } else {
14594         Visit(CE->getCallee());
14595       }
14596 
14597       // Then visit the argument expressions.
14598       Region = OtherRegion;
14599       for (const Expr *Argument : CE->arguments())
14600         Visit(Argument);
14601 
14602       Region = OldRegion;
14603       if (SemaRef.getLangOpts().CPlusPlus17) {
14604         Tree.merge(CalleeRegion);
14605         Tree.merge(OtherRegion);
14606       }
14607     });
14608   }
14609 
14610   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14611     // C++17 [over.match.oper]p2:
14612     //   [...] the operator notation is first transformed to the equivalent
14613     //   function-call notation as summarized in Table 12 (where @ denotes one
14614     //   of the operators covered in the specified subclause). However, the
14615     //   operands are sequenced in the order prescribed for the built-in
14616     //   operator (Clause 8).
14617     //
14618     // From the above only overloaded binary operators and overloaded call
14619     // operators have sequencing rules in C++17 that we need to handle
14620     // separately.
14621     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14622         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14623       return VisitCallExpr(CXXOCE);
14624 
14625     enum {
14626       NoSequencing,
14627       LHSBeforeRHS,
14628       RHSBeforeLHS,
14629       LHSBeforeRest
14630     } SequencingKind;
14631     switch (CXXOCE->getOperator()) {
14632     case OO_Equal:
14633     case OO_PlusEqual:
14634     case OO_MinusEqual:
14635     case OO_StarEqual:
14636     case OO_SlashEqual:
14637     case OO_PercentEqual:
14638     case OO_CaretEqual:
14639     case OO_AmpEqual:
14640     case OO_PipeEqual:
14641     case OO_LessLessEqual:
14642     case OO_GreaterGreaterEqual:
14643       SequencingKind = RHSBeforeLHS;
14644       break;
14645 
14646     case OO_LessLess:
14647     case OO_GreaterGreater:
14648     case OO_AmpAmp:
14649     case OO_PipePipe:
14650     case OO_Comma:
14651     case OO_ArrowStar:
14652     case OO_Subscript:
14653       SequencingKind = LHSBeforeRHS;
14654       break;
14655 
14656     case OO_Call:
14657       SequencingKind = LHSBeforeRest;
14658       break;
14659 
14660     default:
14661       SequencingKind = NoSequencing;
14662       break;
14663     }
14664 
14665     if (SequencingKind == NoSequencing)
14666       return VisitCallExpr(CXXOCE);
14667 
14668     // This is a call, so all subexpressions are sequenced before the result.
14669     SequencedSubexpression Sequenced(*this);
14670 
14671     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14672       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14673              "Should only get there with C++17 and above!");
14674       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14675              "Should only get there with an overloaded binary operator"
14676              " or an overloaded call operator!");
14677 
14678       if (SequencingKind == LHSBeforeRest) {
14679         assert(CXXOCE->getOperator() == OO_Call &&
14680                "We should only have an overloaded call operator here!");
14681 
14682         // This is very similar to VisitCallExpr, except that we only have the
14683         // C++17 case. The postfix-expression is the first argument of the
14684         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14685         // are in the following arguments.
14686         //
14687         // Note that we intentionally do not visit the callee expression since
14688         // it is just a decayed reference to a function.
14689         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14690         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14691         SequenceTree::Seq OldRegion = Region;
14692 
14693         assert(CXXOCE->getNumArgs() >= 1 &&
14694                "An overloaded call operator must have at least one argument"
14695                " for the postfix-expression!");
14696         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14697         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14698                                           CXXOCE->getNumArgs() - 1);
14699 
14700         // Visit the postfix-expression first.
14701         {
14702           Region = PostfixExprRegion;
14703           SequencedSubexpression Sequenced(*this);
14704           Visit(PostfixExpr);
14705         }
14706 
14707         // Then visit the argument expressions.
14708         Region = ArgsRegion;
14709         for (const Expr *Arg : Args)
14710           Visit(Arg);
14711 
14712         Region = OldRegion;
14713         Tree.merge(PostfixExprRegion);
14714         Tree.merge(ArgsRegion);
14715       } else {
14716         assert(CXXOCE->getNumArgs() == 2 &&
14717                "Should only have two arguments here!");
14718         assert((SequencingKind == LHSBeforeRHS ||
14719                 SequencingKind == RHSBeforeLHS) &&
14720                "Unexpected sequencing kind!");
14721 
14722         // We do not visit the callee expression since it is just a decayed
14723         // reference to a function.
14724         const Expr *E1 = CXXOCE->getArg(0);
14725         const Expr *E2 = CXXOCE->getArg(1);
14726         if (SequencingKind == RHSBeforeLHS)
14727           std::swap(E1, E2);
14728 
14729         return VisitSequencedExpressions(E1, E2);
14730       }
14731     });
14732   }
14733 
14734   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14735     // This is a call, so all subexpressions are sequenced before the result.
14736     SequencedSubexpression Sequenced(*this);
14737 
14738     if (!CCE->isListInitialization())
14739       return VisitExpr(CCE);
14740 
14741     // In C++11, list initializations are sequenced.
14742     SmallVector<SequenceTree::Seq, 32> Elts;
14743     SequenceTree::Seq Parent = Region;
14744     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14745                                               E = CCE->arg_end();
14746          I != E; ++I) {
14747       Region = Tree.allocate(Parent);
14748       Elts.push_back(Region);
14749       Visit(*I);
14750     }
14751 
14752     // Forget that the initializers are sequenced.
14753     Region = Parent;
14754     for (unsigned I = 0; I < Elts.size(); ++I)
14755       Tree.merge(Elts[I]);
14756   }
14757 
14758   void VisitInitListExpr(const InitListExpr *ILE) {
14759     if (!SemaRef.getLangOpts().CPlusPlus11)
14760       return VisitExpr(ILE);
14761 
14762     // In C++11, list initializations are sequenced.
14763     SmallVector<SequenceTree::Seq, 32> Elts;
14764     SequenceTree::Seq Parent = Region;
14765     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14766       const Expr *E = ILE->getInit(I);
14767       if (!E)
14768         continue;
14769       Region = Tree.allocate(Parent);
14770       Elts.push_back(Region);
14771       Visit(E);
14772     }
14773 
14774     // Forget that the initializers are sequenced.
14775     Region = Parent;
14776     for (unsigned I = 0; I < Elts.size(); ++I)
14777       Tree.merge(Elts[I]);
14778   }
14779 };
14780 
14781 } // namespace
14782 
14783 void Sema::CheckUnsequencedOperations(const Expr *E) {
14784   SmallVector<const Expr *, 8> WorkList;
14785   WorkList.push_back(E);
14786   while (!WorkList.empty()) {
14787     const Expr *Item = WorkList.pop_back_val();
14788     SequenceChecker(*this, Item, WorkList);
14789   }
14790 }
14791 
14792 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14793                               bool IsConstexpr) {
14794   llvm::SaveAndRestore<bool> ConstantContext(
14795       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14796   CheckImplicitConversions(E, CheckLoc);
14797   if (!E->isInstantiationDependent())
14798     CheckUnsequencedOperations(E);
14799   if (!IsConstexpr && !E->isValueDependent())
14800     CheckForIntOverflow(E);
14801   DiagnoseMisalignedMembers();
14802 }
14803 
14804 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14805                                        FieldDecl *BitField,
14806                                        Expr *Init) {
14807   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14808 }
14809 
14810 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14811                                          SourceLocation Loc) {
14812   if (!PType->isVariablyModifiedType())
14813     return;
14814   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14815     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14816     return;
14817   }
14818   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14819     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14820     return;
14821   }
14822   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14823     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14824     return;
14825   }
14826 
14827   const ArrayType *AT = S.Context.getAsArrayType(PType);
14828   if (!AT)
14829     return;
14830 
14831   if (AT->getSizeModifier() != ArrayType::Star) {
14832     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14833     return;
14834   }
14835 
14836   S.Diag(Loc, diag::err_array_star_in_function_definition);
14837 }
14838 
14839 /// CheckParmsForFunctionDef - Check that the parameters of the given
14840 /// function are appropriate for the definition of a function. This
14841 /// takes care of any checks that cannot be performed on the
14842 /// declaration itself, e.g., that the types of each of the function
14843 /// parameters are complete.
14844 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14845                                     bool CheckParameterNames) {
14846   bool HasInvalidParm = false;
14847   for (ParmVarDecl *Param : Parameters) {
14848     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14849     // function declarator that is part of a function definition of
14850     // that function shall not have incomplete type.
14851     //
14852     // This is also C++ [dcl.fct]p6.
14853     if (!Param->isInvalidDecl() &&
14854         RequireCompleteType(Param->getLocation(), Param->getType(),
14855                             diag::err_typecheck_decl_incomplete_type)) {
14856       Param->setInvalidDecl();
14857       HasInvalidParm = true;
14858     }
14859 
14860     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14861     // declaration of each parameter shall include an identifier.
14862     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14863         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14864       // Diagnose this as an extension in C17 and earlier.
14865       if (!getLangOpts().C2x)
14866         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14867     }
14868 
14869     // C99 6.7.5.3p12:
14870     //   If the function declarator is not part of a definition of that
14871     //   function, parameters may have incomplete type and may use the [*]
14872     //   notation in their sequences of declarator specifiers to specify
14873     //   variable length array types.
14874     QualType PType = Param->getOriginalType();
14875     // FIXME: This diagnostic should point the '[*]' if source-location
14876     // information is added for it.
14877     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14878 
14879     // If the parameter is a c++ class type and it has to be destructed in the
14880     // callee function, declare the destructor so that it can be called by the
14881     // callee function. Do not perform any direct access check on the dtor here.
14882     if (!Param->isInvalidDecl()) {
14883       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14884         if (!ClassDecl->isInvalidDecl() &&
14885             !ClassDecl->hasIrrelevantDestructor() &&
14886             !ClassDecl->isDependentContext() &&
14887             ClassDecl->isParamDestroyedInCallee()) {
14888           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14889           MarkFunctionReferenced(Param->getLocation(), Destructor);
14890           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14891         }
14892       }
14893     }
14894 
14895     // Parameters with the pass_object_size attribute only need to be marked
14896     // constant at function definitions. Because we lack information about
14897     // whether we're on a declaration or definition when we're instantiating the
14898     // attribute, we need to check for constness here.
14899     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14900       if (!Param->getType().isConstQualified())
14901         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14902             << Attr->getSpelling() << 1;
14903 
14904     // Check for parameter names shadowing fields from the class.
14905     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14906       // The owning context for the parameter should be the function, but we
14907       // want to see if this function's declaration context is a record.
14908       DeclContext *DC = Param->getDeclContext();
14909       if (DC && DC->isFunctionOrMethod()) {
14910         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14911           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14912                                      RD, /*DeclIsField*/ false);
14913       }
14914     }
14915   }
14916 
14917   return HasInvalidParm;
14918 }
14919 
14920 Optional<std::pair<CharUnits, CharUnits>>
14921 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14922 
14923 /// Compute the alignment and offset of the base class object given the
14924 /// derived-to-base cast expression and the alignment and offset of the derived
14925 /// class object.
14926 static std::pair<CharUnits, CharUnits>
14927 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14928                                    CharUnits BaseAlignment, CharUnits Offset,
14929                                    ASTContext &Ctx) {
14930   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14931        ++PathI) {
14932     const CXXBaseSpecifier *Base = *PathI;
14933     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14934     if (Base->isVirtual()) {
14935       // The complete object may have a lower alignment than the non-virtual
14936       // alignment of the base, in which case the base may be misaligned. Choose
14937       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14938       // conservative lower bound of the complete object alignment.
14939       CharUnits NonVirtualAlignment =
14940           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14941       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14942       Offset = CharUnits::Zero();
14943     } else {
14944       const ASTRecordLayout &RL =
14945           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14946       Offset += RL.getBaseClassOffset(BaseDecl);
14947     }
14948     DerivedType = Base->getType();
14949   }
14950 
14951   return std::make_pair(BaseAlignment, Offset);
14952 }
14953 
14954 /// Compute the alignment and offset of a binary additive operator.
14955 static Optional<std::pair<CharUnits, CharUnits>>
14956 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14957                                      bool IsSub, ASTContext &Ctx) {
14958   QualType PointeeType = PtrE->getType()->getPointeeType();
14959 
14960   if (!PointeeType->isConstantSizeType())
14961     return llvm::None;
14962 
14963   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14964 
14965   if (!P)
14966     return llvm::None;
14967 
14968   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14969   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14970     CharUnits Offset = EltSize * IdxRes->getExtValue();
14971     if (IsSub)
14972       Offset = -Offset;
14973     return std::make_pair(P->first, P->second + Offset);
14974   }
14975 
14976   // If the integer expression isn't a constant expression, compute the lower
14977   // bound of the alignment using the alignment and offset of the pointer
14978   // expression and the element size.
14979   return std::make_pair(
14980       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14981       CharUnits::Zero());
14982 }
14983 
14984 /// This helper function takes an lvalue expression and returns the alignment of
14985 /// a VarDecl and a constant offset from the VarDecl.
14986 Optional<std::pair<CharUnits, CharUnits>>
14987 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14988   E = E->IgnoreParens();
14989   switch (E->getStmtClass()) {
14990   default:
14991     break;
14992   case Stmt::CStyleCastExprClass:
14993   case Stmt::CXXStaticCastExprClass:
14994   case Stmt::ImplicitCastExprClass: {
14995     auto *CE = cast<CastExpr>(E);
14996     const Expr *From = CE->getSubExpr();
14997     switch (CE->getCastKind()) {
14998     default:
14999       break;
15000     case CK_NoOp:
15001       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15002     case CK_UncheckedDerivedToBase:
15003     case CK_DerivedToBase: {
15004       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15005       if (!P)
15006         break;
15007       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15008                                                 P->second, Ctx);
15009     }
15010     }
15011     break;
15012   }
15013   case Stmt::ArraySubscriptExprClass: {
15014     auto *ASE = cast<ArraySubscriptExpr>(E);
15015     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
15016                                                 false, Ctx);
15017   }
15018   case Stmt::DeclRefExprClass: {
15019     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15020       // FIXME: If VD is captured by copy or is an escaping __block variable,
15021       // use the alignment of VD's type.
15022       if (!VD->getType()->isReferenceType())
15023         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15024       if (VD->hasInit())
15025         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15026     }
15027     break;
15028   }
15029   case Stmt::MemberExprClass: {
15030     auto *ME = cast<MemberExpr>(E);
15031     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15032     if (!FD || FD->getType()->isReferenceType() ||
15033         FD->getParent()->isInvalidDecl())
15034       break;
15035     Optional<std::pair<CharUnits, CharUnits>> P;
15036     if (ME->isArrow())
15037       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15038     else
15039       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15040     if (!P)
15041       break;
15042     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15043     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15044     return std::make_pair(P->first,
15045                           P->second + CharUnits::fromQuantity(Offset));
15046   }
15047   case Stmt::UnaryOperatorClass: {
15048     auto *UO = cast<UnaryOperator>(E);
15049     switch (UO->getOpcode()) {
15050     default:
15051       break;
15052     case UO_Deref:
15053       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
15054     }
15055     break;
15056   }
15057   case Stmt::BinaryOperatorClass: {
15058     auto *BO = cast<BinaryOperator>(E);
15059     auto Opcode = BO->getOpcode();
15060     switch (Opcode) {
15061     default:
15062       break;
15063     case BO_Comma:
15064       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
15065     }
15066     break;
15067   }
15068   }
15069   return llvm::None;
15070 }
15071 
15072 /// This helper function takes a pointer expression and returns the alignment of
15073 /// a VarDecl and a constant offset from the VarDecl.
15074 Optional<std::pair<CharUnits, CharUnits>>
15075 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
15076   E = E->IgnoreParens();
15077   switch (E->getStmtClass()) {
15078   default:
15079     break;
15080   case Stmt::CStyleCastExprClass:
15081   case Stmt::CXXStaticCastExprClass:
15082   case Stmt::ImplicitCastExprClass: {
15083     auto *CE = cast<CastExpr>(E);
15084     const Expr *From = CE->getSubExpr();
15085     switch (CE->getCastKind()) {
15086     default:
15087       break;
15088     case CK_NoOp:
15089       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15090     case CK_ArrayToPointerDecay:
15091       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15092     case CK_UncheckedDerivedToBase:
15093     case CK_DerivedToBase: {
15094       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15095       if (!P)
15096         break;
15097       return getDerivedToBaseAlignmentAndOffset(
15098           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15099     }
15100     }
15101     break;
15102   }
15103   case Stmt::CXXThisExprClass: {
15104     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15105     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
15106     return std::make_pair(Alignment, CharUnits::Zero());
15107   }
15108   case Stmt::UnaryOperatorClass: {
15109     auto *UO = cast<UnaryOperator>(E);
15110     if (UO->getOpcode() == UO_AddrOf)
15111       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
15112     break;
15113   }
15114   case Stmt::BinaryOperatorClass: {
15115     auto *BO = cast<BinaryOperator>(E);
15116     auto Opcode = BO->getOpcode();
15117     switch (Opcode) {
15118     default:
15119       break;
15120     case BO_Add:
15121     case BO_Sub: {
15122       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15123       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15124         std::swap(LHS, RHS);
15125       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15126                                                   Ctx);
15127     }
15128     case BO_Comma:
15129       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15130     }
15131     break;
15132   }
15133   }
15134   return llvm::None;
15135 }
15136 
15137 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
15138   // See if we can compute the alignment of a VarDecl and an offset from it.
15139   Optional<std::pair<CharUnits, CharUnits>> P =
15140       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
15141 
15142   if (P)
15143     return P->first.alignmentAtOffset(P->second);
15144 
15145   // If that failed, return the type's alignment.
15146   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
15147 }
15148 
15149 /// CheckCastAlign - Implements -Wcast-align, which warns when a
15150 /// pointer cast increases the alignment requirements.
15151 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
15152   // This is actually a lot of work to potentially be doing on every
15153   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15154   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15155     return;
15156 
15157   // Ignore dependent types.
15158   if (T->isDependentType() || Op->getType()->isDependentType())
15159     return;
15160 
15161   // Require that the destination be a pointer type.
15162   const PointerType *DestPtr = T->getAs<PointerType>();
15163   if (!DestPtr) return;
15164 
15165   // If the destination has alignment 1, we're done.
15166   QualType DestPointee = DestPtr->getPointeeType();
15167   if (DestPointee->isIncompleteType()) return;
15168   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15169   if (DestAlign.isOne()) return;
15170 
15171   // Require that the source be a pointer type.
15172   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15173   if (!SrcPtr) return;
15174   QualType SrcPointee = SrcPtr->getPointeeType();
15175 
15176   // Explicitly allow casts from cv void*.  We already implicitly
15177   // allowed casts to cv void*, since they have alignment 1.
15178   // Also allow casts involving incomplete types, which implicitly
15179   // includes 'void'.
15180   if (SrcPointee->isIncompleteType()) return;
15181 
15182   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15183 
15184   if (SrcAlign >= DestAlign) return;
15185 
15186   Diag(TRange.getBegin(), diag::warn_cast_align)
15187     << Op->getType() << T
15188     << static_cast<unsigned>(SrcAlign.getQuantity())
15189     << static_cast<unsigned>(DestAlign.getQuantity())
15190     << TRange << Op->getSourceRange();
15191 }
15192 
15193 /// Check whether this array fits the idiom of a size-one tail padded
15194 /// array member of a struct.
15195 ///
15196 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
15197 /// commonly used to emulate flexible arrays in C89 code.
15198 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
15199                                     const NamedDecl *ND) {
15200   if (Size != 1 || !ND) return false;
15201 
15202   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
15203   if (!FD) return false;
15204 
15205   // Don't consider sizes resulting from macro expansions or template argument
15206   // substitution to form C89 tail-padded arrays.
15207 
15208   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
15209   while (TInfo) {
15210     TypeLoc TL = TInfo->getTypeLoc();
15211     // Look through typedefs.
15212     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
15213       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
15214       TInfo = TDL->getTypeSourceInfo();
15215       continue;
15216     }
15217     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
15218       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
15219       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
15220         return false;
15221     }
15222     break;
15223   }
15224 
15225   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
15226   if (!RD) return false;
15227   if (RD->isUnion()) return false;
15228   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15229     if (!CRD->isStandardLayout()) return false;
15230   }
15231 
15232   // See if this is the last field decl in the record.
15233   const Decl *D = FD;
15234   while ((D = D->getNextDeclInContext()))
15235     if (isa<FieldDecl>(D))
15236       return false;
15237   return true;
15238 }
15239 
15240 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15241                             const ArraySubscriptExpr *ASE,
15242                             bool AllowOnePastEnd, bool IndexNegated) {
15243   // Already diagnosed by the constant evaluator.
15244   if (isConstantEvaluated())
15245     return;
15246 
15247   IndexExpr = IndexExpr->IgnoreParenImpCasts();
15248   if (IndexExpr->isValueDependent())
15249     return;
15250 
15251   const Type *EffectiveType =
15252       BaseExpr->getType()->getPointeeOrArrayElementType();
15253   BaseExpr = BaseExpr->IgnoreParenCasts();
15254   const ConstantArrayType *ArrayTy =
15255       Context.getAsConstantArrayType(BaseExpr->getType());
15256 
15257   const Type *BaseType =
15258       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15259   bool IsUnboundedArray = (BaseType == nullptr);
15260   if (EffectiveType->isDependentType() ||
15261       (!IsUnboundedArray && BaseType->isDependentType()))
15262     return;
15263 
15264   Expr::EvalResult Result;
15265   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15266     return;
15267 
15268   llvm::APSInt index = Result.Val.getInt();
15269   if (IndexNegated) {
15270     index.setIsUnsigned(false);
15271     index = -index;
15272   }
15273 
15274   const NamedDecl *ND = nullptr;
15275   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15276     ND = DRE->getDecl();
15277   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
15278     ND = ME->getMemberDecl();
15279 
15280   if (IsUnboundedArray) {
15281     if (index.isUnsigned() || !index.isNegative()) {
15282       const auto &ASTC = getASTContext();
15283       unsigned AddrBits =
15284           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
15285               EffectiveType->getCanonicalTypeInternal()));
15286       if (index.getBitWidth() < AddrBits)
15287         index = index.zext(AddrBits);
15288       Optional<CharUnits> ElemCharUnits =
15289           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15290       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15291       // pointer) bounds-checking isn't meaningful.
15292       if (!ElemCharUnits)
15293         return;
15294       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15295       // If index has more active bits than address space, we already know
15296       // we have a bounds violation to warn about.  Otherwise, compute
15297       // address of (index + 1)th element, and warn about bounds violation
15298       // only if that address exceeds address space.
15299       if (index.getActiveBits() <= AddrBits) {
15300         bool Overflow;
15301         llvm::APInt Product(index);
15302         Product += 1;
15303         Product = Product.umul_ov(ElemBytes, Overflow);
15304         if (!Overflow && Product.getActiveBits() <= AddrBits)
15305           return;
15306       }
15307 
15308       // Need to compute max possible elements in address space, since that
15309       // is included in diag message.
15310       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15311       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15312       MaxElems += 1;
15313       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15314       MaxElems = MaxElems.udiv(ElemBytes);
15315 
15316       unsigned DiagID =
15317           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15318               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15319 
15320       // Diag message shows element size in bits and in "bytes" (platform-
15321       // dependent CharUnits)
15322       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15323                           PDiag(DiagID)
15324                               << toString(index, 10, true) << AddrBits
15325                               << (unsigned)ASTC.toBits(*ElemCharUnits)
15326                               << toString(ElemBytes, 10, false)
15327                               << toString(MaxElems, 10, false)
15328                               << (unsigned)MaxElems.getLimitedValue(~0U)
15329                               << IndexExpr->getSourceRange());
15330 
15331       if (!ND) {
15332         // Try harder to find a NamedDecl to point at in the note.
15333         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15334           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15335         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15336           ND = DRE->getDecl();
15337         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15338           ND = ME->getMemberDecl();
15339       }
15340 
15341       if (ND)
15342         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15343                             PDiag(diag::note_array_declared_here) << ND);
15344     }
15345     return;
15346   }
15347 
15348   if (index.isUnsigned() || !index.isNegative()) {
15349     // It is possible that the type of the base expression after
15350     // IgnoreParenCasts is incomplete, even though the type of the base
15351     // expression before IgnoreParenCasts is complete (see PR39746 for an
15352     // example). In this case we have no information about whether the array
15353     // access exceeds the array bounds. However we can still diagnose an array
15354     // access which precedes the array bounds.
15355     if (BaseType->isIncompleteType())
15356       return;
15357 
15358     llvm::APInt size = ArrayTy->getSize();
15359     if (!size.isStrictlyPositive())
15360       return;
15361 
15362     if (BaseType != EffectiveType) {
15363       // Make sure we're comparing apples to apples when comparing index to size
15364       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15365       uint64_t array_typesize = Context.getTypeSize(BaseType);
15366       // Handle ptrarith_typesize being zero, such as when casting to void*
15367       if (!ptrarith_typesize) ptrarith_typesize = 1;
15368       if (ptrarith_typesize != array_typesize) {
15369         // There's a cast to a different size type involved
15370         uint64_t ratio = array_typesize / ptrarith_typesize;
15371         // TODO: Be smarter about handling cases where array_typesize is not a
15372         // multiple of ptrarith_typesize
15373         if (ptrarith_typesize * ratio == array_typesize)
15374           size *= llvm::APInt(size.getBitWidth(), ratio);
15375       }
15376     }
15377 
15378     if (size.getBitWidth() > index.getBitWidth())
15379       index = index.zext(size.getBitWidth());
15380     else if (size.getBitWidth() < index.getBitWidth())
15381       size = size.zext(index.getBitWidth());
15382 
15383     // For array subscripting the index must be less than size, but for pointer
15384     // arithmetic also allow the index (offset) to be equal to size since
15385     // computing the next address after the end of the array is legal and
15386     // commonly done e.g. in C++ iterators and range-based for loops.
15387     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15388       return;
15389 
15390     // Also don't warn for arrays of size 1 which are members of some
15391     // structure. These are often used to approximate flexible arrays in C89
15392     // code.
15393     if (IsTailPaddedMemberArray(*this, size, ND))
15394       return;
15395 
15396     // Suppress the warning if the subscript expression (as identified by the
15397     // ']' location) and the index expression are both from macro expansions
15398     // within a system header.
15399     if (ASE) {
15400       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15401           ASE->getRBracketLoc());
15402       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15403         SourceLocation IndexLoc =
15404             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15405         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15406           return;
15407       }
15408     }
15409 
15410     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15411                           : diag::warn_ptr_arith_exceeds_bounds;
15412 
15413     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15414                         PDiag(DiagID) << toString(index, 10, true)
15415                                       << toString(size, 10, true)
15416                                       << (unsigned)size.getLimitedValue(~0U)
15417                                       << IndexExpr->getSourceRange());
15418   } else {
15419     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15420     if (!ASE) {
15421       DiagID = diag::warn_ptr_arith_precedes_bounds;
15422       if (index.isNegative()) index = -index;
15423     }
15424 
15425     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15426                         PDiag(DiagID) << toString(index, 10, true)
15427                                       << IndexExpr->getSourceRange());
15428   }
15429 
15430   if (!ND) {
15431     // Try harder to find a NamedDecl to point at in the note.
15432     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15433       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15434     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15435       ND = DRE->getDecl();
15436     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15437       ND = ME->getMemberDecl();
15438   }
15439 
15440   if (ND)
15441     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15442                         PDiag(diag::note_array_declared_here) << ND);
15443 }
15444 
15445 void Sema::CheckArrayAccess(const Expr *expr) {
15446   int AllowOnePastEnd = 0;
15447   while (expr) {
15448     expr = expr->IgnoreParenImpCasts();
15449     switch (expr->getStmtClass()) {
15450       case Stmt::ArraySubscriptExprClass: {
15451         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15452         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15453                          AllowOnePastEnd > 0);
15454         expr = ASE->getBase();
15455         break;
15456       }
15457       case Stmt::MemberExprClass: {
15458         expr = cast<MemberExpr>(expr)->getBase();
15459         break;
15460       }
15461       case Stmt::OMPArraySectionExprClass: {
15462         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15463         if (ASE->getLowerBound())
15464           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15465                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15466         return;
15467       }
15468       case Stmt::UnaryOperatorClass: {
15469         // Only unwrap the * and & unary operators
15470         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15471         expr = UO->getSubExpr();
15472         switch (UO->getOpcode()) {
15473           case UO_AddrOf:
15474             AllowOnePastEnd++;
15475             break;
15476           case UO_Deref:
15477             AllowOnePastEnd--;
15478             break;
15479           default:
15480             return;
15481         }
15482         break;
15483       }
15484       case Stmt::ConditionalOperatorClass: {
15485         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15486         if (const Expr *lhs = cond->getLHS())
15487           CheckArrayAccess(lhs);
15488         if (const Expr *rhs = cond->getRHS())
15489           CheckArrayAccess(rhs);
15490         return;
15491       }
15492       case Stmt::CXXOperatorCallExprClass: {
15493         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15494         for (const auto *Arg : OCE->arguments())
15495           CheckArrayAccess(Arg);
15496         return;
15497       }
15498       default:
15499         return;
15500     }
15501   }
15502 }
15503 
15504 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15505 
15506 namespace {
15507 
15508 struct RetainCycleOwner {
15509   VarDecl *Variable = nullptr;
15510   SourceRange Range;
15511   SourceLocation Loc;
15512   bool Indirect = false;
15513 
15514   RetainCycleOwner() = default;
15515 
15516   void setLocsFrom(Expr *e) {
15517     Loc = e->getExprLoc();
15518     Range = e->getSourceRange();
15519   }
15520 };
15521 
15522 } // namespace
15523 
15524 /// Consider whether capturing the given variable can possibly lead to
15525 /// a retain cycle.
15526 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15527   // In ARC, it's captured strongly iff the variable has __strong
15528   // lifetime.  In MRR, it's captured strongly if the variable is
15529   // __block and has an appropriate type.
15530   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15531     return false;
15532 
15533   owner.Variable = var;
15534   if (ref)
15535     owner.setLocsFrom(ref);
15536   return true;
15537 }
15538 
15539 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15540   while (true) {
15541     e = e->IgnoreParens();
15542     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15543       switch (cast->getCastKind()) {
15544       case CK_BitCast:
15545       case CK_LValueBitCast:
15546       case CK_LValueToRValue:
15547       case CK_ARCReclaimReturnedObject:
15548         e = cast->getSubExpr();
15549         continue;
15550 
15551       default:
15552         return false;
15553       }
15554     }
15555 
15556     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15557       ObjCIvarDecl *ivar = ref->getDecl();
15558       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15559         return false;
15560 
15561       // Try to find a retain cycle in the base.
15562       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15563         return false;
15564 
15565       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15566       owner.Indirect = true;
15567       return true;
15568     }
15569 
15570     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15571       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15572       if (!var) return false;
15573       return considerVariable(var, ref, owner);
15574     }
15575 
15576     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15577       if (member->isArrow()) return false;
15578 
15579       // Don't count this as an indirect ownership.
15580       e = member->getBase();
15581       continue;
15582     }
15583 
15584     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15585       // Only pay attention to pseudo-objects on property references.
15586       ObjCPropertyRefExpr *pre
15587         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15588                                               ->IgnoreParens());
15589       if (!pre) return false;
15590       if (pre->isImplicitProperty()) return false;
15591       ObjCPropertyDecl *property = pre->getExplicitProperty();
15592       if (!property->isRetaining() &&
15593           !(property->getPropertyIvarDecl() &&
15594             property->getPropertyIvarDecl()->getType()
15595               .getObjCLifetime() == Qualifiers::OCL_Strong))
15596           return false;
15597 
15598       owner.Indirect = true;
15599       if (pre->isSuperReceiver()) {
15600         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15601         if (!owner.Variable)
15602           return false;
15603         owner.Loc = pre->getLocation();
15604         owner.Range = pre->getSourceRange();
15605         return true;
15606       }
15607       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15608                               ->getSourceExpr());
15609       continue;
15610     }
15611 
15612     // Array ivars?
15613 
15614     return false;
15615   }
15616 }
15617 
15618 namespace {
15619 
15620   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15621     ASTContext &Context;
15622     VarDecl *Variable;
15623     Expr *Capturer = nullptr;
15624     bool VarWillBeReased = false;
15625 
15626     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15627         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15628           Context(Context), Variable(variable) {}
15629 
15630     void VisitDeclRefExpr(DeclRefExpr *ref) {
15631       if (ref->getDecl() == Variable && !Capturer)
15632         Capturer = ref;
15633     }
15634 
15635     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15636       if (Capturer) return;
15637       Visit(ref->getBase());
15638       if (Capturer && ref->isFreeIvar())
15639         Capturer = ref;
15640     }
15641 
15642     void VisitBlockExpr(BlockExpr *block) {
15643       // Look inside nested blocks
15644       if (block->getBlockDecl()->capturesVariable(Variable))
15645         Visit(block->getBlockDecl()->getBody());
15646     }
15647 
15648     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15649       if (Capturer) return;
15650       if (OVE->getSourceExpr())
15651         Visit(OVE->getSourceExpr());
15652     }
15653 
15654     void VisitBinaryOperator(BinaryOperator *BinOp) {
15655       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15656         return;
15657       Expr *LHS = BinOp->getLHS();
15658       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15659         if (DRE->getDecl() != Variable)
15660           return;
15661         if (Expr *RHS = BinOp->getRHS()) {
15662           RHS = RHS->IgnoreParenCasts();
15663           Optional<llvm::APSInt> Value;
15664           VarWillBeReased =
15665               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15666                *Value == 0);
15667         }
15668       }
15669     }
15670   };
15671 
15672 } // namespace
15673 
15674 /// Check whether the given argument is a block which captures a
15675 /// variable.
15676 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15677   assert(owner.Variable && owner.Loc.isValid());
15678 
15679   e = e->IgnoreParenCasts();
15680 
15681   // Look through [^{...} copy] and Block_copy(^{...}).
15682   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15683     Selector Cmd = ME->getSelector();
15684     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15685       e = ME->getInstanceReceiver();
15686       if (!e)
15687         return nullptr;
15688       e = e->IgnoreParenCasts();
15689     }
15690   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15691     if (CE->getNumArgs() == 1) {
15692       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15693       if (Fn) {
15694         const IdentifierInfo *FnI = Fn->getIdentifier();
15695         if (FnI && FnI->isStr("_Block_copy")) {
15696           e = CE->getArg(0)->IgnoreParenCasts();
15697         }
15698       }
15699     }
15700   }
15701 
15702   BlockExpr *block = dyn_cast<BlockExpr>(e);
15703   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15704     return nullptr;
15705 
15706   FindCaptureVisitor visitor(S.Context, owner.Variable);
15707   visitor.Visit(block->getBlockDecl()->getBody());
15708   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15709 }
15710 
15711 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15712                                 RetainCycleOwner &owner) {
15713   assert(capturer);
15714   assert(owner.Variable && owner.Loc.isValid());
15715 
15716   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15717     << owner.Variable << capturer->getSourceRange();
15718   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15719     << owner.Indirect << owner.Range;
15720 }
15721 
15722 /// Check for a keyword selector that starts with the word 'add' or
15723 /// 'set'.
15724 static bool isSetterLikeSelector(Selector sel) {
15725   if (sel.isUnarySelector()) return false;
15726 
15727   StringRef str = sel.getNameForSlot(0);
15728   while (!str.empty() && str.front() == '_') str = str.substr(1);
15729   if (str.startswith("set"))
15730     str = str.substr(3);
15731   else if (str.startswith("add")) {
15732     // Specially allow 'addOperationWithBlock:'.
15733     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15734       return false;
15735     str = str.substr(3);
15736   }
15737   else
15738     return false;
15739 
15740   if (str.empty()) return true;
15741   return !isLowercase(str.front());
15742 }
15743 
15744 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15745                                                     ObjCMessageExpr *Message) {
15746   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15747                                                 Message->getReceiverInterface(),
15748                                                 NSAPI::ClassId_NSMutableArray);
15749   if (!IsMutableArray) {
15750     return None;
15751   }
15752 
15753   Selector Sel = Message->getSelector();
15754 
15755   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15756     S.NSAPIObj->getNSArrayMethodKind(Sel);
15757   if (!MKOpt) {
15758     return None;
15759   }
15760 
15761   NSAPI::NSArrayMethodKind MK = *MKOpt;
15762 
15763   switch (MK) {
15764     case NSAPI::NSMutableArr_addObject:
15765     case NSAPI::NSMutableArr_insertObjectAtIndex:
15766     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15767       return 0;
15768     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15769       return 1;
15770 
15771     default:
15772       return None;
15773   }
15774 
15775   return None;
15776 }
15777 
15778 static
15779 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15780                                                   ObjCMessageExpr *Message) {
15781   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15782                                             Message->getReceiverInterface(),
15783                                             NSAPI::ClassId_NSMutableDictionary);
15784   if (!IsMutableDictionary) {
15785     return None;
15786   }
15787 
15788   Selector Sel = Message->getSelector();
15789 
15790   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15791     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15792   if (!MKOpt) {
15793     return None;
15794   }
15795 
15796   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15797 
15798   switch (MK) {
15799     case NSAPI::NSMutableDict_setObjectForKey:
15800     case NSAPI::NSMutableDict_setValueForKey:
15801     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15802       return 0;
15803 
15804     default:
15805       return None;
15806   }
15807 
15808   return None;
15809 }
15810 
15811 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15812   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15813                                                 Message->getReceiverInterface(),
15814                                                 NSAPI::ClassId_NSMutableSet);
15815 
15816   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15817                                             Message->getReceiverInterface(),
15818                                             NSAPI::ClassId_NSMutableOrderedSet);
15819   if (!IsMutableSet && !IsMutableOrderedSet) {
15820     return None;
15821   }
15822 
15823   Selector Sel = Message->getSelector();
15824 
15825   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15826   if (!MKOpt) {
15827     return None;
15828   }
15829 
15830   NSAPI::NSSetMethodKind MK = *MKOpt;
15831 
15832   switch (MK) {
15833     case NSAPI::NSMutableSet_addObject:
15834     case NSAPI::NSOrderedSet_setObjectAtIndex:
15835     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15836     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15837       return 0;
15838     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15839       return 1;
15840   }
15841 
15842   return None;
15843 }
15844 
15845 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15846   if (!Message->isInstanceMessage()) {
15847     return;
15848   }
15849 
15850   Optional<int> ArgOpt;
15851 
15852   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15853       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15854       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15855     return;
15856   }
15857 
15858   int ArgIndex = *ArgOpt;
15859 
15860   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15861   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15862     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15863   }
15864 
15865   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15866     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15867       if (ArgRE->isObjCSelfExpr()) {
15868         Diag(Message->getSourceRange().getBegin(),
15869              diag::warn_objc_circular_container)
15870           << ArgRE->getDecl() << StringRef("'super'");
15871       }
15872     }
15873   } else {
15874     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15875 
15876     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15877       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15878     }
15879 
15880     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15881       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15882         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15883           ValueDecl *Decl = ReceiverRE->getDecl();
15884           Diag(Message->getSourceRange().getBegin(),
15885                diag::warn_objc_circular_container)
15886             << Decl << Decl;
15887           if (!ArgRE->isObjCSelfExpr()) {
15888             Diag(Decl->getLocation(),
15889                  diag::note_objc_circular_container_declared_here)
15890               << Decl;
15891           }
15892         }
15893       }
15894     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15895       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15896         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15897           ObjCIvarDecl *Decl = IvarRE->getDecl();
15898           Diag(Message->getSourceRange().getBegin(),
15899                diag::warn_objc_circular_container)
15900             << Decl << Decl;
15901           Diag(Decl->getLocation(),
15902                diag::note_objc_circular_container_declared_here)
15903             << Decl;
15904         }
15905       }
15906     }
15907   }
15908 }
15909 
15910 /// Check a message send to see if it's likely to cause a retain cycle.
15911 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15912   // Only check instance methods whose selector looks like a setter.
15913   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15914     return;
15915 
15916   // Try to find a variable that the receiver is strongly owned by.
15917   RetainCycleOwner owner;
15918   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15919     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15920       return;
15921   } else {
15922     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15923     owner.Variable = getCurMethodDecl()->getSelfDecl();
15924     owner.Loc = msg->getSuperLoc();
15925     owner.Range = msg->getSuperLoc();
15926   }
15927 
15928   // Check whether the receiver is captured by any of the arguments.
15929   const ObjCMethodDecl *MD = msg->getMethodDecl();
15930   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15931     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15932       // noescape blocks should not be retained by the method.
15933       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15934         continue;
15935       return diagnoseRetainCycle(*this, capturer, owner);
15936     }
15937   }
15938 }
15939 
15940 /// Check a property assign to see if it's likely to cause a retain cycle.
15941 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15942   RetainCycleOwner owner;
15943   if (!findRetainCycleOwner(*this, receiver, owner))
15944     return;
15945 
15946   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15947     diagnoseRetainCycle(*this, capturer, owner);
15948 }
15949 
15950 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15951   RetainCycleOwner Owner;
15952   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15953     return;
15954 
15955   // Because we don't have an expression for the variable, we have to set the
15956   // location explicitly here.
15957   Owner.Loc = Var->getLocation();
15958   Owner.Range = Var->getSourceRange();
15959 
15960   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15961     diagnoseRetainCycle(*this, Capturer, Owner);
15962 }
15963 
15964 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15965                                      Expr *RHS, bool isProperty) {
15966   // Check if RHS is an Objective-C object literal, which also can get
15967   // immediately zapped in a weak reference.  Note that we explicitly
15968   // allow ObjCStringLiterals, since those are designed to never really die.
15969   RHS = RHS->IgnoreParenImpCasts();
15970 
15971   // This enum needs to match with the 'select' in
15972   // warn_objc_arc_literal_assign (off-by-1).
15973   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15974   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15975     return false;
15976 
15977   S.Diag(Loc, diag::warn_arc_literal_assign)
15978     << (unsigned) Kind
15979     << (isProperty ? 0 : 1)
15980     << RHS->getSourceRange();
15981 
15982   return true;
15983 }
15984 
15985 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15986                                     Qualifiers::ObjCLifetime LT,
15987                                     Expr *RHS, bool isProperty) {
15988   // Strip off any implicit cast added to get to the one ARC-specific.
15989   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15990     if (cast->getCastKind() == CK_ARCConsumeObject) {
15991       S.Diag(Loc, diag::warn_arc_retained_assign)
15992         << (LT == Qualifiers::OCL_ExplicitNone)
15993         << (isProperty ? 0 : 1)
15994         << RHS->getSourceRange();
15995       return true;
15996     }
15997     RHS = cast->getSubExpr();
15998   }
15999 
16000   if (LT == Qualifiers::OCL_Weak &&
16001       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16002     return true;
16003 
16004   return false;
16005 }
16006 
16007 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
16008                               QualType LHS, Expr *RHS) {
16009   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
16010 
16011   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
16012     return false;
16013 
16014   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
16015     return true;
16016 
16017   return false;
16018 }
16019 
16020 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
16021                               Expr *LHS, Expr *RHS) {
16022   QualType LHSType;
16023   // PropertyRef on LHS type need be directly obtained from
16024   // its declaration as it has a PseudoType.
16025   ObjCPropertyRefExpr *PRE
16026     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
16027   if (PRE && !PRE->isImplicitProperty()) {
16028     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16029     if (PD)
16030       LHSType = PD->getType();
16031   }
16032 
16033   if (LHSType.isNull())
16034     LHSType = LHS->getType();
16035 
16036   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
16037 
16038   if (LT == Qualifiers::OCL_Weak) {
16039     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
16040       getCurFunction()->markSafeWeakUse(LHS);
16041   }
16042 
16043   if (checkUnsafeAssigns(Loc, LHSType, RHS))
16044     return;
16045 
16046   // FIXME. Check for other life times.
16047   if (LT != Qualifiers::OCL_None)
16048     return;
16049 
16050   if (PRE) {
16051     if (PRE->isImplicitProperty())
16052       return;
16053     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16054     if (!PD)
16055       return;
16056 
16057     unsigned Attributes = PD->getPropertyAttributes();
16058     if (Attributes & ObjCPropertyAttribute::kind_assign) {
16059       // when 'assign' attribute was not explicitly specified
16060       // by user, ignore it and rely on property type itself
16061       // for lifetime info.
16062       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16063       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16064           LHSType->isObjCRetainableType())
16065         return;
16066 
16067       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16068         if (cast->getCastKind() == CK_ARCConsumeObject) {
16069           Diag(Loc, diag::warn_arc_retained_property_assign)
16070           << RHS->getSourceRange();
16071           return;
16072         }
16073         RHS = cast->getSubExpr();
16074       }
16075     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16076       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
16077         return;
16078     }
16079   }
16080 }
16081 
16082 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16083 
16084 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16085                                         SourceLocation StmtLoc,
16086                                         const NullStmt *Body) {
16087   // Do not warn if the body is a macro that expands to nothing, e.g:
16088   //
16089   // #define CALL(x)
16090   // if (condition)
16091   //   CALL(0);
16092   if (Body->hasLeadingEmptyMacro())
16093     return false;
16094 
16095   // Get line numbers of statement and body.
16096   bool StmtLineInvalid;
16097   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16098                                                       &StmtLineInvalid);
16099   if (StmtLineInvalid)
16100     return false;
16101 
16102   bool BodyLineInvalid;
16103   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16104                                                       &BodyLineInvalid);
16105   if (BodyLineInvalid)
16106     return false;
16107 
16108   // Warn if null statement and body are on the same line.
16109   if (StmtLine != BodyLine)
16110     return false;
16111 
16112   return true;
16113 }
16114 
16115 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
16116                                  const Stmt *Body,
16117                                  unsigned DiagID) {
16118   // Since this is a syntactic check, don't emit diagnostic for template
16119   // instantiations, this just adds noise.
16120   if (CurrentInstantiationScope)
16121     return;
16122 
16123   // The body should be a null statement.
16124   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16125   if (!NBody)
16126     return;
16127 
16128   // Do the usual checks.
16129   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16130     return;
16131 
16132   Diag(NBody->getSemiLoc(), DiagID);
16133   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16134 }
16135 
16136 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
16137                                  const Stmt *PossibleBody) {
16138   assert(!CurrentInstantiationScope); // Ensured by caller
16139 
16140   SourceLocation StmtLoc;
16141   const Stmt *Body;
16142   unsigned DiagID;
16143   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16144     StmtLoc = FS->getRParenLoc();
16145     Body = FS->getBody();
16146     DiagID = diag::warn_empty_for_body;
16147   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16148     StmtLoc = WS->getCond()->getSourceRange().getEnd();
16149     Body = WS->getBody();
16150     DiagID = diag::warn_empty_while_body;
16151   } else
16152     return; // Neither `for' nor `while'.
16153 
16154   // The body should be a null statement.
16155   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16156   if (!NBody)
16157     return;
16158 
16159   // Skip expensive checks if diagnostic is disabled.
16160   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16161     return;
16162 
16163   // Do the usual checks.
16164   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16165     return;
16166 
16167   // `for(...);' and `while(...);' are popular idioms, so in order to keep
16168   // noise level low, emit diagnostics only if for/while is followed by a
16169   // CompoundStmt, e.g.:
16170   //    for (int i = 0; i < n; i++);
16171   //    {
16172   //      a(i);
16173   //    }
16174   // or if for/while is followed by a statement with more indentation
16175   // than for/while itself:
16176   //    for (int i = 0; i < n; i++);
16177   //      a(i);
16178   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16179   if (!ProbableTypo) {
16180     bool BodyColInvalid;
16181     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16182         PossibleBody->getBeginLoc(), &BodyColInvalid);
16183     if (BodyColInvalid)
16184       return;
16185 
16186     bool StmtColInvalid;
16187     unsigned StmtCol =
16188         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16189     if (StmtColInvalid)
16190       return;
16191 
16192     if (BodyCol > StmtCol)
16193       ProbableTypo = true;
16194   }
16195 
16196   if (ProbableTypo) {
16197     Diag(NBody->getSemiLoc(), DiagID);
16198     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16199   }
16200 }
16201 
16202 //===--- CHECK: Warn on self move with std::move. -------------------------===//
16203 
16204 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
16205 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16206                              SourceLocation OpLoc) {
16207   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16208     return;
16209 
16210   if (inTemplateInstantiation())
16211     return;
16212 
16213   // Strip parens and casts away.
16214   LHSExpr = LHSExpr->IgnoreParenImpCasts();
16215   RHSExpr = RHSExpr->IgnoreParenImpCasts();
16216 
16217   // Check for a call expression
16218   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
16219   if (!CE || CE->getNumArgs() != 1)
16220     return;
16221 
16222   // Check for a call to std::move
16223   if (!CE->isCallToStdMove())
16224     return;
16225 
16226   // Get argument from std::move
16227   RHSExpr = CE->getArg(0);
16228 
16229   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16230   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16231 
16232   // Two DeclRefExpr's, check that the decls are the same.
16233   if (LHSDeclRef && RHSDeclRef) {
16234     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16235       return;
16236     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16237         RHSDeclRef->getDecl()->getCanonicalDecl())
16238       return;
16239 
16240     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16241                                         << LHSExpr->getSourceRange()
16242                                         << RHSExpr->getSourceRange();
16243     return;
16244   }
16245 
16246   // Member variables require a different approach to check for self moves.
16247   // MemberExpr's are the same if every nested MemberExpr refers to the same
16248   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16249   // the base Expr's are CXXThisExpr's.
16250   const Expr *LHSBase = LHSExpr;
16251   const Expr *RHSBase = RHSExpr;
16252   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16253   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16254   if (!LHSME || !RHSME)
16255     return;
16256 
16257   while (LHSME && RHSME) {
16258     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16259         RHSME->getMemberDecl()->getCanonicalDecl())
16260       return;
16261 
16262     LHSBase = LHSME->getBase();
16263     RHSBase = RHSME->getBase();
16264     LHSME = dyn_cast<MemberExpr>(LHSBase);
16265     RHSME = dyn_cast<MemberExpr>(RHSBase);
16266   }
16267 
16268   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16269   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16270   if (LHSDeclRef && RHSDeclRef) {
16271     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16272       return;
16273     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16274         RHSDeclRef->getDecl()->getCanonicalDecl())
16275       return;
16276 
16277     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16278                                         << LHSExpr->getSourceRange()
16279                                         << RHSExpr->getSourceRange();
16280     return;
16281   }
16282 
16283   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16284     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16285                                         << LHSExpr->getSourceRange()
16286                                         << RHSExpr->getSourceRange();
16287 }
16288 
16289 //===--- Layout compatibility ----------------------------------------------//
16290 
16291 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
16292 
16293 /// Check if two enumeration types are layout-compatible.
16294 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
16295   // C++11 [dcl.enum] p8:
16296   // Two enumeration types are layout-compatible if they have the same
16297   // underlying type.
16298   return ED1->isComplete() && ED2->isComplete() &&
16299          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16300 }
16301 
16302 /// Check if two fields are layout-compatible.
16303 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
16304                                FieldDecl *Field2) {
16305   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16306     return false;
16307 
16308   if (Field1->isBitField() != Field2->isBitField())
16309     return false;
16310 
16311   if (Field1->isBitField()) {
16312     // Make sure that the bit-fields are the same length.
16313     unsigned Bits1 = Field1->getBitWidthValue(C);
16314     unsigned Bits2 = Field2->getBitWidthValue(C);
16315 
16316     if (Bits1 != Bits2)
16317       return false;
16318   }
16319 
16320   return true;
16321 }
16322 
16323 /// Check if two standard-layout structs are layout-compatible.
16324 /// (C++11 [class.mem] p17)
16325 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
16326                                      RecordDecl *RD2) {
16327   // If both records are C++ classes, check that base classes match.
16328   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
16329     // If one of records is a CXXRecordDecl we are in C++ mode,
16330     // thus the other one is a CXXRecordDecl, too.
16331     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
16332     // Check number of base classes.
16333     if (D1CXX->getNumBases() != D2CXX->getNumBases())
16334       return false;
16335 
16336     // Check the base classes.
16337     for (CXXRecordDecl::base_class_const_iterator
16338                Base1 = D1CXX->bases_begin(),
16339            BaseEnd1 = D1CXX->bases_end(),
16340               Base2 = D2CXX->bases_begin();
16341          Base1 != BaseEnd1;
16342          ++Base1, ++Base2) {
16343       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16344         return false;
16345     }
16346   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16347     // If only RD2 is a C++ class, it should have zero base classes.
16348     if (D2CXX->getNumBases() > 0)
16349       return false;
16350   }
16351 
16352   // Check the fields.
16353   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16354                              Field2End = RD2->field_end(),
16355                              Field1 = RD1->field_begin(),
16356                              Field1End = RD1->field_end();
16357   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16358     if (!isLayoutCompatible(C, *Field1, *Field2))
16359       return false;
16360   }
16361   if (Field1 != Field1End || Field2 != Field2End)
16362     return false;
16363 
16364   return true;
16365 }
16366 
16367 /// Check if two standard-layout unions are layout-compatible.
16368 /// (C++11 [class.mem] p18)
16369 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16370                                     RecordDecl *RD2) {
16371   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16372   for (auto *Field2 : RD2->fields())
16373     UnmatchedFields.insert(Field2);
16374 
16375   for (auto *Field1 : RD1->fields()) {
16376     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16377         I = UnmatchedFields.begin(),
16378         E = UnmatchedFields.end();
16379 
16380     for ( ; I != E; ++I) {
16381       if (isLayoutCompatible(C, Field1, *I)) {
16382         bool Result = UnmatchedFields.erase(*I);
16383         (void) Result;
16384         assert(Result);
16385         break;
16386       }
16387     }
16388     if (I == E)
16389       return false;
16390   }
16391 
16392   return UnmatchedFields.empty();
16393 }
16394 
16395 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16396                                RecordDecl *RD2) {
16397   if (RD1->isUnion() != RD2->isUnion())
16398     return false;
16399 
16400   if (RD1->isUnion())
16401     return isLayoutCompatibleUnion(C, RD1, RD2);
16402   else
16403     return isLayoutCompatibleStruct(C, RD1, RD2);
16404 }
16405 
16406 /// Check if two types are layout-compatible in C++11 sense.
16407 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16408   if (T1.isNull() || T2.isNull())
16409     return false;
16410 
16411   // C++11 [basic.types] p11:
16412   // If two types T1 and T2 are the same type, then T1 and T2 are
16413   // layout-compatible types.
16414   if (C.hasSameType(T1, T2))
16415     return true;
16416 
16417   T1 = T1.getCanonicalType().getUnqualifiedType();
16418   T2 = T2.getCanonicalType().getUnqualifiedType();
16419 
16420   const Type::TypeClass TC1 = T1->getTypeClass();
16421   const Type::TypeClass TC2 = T2->getTypeClass();
16422 
16423   if (TC1 != TC2)
16424     return false;
16425 
16426   if (TC1 == Type::Enum) {
16427     return isLayoutCompatible(C,
16428                               cast<EnumType>(T1)->getDecl(),
16429                               cast<EnumType>(T2)->getDecl());
16430   } else if (TC1 == Type::Record) {
16431     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16432       return false;
16433 
16434     return isLayoutCompatible(C,
16435                               cast<RecordType>(T1)->getDecl(),
16436                               cast<RecordType>(T2)->getDecl());
16437   }
16438 
16439   return false;
16440 }
16441 
16442 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16443 
16444 /// Given a type tag expression find the type tag itself.
16445 ///
16446 /// \param TypeExpr Type tag expression, as it appears in user's code.
16447 ///
16448 /// \param VD Declaration of an identifier that appears in a type tag.
16449 ///
16450 /// \param MagicValue Type tag magic value.
16451 ///
16452 /// \param isConstantEvaluated whether the evalaution should be performed in
16453 
16454 /// constant context.
16455 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16456                             const ValueDecl **VD, uint64_t *MagicValue,
16457                             bool isConstantEvaluated) {
16458   while(true) {
16459     if (!TypeExpr)
16460       return false;
16461 
16462     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16463 
16464     switch (TypeExpr->getStmtClass()) {
16465     case Stmt::UnaryOperatorClass: {
16466       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16467       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16468         TypeExpr = UO->getSubExpr();
16469         continue;
16470       }
16471       return false;
16472     }
16473 
16474     case Stmt::DeclRefExprClass: {
16475       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16476       *VD = DRE->getDecl();
16477       return true;
16478     }
16479 
16480     case Stmt::IntegerLiteralClass: {
16481       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16482       llvm::APInt MagicValueAPInt = IL->getValue();
16483       if (MagicValueAPInt.getActiveBits() <= 64) {
16484         *MagicValue = MagicValueAPInt.getZExtValue();
16485         return true;
16486       } else
16487         return false;
16488     }
16489 
16490     case Stmt::BinaryConditionalOperatorClass:
16491     case Stmt::ConditionalOperatorClass: {
16492       const AbstractConditionalOperator *ACO =
16493           cast<AbstractConditionalOperator>(TypeExpr);
16494       bool Result;
16495       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16496                                                      isConstantEvaluated)) {
16497         if (Result)
16498           TypeExpr = ACO->getTrueExpr();
16499         else
16500           TypeExpr = ACO->getFalseExpr();
16501         continue;
16502       }
16503       return false;
16504     }
16505 
16506     case Stmt::BinaryOperatorClass: {
16507       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16508       if (BO->getOpcode() == BO_Comma) {
16509         TypeExpr = BO->getRHS();
16510         continue;
16511       }
16512       return false;
16513     }
16514 
16515     default:
16516       return false;
16517     }
16518   }
16519 }
16520 
16521 /// Retrieve the C type corresponding to type tag TypeExpr.
16522 ///
16523 /// \param TypeExpr Expression that specifies a type tag.
16524 ///
16525 /// \param MagicValues Registered magic values.
16526 ///
16527 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16528 ///        kind.
16529 ///
16530 /// \param TypeInfo Information about the corresponding C type.
16531 ///
16532 /// \param isConstantEvaluated whether the evalaution should be performed in
16533 /// constant context.
16534 ///
16535 /// \returns true if the corresponding C type was found.
16536 static bool GetMatchingCType(
16537     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16538     const ASTContext &Ctx,
16539     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16540         *MagicValues,
16541     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16542     bool isConstantEvaluated) {
16543   FoundWrongKind = false;
16544 
16545   // Variable declaration that has type_tag_for_datatype attribute.
16546   const ValueDecl *VD = nullptr;
16547 
16548   uint64_t MagicValue;
16549 
16550   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16551     return false;
16552 
16553   if (VD) {
16554     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16555       if (I->getArgumentKind() != ArgumentKind) {
16556         FoundWrongKind = true;
16557         return false;
16558       }
16559       TypeInfo.Type = I->getMatchingCType();
16560       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16561       TypeInfo.MustBeNull = I->getMustBeNull();
16562       return true;
16563     }
16564     return false;
16565   }
16566 
16567   if (!MagicValues)
16568     return false;
16569 
16570   llvm::DenseMap<Sema::TypeTagMagicValue,
16571                  Sema::TypeTagData>::const_iterator I =
16572       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16573   if (I == MagicValues->end())
16574     return false;
16575 
16576   TypeInfo = I->second;
16577   return true;
16578 }
16579 
16580 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16581                                       uint64_t MagicValue, QualType Type,
16582                                       bool LayoutCompatible,
16583                                       bool MustBeNull) {
16584   if (!TypeTagForDatatypeMagicValues)
16585     TypeTagForDatatypeMagicValues.reset(
16586         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16587 
16588   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16589   (*TypeTagForDatatypeMagicValues)[Magic] =
16590       TypeTagData(Type, LayoutCompatible, MustBeNull);
16591 }
16592 
16593 static bool IsSameCharType(QualType T1, QualType T2) {
16594   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16595   if (!BT1)
16596     return false;
16597 
16598   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16599   if (!BT2)
16600     return false;
16601 
16602   BuiltinType::Kind T1Kind = BT1->getKind();
16603   BuiltinType::Kind T2Kind = BT2->getKind();
16604 
16605   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16606          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16607          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16608          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16609 }
16610 
16611 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16612                                     const ArrayRef<const Expr *> ExprArgs,
16613                                     SourceLocation CallSiteLoc) {
16614   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16615   bool IsPointerAttr = Attr->getIsPointer();
16616 
16617   // Retrieve the argument representing the 'type_tag'.
16618   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16619   if (TypeTagIdxAST >= ExprArgs.size()) {
16620     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16621         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16622     return;
16623   }
16624   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16625   bool FoundWrongKind;
16626   TypeTagData TypeInfo;
16627   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16628                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16629                         TypeInfo, isConstantEvaluated())) {
16630     if (FoundWrongKind)
16631       Diag(TypeTagExpr->getExprLoc(),
16632            diag::warn_type_tag_for_datatype_wrong_kind)
16633         << TypeTagExpr->getSourceRange();
16634     return;
16635   }
16636 
16637   // Retrieve the argument representing the 'arg_idx'.
16638   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16639   if (ArgumentIdxAST >= ExprArgs.size()) {
16640     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16641         << 1 << Attr->getArgumentIdx().getSourceIndex();
16642     return;
16643   }
16644   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16645   if (IsPointerAttr) {
16646     // Skip implicit cast of pointer to `void *' (as a function argument).
16647     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16648       if (ICE->getType()->isVoidPointerType() &&
16649           ICE->getCastKind() == CK_BitCast)
16650         ArgumentExpr = ICE->getSubExpr();
16651   }
16652   QualType ArgumentType = ArgumentExpr->getType();
16653 
16654   // Passing a `void*' pointer shouldn't trigger a warning.
16655   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16656     return;
16657 
16658   if (TypeInfo.MustBeNull) {
16659     // Type tag with matching void type requires a null pointer.
16660     if (!ArgumentExpr->isNullPointerConstant(Context,
16661                                              Expr::NPC_ValueDependentIsNotNull)) {
16662       Diag(ArgumentExpr->getExprLoc(),
16663            diag::warn_type_safety_null_pointer_required)
16664           << ArgumentKind->getName()
16665           << ArgumentExpr->getSourceRange()
16666           << TypeTagExpr->getSourceRange();
16667     }
16668     return;
16669   }
16670 
16671   QualType RequiredType = TypeInfo.Type;
16672   if (IsPointerAttr)
16673     RequiredType = Context.getPointerType(RequiredType);
16674 
16675   bool mismatch = false;
16676   if (!TypeInfo.LayoutCompatible) {
16677     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16678 
16679     // C++11 [basic.fundamental] p1:
16680     // Plain char, signed char, and unsigned char are three distinct types.
16681     //
16682     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16683     // char' depending on the current char signedness mode.
16684     if (mismatch)
16685       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16686                                            RequiredType->getPointeeType())) ||
16687           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16688         mismatch = false;
16689   } else
16690     if (IsPointerAttr)
16691       mismatch = !isLayoutCompatible(Context,
16692                                      ArgumentType->getPointeeType(),
16693                                      RequiredType->getPointeeType());
16694     else
16695       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16696 
16697   if (mismatch)
16698     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16699         << ArgumentType << ArgumentKind
16700         << TypeInfo.LayoutCompatible << RequiredType
16701         << ArgumentExpr->getSourceRange()
16702         << TypeTagExpr->getSourceRange();
16703 }
16704 
16705 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16706                                          CharUnits Alignment) {
16707   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16708 }
16709 
16710 void Sema::DiagnoseMisalignedMembers() {
16711   for (MisalignedMember &m : MisalignedMembers) {
16712     const NamedDecl *ND = m.RD;
16713     if (ND->getName().empty()) {
16714       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16715         ND = TD;
16716     }
16717     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16718         << m.MD << ND << m.E->getSourceRange();
16719   }
16720   MisalignedMembers.clear();
16721 }
16722 
16723 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16724   E = E->IgnoreParens();
16725   if (!T->isPointerType() && !T->isIntegerType())
16726     return;
16727   if (isa<UnaryOperator>(E) &&
16728       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16729     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16730     if (isa<MemberExpr>(Op)) {
16731       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16732       if (MA != MisalignedMembers.end() &&
16733           (T->isIntegerType() ||
16734            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16735                                    Context.getTypeAlignInChars(
16736                                        T->getPointeeType()) <= MA->Alignment))))
16737         MisalignedMembers.erase(MA);
16738     }
16739   }
16740 }
16741 
16742 void Sema::RefersToMemberWithReducedAlignment(
16743     Expr *E,
16744     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16745         Action) {
16746   const auto *ME = dyn_cast<MemberExpr>(E);
16747   if (!ME)
16748     return;
16749 
16750   // No need to check expressions with an __unaligned-qualified type.
16751   if (E->getType().getQualifiers().hasUnaligned())
16752     return;
16753 
16754   // For a chain of MemberExpr like "a.b.c.d" this list
16755   // will keep FieldDecl's like [d, c, b].
16756   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16757   const MemberExpr *TopME = nullptr;
16758   bool AnyIsPacked = false;
16759   do {
16760     QualType BaseType = ME->getBase()->getType();
16761     if (BaseType->isDependentType())
16762       return;
16763     if (ME->isArrow())
16764       BaseType = BaseType->getPointeeType();
16765     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16766     if (RD->isInvalidDecl())
16767       return;
16768 
16769     ValueDecl *MD = ME->getMemberDecl();
16770     auto *FD = dyn_cast<FieldDecl>(MD);
16771     // We do not care about non-data members.
16772     if (!FD || FD->isInvalidDecl())
16773       return;
16774 
16775     AnyIsPacked =
16776         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16777     ReverseMemberChain.push_back(FD);
16778 
16779     TopME = ME;
16780     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16781   } while (ME);
16782   assert(TopME && "We did not compute a topmost MemberExpr!");
16783 
16784   // Not the scope of this diagnostic.
16785   if (!AnyIsPacked)
16786     return;
16787 
16788   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16789   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16790   // TODO: The innermost base of the member expression may be too complicated.
16791   // For now, just disregard these cases. This is left for future
16792   // improvement.
16793   if (!DRE && !isa<CXXThisExpr>(TopBase))
16794       return;
16795 
16796   // Alignment expected by the whole expression.
16797   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16798 
16799   // No need to do anything else with this case.
16800   if (ExpectedAlignment.isOne())
16801     return;
16802 
16803   // Synthesize offset of the whole access.
16804   CharUnits Offset;
16805   for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16806     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16807 
16808   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16809   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16810       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16811 
16812   // The base expression of the innermost MemberExpr may give
16813   // stronger guarantees than the class containing the member.
16814   if (DRE && !TopME->isArrow()) {
16815     const ValueDecl *VD = DRE->getDecl();
16816     if (!VD->getType()->isReferenceType())
16817       CompleteObjectAlignment =
16818           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16819   }
16820 
16821   // Check if the synthesized offset fulfills the alignment.
16822   if (Offset % ExpectedAlignment != 0 ||
16823       // It may fulfill the offset it but the effective alignment may still be
16824       // lower than the expected expression alignment.
16825       CompleteObjectAlignment < ExpectedAlignment) {
16826     // If this happens, we want to determine a sensible culprit of this.
16827     // Intuitively, watching the chain of member expressions from right to
16828     // left, we start with the required alignment (as required by the field
16829     // type) but some packed attribute in that chain has reduced the alignment.
16830     // It may happen that another packed structure increases it again. But if
16831     // we are here such increase has not been enough. So pointing the first
16832     // FieldDecl that either is packed or else its RecordDecl is,
16833     // seems reasonable.
16834     FieldDecl *FD = nullptr;
16835     CharUnits Alignment;
16836     for (FieldDecl *FDI : ReverseMemberChain) {
16837       if (FDI->hasAttr<PackedAttr>() ||
16838           FDI->getParent()->hasAttr<PackedAttr>()) {
16839         FD = FDI;
16840         Alignment = std::min(
16841             Context.getTypeAlignInChars(FD->getType()),
16842             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16843         break;
16844       }
16845     }
16846     assert(FD && "We did not find a packed FieldDecl!");
16847     Action(E, FD->getParent(), FD, Alignment);
16848   }
16849 }
16850 
16851 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16852   using namespace std::placeholders;
16853 
16854   RefersToMemberWithReducedAlignment(
16855       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16856                      _2, _3, _4));
16857 }
16858 
16859 // Check if \p Ty is a valid type for the elementwise math builtins. If it is
16860 // not a valid type, emit an error message and return true. Otherwise return
16861 // false.
16862 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc,
16863                                         QualType Ty) {
16864   if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) {
16865     S.Diag(Loc, diag::err_builtin_invalid_arg_type)
16866         << 1 << /* vector, integer or float ty*/ 0 << Ty;
16867     return true;
16868   }
16869   return false;
16870 }
16871 
16872 bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) {
16873   if (checkArgCount(*this, TheCall, 1))
16874     return true;
16875 
16876   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16877   if (A.isInvalid())
16878     return true;
16879 
16880   TheCall->setArg(0, A.get());
16881   QualType TyA = A.get()->getType();
16882 
16883   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
16884     return true;
16885 
16886   TheCall->setType(TyA);
16887   return false;
16888 }
16889 
16890 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) {
16891   if (checkArgCount(*this, TheCall, 2))
16892     return true;
16893 
16894   ExprResult A = TheCall->getArg(0);
16895   ExprResult B = TheCall->getArg(1);
16896   // Do standard promotions between the two arguments, returning their common
16897   // type.
16898   QualType Res =
16899       UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
16900   if (A.isInvalid() || B.isInvalid())
16901     return true;
16902 
16903   QualType TyA = A.get()->getType();
16904   QualType TyB = B.get()->getType();
16905 
16906   if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
16907     return Diag(A.get()->getBeginLoc(),
16908                 diag::err_typecheck_call_different_arg_types)
16909            << TyA << TyB;
16910 
16911   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
16912     return true;
16913 
16914   TheCall->setArg(0, A.get());
16915   TheCall->setArg(1, B.get());
16916   TheCall->setType(Res);
16917   return false;
16918 }
16919 
16920 bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
16921   if (checkArgCount(*this, TheCall, 1))
16922     return true;
16923 
16924   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16925   if (A.isInvalid())
16926     return true;
16927 
16928   TheCall->setArg(0, A.get());
16929   return false;
16930 }
16931 
16932 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16933                                             ExprResult CallResult) {
16934   if (checkArgCount(*this, TheCall, 1))
16935     return ExprError();
16936 
16937   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16938   if (MatrixArg.isInvalid())
16939     return MatrixArg;
16940   Expr *Matrix = MatrixArg.get();
16941 
16942   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16943   if (!MType) {
16944     Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16945         << 1 << /* matrix ty*/ 1 << Matrix->getType();
16946     return ExprError();
16947   }
16948 
16949   // Create returned matrix type by swapping rows and columns of the argument
16950   // matrix type.
16951   QualType ResultType = Context.getConstantMatrixType(
16952       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16953 
16954   // Change the return type to the type of the returned matrix.
16955   TheCall->setType(ResultType);
16956 
16957   // Update call argument to use the possibly converted matrix argument.
16958   TheCall->setArg(0, Matrix);
16959   return CallResult;
16960 }
16961 
16962 // Get and verify the matrix dimensions.
16963 static llvm::Optional<unsigned>
16964 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16965   SourceLocation ErrorPos;
16966   Optional<llvm::APSInt> Value =
16967       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16968   if (!Value) {
16969     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16970         << Name;
16971     return {};
16972   }
16973   uint64_t Dim = Value->getZExtValue();
16974   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16975     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16976         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16977     return {};
16978   }
16979   return Dim;
16980 }
16981 
16982 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16983                                                   ExprResult CallResult) {
16984   if (!getLangOpts().MatrixTypes) {
16985     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16986     return ExprError();
16987   }
16988 
16989   if (checkArgCount(*this, TheCall, 4))
16990     return ExprError();
16991 
16992   unsigned PtrArgIdx = 0;
16993   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16994   Expr *RowsExpr = TheCall->getArg(1);
16995   Expr *ColumnsExpr = TheCall->getArg(2);
16996   Expr *StrideExpr = TheCall->getArg(3);
16997 
16998   bool ArgError = false;
16999 
17000   // Check pointer argument.
17001   {
17002     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17003     if (PtrConv.isInvalid())
17004       return PtrConv;
17005     PtrExpr = PtrConv.get();
17006     TheCall->setArg(0, PtrExpr);
17007     if (PtrExpr->isTypeDependent()) {
17008       TheCall->setType(Context.DependentTy);
17009       return TheCall;
17010     }
17011   }
17012 
17013   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17014   QualType ElementTy;
17015   if (!PtrTy) {
17016     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17017         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17018     ArgError = true;
17019   } else {
17020     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17021 
17022     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
17023       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17024           << PtrArgIdx + 1 << /* pointer to element ty*/ 2
17025           << PtrExpr->getType();
17026       ArgError = true;
17027     }
17028   }
17029 
17030   // Apply default Lvalue conversions and convert the expression to size_t.
17031   auto ApplyArgumentConversions = [this](Expr *E) {
17032     ExprResult Conv = DefaultLvalueConversion(E);
17033     if (Conv.isInvalid())
17034       return Conv;
17035 
17036     return tryConvertExprToType(Conv.get(), Context.getSizeType());
17037   };
17038 
17039   // Apply conversion to row and column expressions.
17040   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17041   if (!RowsConv.isInvalid()) {
17042     RowsExpr = RowsConv.get();
17043     TheCall->setArg(1, RowsExpr);
17044   } else
17045     RowsExpr = nullptr;
17046 
17047   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17048   if (!ColumnsConv.isInvalid()) {
17049     ColumnsExpr = ColumnsConv.get();
17050     TheCall->setArg(2, ColumnsExpr);
17051   } else
17052     ColumnsExpr = nullptr;
17053 
17054   // If any any part of the result matrix type is still pending, just use
17055   // Context.DependentTy, until all parts are resolved.
17056   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17057       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17058     TheCall->setType(Context.DependentTy);
17059     return CallResult;
17060   }
17061 
17062   // Check row and column dimensions.
17063   llvm::Optional<unsigned> MaybeRows;
17064   if (RowsExpr)
17065     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17066 
17067   llvm::Optional<unsigned> MaybeColumns;
17068   if (ColumnsExpr)
17069     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17070 
17071   // Check stride argument.
17072   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17073   if (StrideConv.isInvalid())
17074     return ExprError();
17075   StrideExpr = StrideConv.get();
17076   TheCall->setArg(3, StrideExpr);
17077 
17078   if (MaybeRows) {
17079     if (Optional<llvm::APSInt> Value =
17080             StrideExpr->getIntegerConstantExpr(Context)) {
17081       uint64_t Stride = Value->getZExtValue();
17082       if (Stride < *MaybeRows) {
17083         Diag(StrideExpr->getBeginLoc(),
17084              diag::err_builtin_matrix_stride_too_small);
17085         ArgError = true;
17086       }
17087     }
17088   }
17089 
17090   if (ArgError || !MaybeRows || !MaybeColumns)
17091     return ExprError();
17092 
17093   TheCall->setType(
17094       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17095   return CallResult;
17096 }
17097 
17098 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17099                                                    ExprResult CallResult) {
17100   if (checkArgCount(*this, TheCall, 3))
17101     return ExprError();
17102 
17103   unsigned PtrArgIdx = 1;
17104   Expr *MatrixExpr = TheCall->getArg(0);
17105   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17106   Expr *StrideExpr = TheCall->getArg(2);
17107 
17108   bool ArgError = false;
17109 
17110   {
17111     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17112     if (MatrixConv.isInvalid())
17113       return MatrixConv;
17114     MatrixExpr = MatrixConv.get();
17115     TheCall->setArg(0, MatrixExpr);
17116   }
17117   if (MatrixExpr->isTypeDependent()) {
17118     TheCall->setType(Context.DependentTy);
17119     return TheCall;
17120   }
17121 
17122   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17123   if (!MatrixTy) {
17124     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17125         << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
17126     ArgError = true;
17127   }
17128 
17129   {
17130     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17131     if (PtrConv.isInvalid())
17132       return PtrConv;
17133     PtrExpr = PtrConv.get();
17134     TheCall->setArg(1, PtrExpr);
17135     if (PtrExpr->isTypeDependent()) {
17136       TheCall->setType(Context.DependentTy);
17137       return TheCall;
17138     }
17139   }
17140 
17141   // Check pointer argument.
17142   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17143   if (!PtrTy) {
17144     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17145         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17146     ArgError = true;
17147   } else {
17148     QualType ElementTy = PtrTy->getPointeeType();
17149     if (ElementTy.isConstQualified()) {
17150       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17151       ArgError = true;
17152     }
17153     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17154     if (MatrixTy &&
17155         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17156       Diag(PtrExpr->getBeginLoc(),
17157            diag::err_builtin_matrix_pointer_arg_mismatch)
17158           << ElementTy << MatrixTy->getElementType();
17159       ArgError = true;
17160     }
17161   }
17162 
17163   // Apply default Lvalue conversions and convert the stride expression to
17164   // size_t.
17165   {
17166     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17167     if (StrideConv.isInvalid())
17168       return StrideConv;
17169 
17170     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17171     if (StrideConv.isInvalid())
17172       return StrideConv;
17173     StrideExpr = StrideConv.get();
17174     TheCall->setArg(2, StrideExpr);
17175   }
17176 
17177   // Check stride argument.
17178   if (MatrixTy) {
17179     if (Optional<llvm::APSInt> Value =
17180             StrideExpr->getIntegerConstantExpr(Context)) {
17181       uint64_t Stride = Value->getZExtValue();
17182       if (Stride < MatrixTy->getNumRows()) {
17183         Diag(StrideExpr->getBeginLoc(),
17184              diag::err_builtin_matrix_stride_too_small);
17185         ArgError = true;
17186       }
17187     }
17188   }
17189 
17190   if (ArgError)
17191     return ExprError();
17192 
17193   return CallResult;
17194 }
17195 
17196 /// \brief Enforce the bounds of a TCB
17197 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
17198 /// directly calls other functions in the same TCB as marked by the enforce_tcb
17199 /// and enforce_tcb_leaf attributes.
17200 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
17201                                const FunctionDecl *Callee) {
17202   const FunctionDecl *Caller = getCurFunctionDecl();
17203 
17204   // Calls to builtins are not enforced.
17205   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
17206       Callee->getBuiltinID() != 0)
17207     return;
17208 
17209   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17210   // all TCBs the callee is a part of.
17211   llvm::StringSet<> CalleeTCBs;
17212   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
17213            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17214   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
17215            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17216 
17217   // Go through the TCBs the caller is a part of and emit warnings if Caller
17218   // is in a TCB that the Callee is not.
17219   for_each(
17220       Caller->specific_attrs<EnforceTCBAttr>(),
17221       [&](const auto *A) {
17222         StringRef CallerTCB = A->getTCBName();
17223         if (CalleeTCBs.count(CallerTCB) == 0) {
17224           this->Diag(TheCall->getExprLoc(),
17225                      diag::warn_tcb_enforcement_violation) << Callee
17226                                                            << CallerTCB;
17227         }
17228       });
17229 }
17230