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,
503                              const TargetInfo &) override {
504 
505     const size_t FieldWidth = computeFieldWidth(FS);
506     const size_t Precision = computePrecision(FS);
507 
508     // The actual format.
509     switch (FS.getConversionSpecifier().getKind()) {
510     // Just a char.
511     case analyze_format_string::ConversionSpecifier::cArg:
512     case analyze_format_string::ConversionSpecifier::CArg:
513       Size += std::max(FieldWidth, (size_t)1);
514       break;
515     // Just an integer.
516     case analyze_format_string::ConversionSpecifier::dArg:
517     case analyze_format_string::ConversionSpecifier::DArg:
518     case analyze_format_string::ConversionSpecifier::iArg:
519     case analyze_format_string::ConversionSpecifier::oArg:
520     case analyze_format_string::ConversionSpecifier::OArg:
521     case analyze_format_string::ConversionSpecifier::uArg:
522     case analyze_format_string::ConversionSpecifier::UArg:
523     case analyze_format_string::ConversionSpecifier::xArg:
524     case analyze_format_string::ConversionSpecifier::XArg:
525       Size += std::max(FieldWidth, Precision);
526       break;
527 
528     // %g style conversion switches between %f or %e style dynamically.
529     // %f always takes less space, so default to it.
530     case analyze_format_string::ConversionSpecifier::gArg:
531     case analyze_format_string::ConversionSpecifier::GArg:
532 
533     // Floating point number in the form '[+]ddd.ddd'.
534     case analyze_format_string::ConversionSpecifier::fArg:
535     case analyze_format_string::ConversionSpecifier::FArg:
536       Size += std::max(FieldWidth, 1 /* integer part */ +
537                                        (Precision ? 1 + Precision
538                                                   : 0) /* period + decimal */);
539       break;
540 
541     // Floating point number in the form '[-]d.ddde[+-]dd'.
542     case analyze_format_string::ConversionSpecifier::eArg:
543     case analyze_format_string::ConversionSpecifier::EArg:
544       Size +=
545           std::max(FieldWidth,
546                    1 /* integer part */ +
547                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
548                        1 /* e or E letter */ + 2 /* exponent */);
549       break;
550 
551     // Floating point number in the form '[-]0xh.hhhhp±dd'.
552     case analyze_format_string::ConversionSpecifier::aArg:
553     case analyze_format_string::ConversionSpecifier::AArg:
554       Size +=
555           std::max(FieldWidth,
556                    2 /* 0x */ + 1 /* integer part */ +
557                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
558                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
559       break;
560 
561     // Just a string.
562     case analyze_format_string::ConversionSpecifier::sArg:
563     case analyze_format_string::ConversionSpecifier::SArg:
564       Size += FieldWidth;
565       break;
566 
567     // Just a pointer in the form '0xddd'.
568     case analyze_format_string::ConversionSpecifier::pArg:
569       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
570       break;
571 
572     // A plain percent.
573     case analyze_format_string::ConversionSpecifier::PercentArg:
574       Size += 1;
575       break;
576 
577     default:
578       break;
579     }
580 
581     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
582 
583     if (FS.hasAlternativeForm()) {
584       switch (FS.getConversionSpecifier().getKind()) {
585       default:
586         break;
587       // Force a leading '0'.
588       case analyze_format_string::ConversionSpecifier::oArg:
589         Size += 1;
590         break;
591       // Force a leading '0x'.
592       case analyze_format_string::ConversionSpecifier::xArg:
593       case analyze_format_string::ConversionSpecifier::XArg:
594         Size += 2;
595         break;
596       // Force a period '.' before decimal, even if precision is 0.
597       case analyze_format_string::ConversionSpecifier::aArg:
598       case analyze_format_string::ConversionSpecifier::AArg:
599       case analyze_format_string::ConversionSpecifier::eArg:
600       case analyze_format_string::ConversionSpecifier::EArg:
601       case analyze_format_string::ConversionSpecifier::fArg:
602       case analyze_format_string::ConversionSpecifier::FArg:
603       case analyze_format_string::ConversionSpecifier::gArg:
604       case analyze_format_string::ConversionSpecifier::GArg:
605         Size += (Precision ? 0 : 1);
606         break;
607       }
608     }
609     assert(SpecifierLen <= Size && "no underflow");
610     Size -= SpecifierLen;
611     return true;
612   }
613 
614   size_t getSizeLowerBound() const { return Size; }
615 
616 private:
617   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
618     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
619     size_t FieldWidth = 0;
620     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
621       FieldWidth = FW.getConstantAmount();
622     return FieldWidth;
623   }
624 
625   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
626     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
627     size_t Precision = 0;
628 
629     // See man 3 printf for default precision value based on the specifier.
630     switch (FW.getHowSpecified()) {
631     case analyze_format_string::OptionalAmount::NotSpecified:
632       switch (FS.getConversionSpecifier().getKind()) {
633       default:
634         break;
635       case analyze_format_string::ConversionSpecifier::dArg: // %d
636       case analyze_format_string::ConversionSpecifier::DArg: // %D
637       case analyze_format_string::ConversionSpecifier::iArg: // %i
638         Precision = 1;
639         break;
640       case analyze_format_string::ConversionSpecifier::oArg: // %d
641       case analyze_format_string::ConversionSpecifier::OArg: // %D
642       case analyze_format_string::ConversionSpecifier::uArg: // %d
643       case analyze_format_string::ConversionSpecifier::UArg: // %D
644       case analyze_format_string::ConversionSpecifier::xArg: // %d
645       case analyze_format_string::ConversionSpecifier::XArg: // %D
646         Precision = 1;
647         break;
648       case analyze_format_string::ConversionSpecifier::fArg: // %f
649       case analyze_format_string::ConversionSpecifier::FArg: // %F
650       case analyze_format_string::ConversionSpecifier::eArg: // %e
651       case analyze_format_string::ConversionSpecifier::EArg: // %E
652       case analyze_format_string::ConversionSpecifier::gArg: // %g
653       case analyze_format_string::ConversionSpecifier::GArg: // %G
654         Precision = 6;
655         break;
656       case analyze_format_string::ConversionSpecifier::pArg: // %d
657         Precision = 1;
658         break;
659       }
660       break;
661     case analyze_format_string::OptionalAmount::Constant:
662       Precision = FW.getConstantAmount();
663       break;
664     default:
665       break;
666     }
667     return Precision;
668   }
669 };
670 
671 } // namespace
672 
673 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
674                                                CallExpr *TheCall) {
675   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
676       isConstantEvaluated())
677     return;
678 
679   bool UseDABAttr = false;
680   const FunctionDecl *UseDecl = FD;
681 
682   const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
683   if (DABAttr) {
684     UseDecl = DABAttr->getFunction();
685     assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
686     UseDABAttr = true;
687   }
688 
689   unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
690 
691   if (!BuiltinID)
692     return;
693 
694   const TargetInfo &TI = getASTContext().getTargetInfo();
695   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
696 
697   auto TranslateIndex = [&](unsigned Index) -> Optional<unsigned> {
698     // If we refer to a diagnose_as_builtin attribute, we need to change the
699     // argument index to refer to the arguments of the called function. Unless
700     // the index is out of bounds, which presumably means it's a variadic
701     // function.
702     if (!UseDABAttr)
703       return Index;
704     unsigned DABIndices = DABAttr->argIndices_size();
705     unsigned NewIndex = Index < DABIndices
706                             ? DABAttr->argIndices_begin()[Index]
707                             : Index - DABIndices + FD->getNumParams();
708     if (NewIndex >= TheCall->getNumArgs())
709       return llvm::None;
710     return NewIndex;
711   };
712 
713   auto ComputeExplicitObjectSizeArgument =
714       [&](unsigned Index) -> Optional<llvm::APSInt> {
715     Optional<unsigned> IndexOptional = TranslateIndex(Index);
716     if (!IndexOptional)
717       return llvm::None;
718     unsigned NewIndex = IndexOptional.getValue();
719     Expr::EvalResult Result;
720     Expr *SizeArg = TheCall->getArg(NewIndex);
721     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
722       return llvm::None;
723     llvm::APSInt Integer = Result.Val.getInt();
724     Integer.setIsUnsigned(true);
725     return Integer;
726   };
727 
728   auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
729     // If the parameter has a pass_object_size attribute, then we should use its
730     // (potentially) more strict checking mode. Otherwise, conservatively assume
731     // type 0.
732     int BOSType = 0;
733     // This check can fail for variadic functions.
734     if (Index < FD->getNumParams()) {
735       if (const auto *POS =
736               FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
737         BOSType = POS->getType();
738     }
739 
740     Optional<unsigned> IndexOptional = TranslateIndex(Index);
741     if (!IndexOptional)
742       return llvm::None;
743     unsigned NewIndex = IndexOptional.getValue();
744 
745     const Expr *ObjArg = TheCall->getArg(NewIndex);
746     uint64_t Result;
747     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
748       return llvm::None;
749 
750     // Get the object size in the target's size_t width.
751     return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
752   };
753 
754   auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
755     Optional<unsigned> IndexOptional = TranslateIndex(Index);
756     if (!IndexOptional)
757       return llvm::None;
758     unsigned NewIndex = IndexOptional.getValue();
759 
760     const Expr *ObjArg = TheCall->getArg(NewIndex);
761     uint64_t Result;
762     if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
763       return llvm::None;
764     // Add 1 for null byte.
765     return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
766   };
767 
768   Optional<llvm::APSInt> SourceSize;
769   Optional<llvm::APSInt> DestinationSize;
770   unsigned DiagID = 0;
771   bool IsChkVariant = false;
772 
773   auto GetFunctionName = [&]() {
774     StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
775     // Skim off the details of whichever builtin was called to produce a better
776     // diagnostic, as it's unlikely that the user wrote the __builtin
777     // explicitly.
778     if (IsChkVariant) {
779       FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
780       FunctionName = FunctionName.drop_back(std::strlen("_chk"));
781     } else if (FunctionName.startswith("__builtin_")) {
782       FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
783     }
784     return FunctionName;
785   };
786 
787   switch (BuiltinID) {
788   default:
789     return;
790   case Builtin::BI__builtin_strcpy:
791   case Builtin::BIstrcpy: {
792     DiagID = diag::warn_fortify_strlen_overflow;
793     SourceSize = ComputeStrLenArgument(1);
794     DestinationSize = ComputeSizeArgument(0);
795     break;
796   }
797 
798   case Builtin::BI__builtin___strcpy_chk: {
799     DiagID = diag::warn_fortify_strlen_overflow;
800     SourceSize = ComputeStrLenArgument(1);
801     DestinationSize = ComputeExplicitObjectSizeArgument(2);
802     IsChkVariant = true;
803     break;
804   }
805 
806   case Builtin::BIscanf:
807   case Builtin::BIfscanf:
808   case Builtin::BIsscanf: {
809     unsigned FormatIndex = 1;
810     unsigned DataIndex = 2;
811     if (BuiltinID == Builtin::BIscanf) {
812       FormatIndex = 0;
813       DataIndex = 1;
814     }
815 
816     const auto *FormatExpr =
817         TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
818 
819     const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
820     if (!Format)
821       return;
822 
823     if (!Format->isAscii() && !Format->isUTF8())
824       return;
825 
826     auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
827                         unsigned SourceSize) {
828       DiagID = diag::warn_fortify_scanf_overflow;
829       unsigned Index = ArgIndex + DataIndex;
830       StringRef FunctionName = GetFunctionName();
831       DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
832                           PDiag(DiagID) << FunctionName << (Index + 1)
833                                         << DestSize << SourceSize);
834     };
835 
836     StringRef FormatStrRef = Format->getString();
837     auto ShiftedComputeSizeArgument = [&](unsigned Index) {
838       return ComputeSizeArgument(Index + DataIndex);
839     };
840     ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
841     const char *FormatBytes = FormatStrRef.data();
842     const ConstantArrayType *T =
843         Context.getAsConstantArrayType(Format->getType());
844     assert(T && "String literal not of constant array type!");
845     size_t TypeSize = T->getSize().getZExtValue();
846 
847     // In case there's a null byte somewhere.
848     size_t StrLen =
849         std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
850 
851     analyze_format_string::ParseScanfString(H, FormatBytes,
852                                             FormatBytes + StrLen, getLangOpts(),
853                                             Context.getTargetInfo());
854 
855     // Unlike the other cases, in this one we have already issued the diagnostic
856     // here, so no need to continue (because unlike the other cases, here the
857     // diagnostic refers to the argument number).
858     return;
859   }
860 
861   case Builtin::BIsprintf:
862   case Builtin::BI__builtin___sprintf_chk: {
863     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
864     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
865 
866     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
867 
868       if (!Format->isAscii() && !Format->isUTF8())
869         return;
870 
871       StringRef FormatStrRef = Format->getString();
872       EstimateSizeFormatHandler H(FormatStrRef);
873       const char *FormatBytes = FormatStrRef.data();
874       const ConstantArrayType *T =
875           Context.getAsConstantArrayType(Format->getType());
876       assert(T && "String literal not of constant array type!");
877       size_t TypeSize = T->getSize().getZExtValue();
878 
879       // In case there's a null byte somewhere.
880       size_t StrLen =
881           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
882       if (!analyze_format_string::ParsePrintfString(
883               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
884               Context.getTargetInfo(), false)) {
885         DiagID = diag::warn_fortify_source_format_overflow;
886         SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
887                          .extOrTrunc(SizeTypeWidth);
888         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
889           DestinationSize = ComputeExplicitObjectSizeArgument(2);
890           IsChkVariant = true;
891         } else {
892           DestinationSize = ComputeSizeArgument(0);
893         }
894         break;
895       }
896     }
897     return;
898   }
899   case Builtin::BI__builtin___memcpy_chk:
900   case Builtin::BI__builtin___memmove_chk:
901   case Builtin::BI__builtin___memset_chk:
902   case Builtin::BI__builtin___strlcat_chk:
903   case Builtin::BI__builtin___strlcpy_chk:
904   case Builtin::BI__builtin___strncat_chk:
905   case Builtin::BI__builtin___strncpy_chk:
906   case Builtin::BI__builtin___stpncpy_chk:
907   case Builtin::BI__builtin___memccpy_chk:
908   case Builtin::BI__builtin___mempcpy_chk: {
909     DiagID = diag::warn_builtin_chk_overflow;
910     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
911     DestinationSize =
912         ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
913     IsChkVariant = true;
914     break;
915   }
916 
917   case Builtin::BI__builtin___snprintf_chk:
918   case Builtin::BI__builtin___vsnprintf_chk: {
919     DiagID = diag::warn_builtin_chk_overflow;
920     SourceSize = ComputeExplicitObjectSizeArgument(1);
921     DestinationSize = ComputeExplicitObjectSizeArgument(3);
922     IsChkVariant = true;
923     break;
924   }
925 
926   case Builtin::BIstrncat:
927   case Builtin::BI__builtin_strncat:
928   case Builtin::BIstrncpy:
929   case Builtin::BI__builtin_strncpy:
930   case Builtin::BIstpncpy:
931   case Builtin::BI__builtin_stpncpy: {
932     // Whether these functions overflow depends on the runtime strlen of the
933     // string, not just the buffer size, so emitting the "always overflow"
934     // diagnostic isn't quite right. We should still diagnose passing a buffer
935     // size larger than the destination buffer though; this is a runtime abort
936     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
937     DiagID = diag::warn_fortify_source_size_mismatch;
938     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
939     DestinationSize = ComputeSizeArgument(0);
940     break;
941   }
942 
943   case Builtin::BImemcpy:
944   case Builtin::BI__builtin_memcpy:
945   case Builtin::BImemmove:
946   case Builtin::BI__builtin_memmove:
947   case Builtin::BImemset:
948   case Builtin::BI__builtin_memset:
949   case Builtin::BImempcpy:
950   case Builtin::BI__builtin_mempcpy: {
951     DiagID = diag::warn_fortify_source_overflow;
952     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
953     DestinationSize = ComputeSizeArgument(0);
954     break;
955   }
956   case Builtin::BIsnprintf:
957   case Builtin::BI__builtin_snprintf:
958   case Builtin::BIvsnprintf:
959   case Builtin::BI__builtin_vsnprintf: {
960     DiagID = diag::warn_fortify_source_size_mismatch;
961     SourceSize = ComputeExplicitObjectSizeArgument(1);
962     DestinationSize = ComputeSizeArgument(0);
963     break;
964   }
965   }
966 
967   if (!SourceSize || !DestinationSize ||
968       llvm::APSInt::compareValues(SourceSize.getValue(),
969                                   DestinationSize.getValue()) <= 0)
970     return;
971 
972   StringRef FunctionName = GetFunctionName();
973 
974   SmallString<16> DestinationStr;
975   SmallString<16> SourceStr;
976   DestinationSize->toString(DestinationStr, /*Radix=*/10);
977   SourceSize->toString(SourceStr, /*Radix=*/10);
978   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
979                       PDiag(DiagID)
980                           << FunctionName << DestinationStr << SourceStr);
981 }
982 
983 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
984                                      Scope::ScopeFlags NeededScopeFlags,
985                                      unsigned DiagID) {
986   // Scopes aren't available during instantiation. Fortunately, builtin
987   // functions cannot be template args so they cannot be formed through template
988   // instantiation. Therefore checking once during the parse is sufficient.
989   if (SemaRef.inTemplateInstantiation())
990     return false;
991 
992   Scope *S = SemaRef.getCurScope();
993   while (S && !S->isSEHExceptScope())
994     S = S->getParent();
995   if (!S || !(S->getFlags() & NeededScopeFlags)) {
996     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
997     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
998         << DRE->getDecl()->getIdentifier();
999     return true;
1000   }
1001 
1002   return false;
1003 }
1004 
1005 static inline bool isBlockPointer(Expr *Arg) {
1006   return Arg->getType()->isBlockPointerType();
1007 }
1008 
1009 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
1010 /// void*, which is a requirement of device side enqueue.
1011 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
1012   const BlockPointerType *BPT =
1013       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1014   ArrayRef<QualType> Params =
1015       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
1016   unsigned ArgCounter = 0;
1017   bool IllegalParams = false;
1018   // Iterate through the block parameters until either one is found that is not
1019   // a local void*, or the block is valid.
1020   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
1021        I != E; ++I, ++ArgCounter) {
1022     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
1023         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
1024             LangAS::opencl_local) {
1025       // Get the location of the error. If a block literal has been passed
1026       // (BlockExpr) then we can point straight to the offending argument,
1027       // else we just point to the variable reference.
1028       SourceLocation ErrorLoc;
1029       if (isa<BlockExpr>(BlockArg)) {
1030         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
1031         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
1032       } else if (isa<DeclRefExpr>(BlockArg)) {
1033         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
1034       }
1035       S.Diag(ErrorLoc,
1036              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
1037       IllegalParams = true;
1038     }
1039   }
1040 
1041   return IllegalParams;
1042 }
1043 
1044 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
1045   // OpenCL device can support extension but not the feature as extension
1046   // requires subgroup independent forward progress, but subgroup independent
1047   // forward progress is optional in OpenCL C 3.0 __opencl_c_subgroups feature.
1048   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts()) &&
1049       !S.getOpenCLOptions().isSupported("__opencl_c_subgroups",
1050                                         S.getLangOpts())) {
1051     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
1052         << 1 << Call->getDirectCallee()
1053         << "cl_khr_subgroups or __opencl_c_subgroups";
1054     return true;
1055   }
1056   return false;
1057 }
1058 
1059 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
1060   if (checkArgCount(S, TheCall, 2))
1061     return true;
1062 
1063   if (checkOpenCLSubgroupExt(S, TheCall))
1064     return true;
1065 
1066   // First argument is an ndrange_t type.
1067   Expr *NDRangeArg = TheCall->getArg(0);
1068   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1069     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1070         << TheCall->getDirectCallee() << "'ndrange_t'";
1071     return true;
1072   }
1073 
1074   Expr *BlockArg = TheCall->getArg(1);
1075   if (!isBlockPointer(BlockArg)) {
1076     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1077         << TheCall->getDirectCallee() << "block";
1078     return true;
1079   }
1080   return checkOpenCLBlockArgs(S, BlockArg);
1081 }
1082 
1083 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
1084 /// get_kernel_work_group_size
1085 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
1086 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
1087   if (checkArgCount(S, TheCall, 1))
1088     return true;
1089 
1090   Expr *BlockArg = TheCall->getArg(0);
1091   if (!isBlockPointer(BlockArg)) {
1092     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1093         << TheCall->getDirectCallee() << "block";
1094     return true;
1095   }
1096   return checkOpenCLBlockArgs(S, BlockArg);
1097 }
1098 
1099 /// Diagnose integer type and any valid implicit conversion to it.
1100 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
1101                                       const QualType &IntType);
1102 
1103 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
1104                                             unsigned Start, unsigned End) {
1105   bool IllegalParams = false;
1106   for (unsigned I = Start; I <= End; ++I)
1107     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
1108                                               S.Context.getSizeType());
1109   return IllegalParams;
1110 }
1111 
1112 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
1113 /// 'local void*' parameter of passed block.
1114 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
1115                                            Expr *BlockArg,
1116                                            unsigned NumNonVarArgs) {
1117   const BlockPointerType *BPT =
1118       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1119   unsigned NumBlockParams =
1120       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
1121   unsigned TotalNumArgs = TheCall->getNumArgs();
1122 
1123   // For each argument passed to the block, a corresponding uint needs to
1124   // be passed to describe the size of the local memory.
1125   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
1126     S.Diag(TheCall->getBeginLoc(),
1127            diag::err_opencl_enqueue_kernel_local_size_args);
1128     return true;
1129   }
1130 
1131   // Check that the sizes of the local memory are specified by integers.
1132   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
1133                                          TotalNumArgs - 1);
1134 }
1135 
1136 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
1137 /// overload formats specified in Table 6.13.17.1.
1138 /// int enqueue_kernel(queue_t queue,
1139 ///                    kernel_enqueue_flags_t flags,
1140 ///                    const ndrange_t ndrange,
1141 ///                    void (^block)(void))
1142 /// int enqueue_kernel(queue_t queue,
1143 ///                    kernel_enqueue_flags_t flags,
1144 ///                    const ndrange_t ndrange,
1145 ///                    uint num_events_in_wait_list,
1146 ///                    clk_event_t *event_wait_list,
1147 ///                    clk_event_t *event_ret,
1148 ///                    void (^block)(void))
1149 /// int enqueue_kernel(queue_t queue,
1150 ///                    kernel_enqueue_flags_t flags,
1151 ///                    const ndrange_t ndrange,
1152 ///                    void (^block)(local void*, ...),
1153 ///                    uint size0, ...)
1154 /// int enqueue_kernel(queue_t queue,
1155 ///                    kernel_enqueue_flags_t flags,
1156 ///                    const ndrange_t ndrange,
1157 ///                    uint num_events_in_wait_list,
1158 ///                    clk_event_t *event_wait_list,
1159 ///                    clk_event_t *event_ret,
1160 ///                    void (^block)(local void*, ...),
1161 ///                    uint size0, ...)
1162 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
1163   unsigned NumArgs = TheCall->getNumArgs();
1164 
1165   if (NumArgs < 4) {
1166     S.Diag(TheCall->getBeginLoc(),
1167            diag::err_typecheck_call_too_few_args_at_least)
1168         << 0 << 4 << NumArgs;
1169     return true;
1170   }
1171 
1172   Expr *Arg0 = TheCall->getArg(0);
1173   Expr *Arg1 = TheCall->getArg(1);
1174   Expr *Arg2 = TheCall->getArg(2);
1175   Expr *Arg3 = TheCall->getArg(3);
1176 
1177   // First argument always needs to be a queue_t type.
1178   if (!Arg0->getType()->isQueueT()) {
1179     S.Diag(TheCall->getArg(0)->getBeginLoc(),
1180            diag::err_opencl_builtin_expected_type)
1181         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
1182     return true;
1183   }
1184 
1185   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
1186   if (!Arg1->getType()->isIntegerType()) {
1187     S.Diag(TheCall->getArg(1)->getBeginLoc(),
1188            diag::err_opencl_builtin_expected_type)
1189         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
1190     return true;
1191   }
1192 
1193   // Third argument is always an ndrange_t type.
1194   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1195     S.Diag(TheCall->getArg(2)->getBeginLoc(),
1196            diag::err_opencl_builtin_expected_type)
1197         << TheCall->getDirectCallee() << "'ndrange_t'";
1198     return true;
1199   }
1200 
1201   // With four arguments, there is only one form that the function could be
1202   // called in: no events and no variable arguments.
1203   if (NumArgs == 4) {
1204     // check that the last argument is the right block type.
1205     if (!isBlockPointer(Arg3)) {
1206       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1207           << TheCall->getDirectCallee() << "block";
1208       return true;
1209     }
1210     // we have a block type, check the prototype
1211     const BlockPointerType *BPT =
1212         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1213     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1214       S.Diag(Arg3->getBeginLoc(),
1215              diag::err_opencl_enqueue_kernel_blocks_no_args);
1216       return true;
1217     }
1218     return false;
1219   }
1220   // we can have block + varargs.
1221   if (isBlockPointer(Arg3))
1222     return (checkOpenCLBlockArgs(S, Arg3) ||
1223             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1224   // last two cases with either exactly 7 args or 7 args and varargs.
1225   if (NumArgs >= 7) {
1226     // check common block argument.
1227     Expr *Arg6 = TheCall->getArg(6);
1228     if (!isBlockPointer(Arg6)) {
1229       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1230           << TheCall->getDirectCallee() << "block";
1231       return true;
1232     }
1233     if (checkOpenCLBlockArgs(S, Arg6))
1234       return true;
1235 
1236     // Forth argument has to be any integer type.
1237     if (!Arg3->getType()->isIntegerType()) {
1238       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1239              diag::err_opencl_builtin_expected_type)
1240           << TheCall->getDirectCallee() << "integer";
1241       return true;
1242     }
1243     // check remaining common arguments.
1244     Expr *Arg4 = TheCall->getArg(4);
1245     Expr *Arg5 = TheCall->getArg(5);
1246 
1247     // Fifth argument is always passed as a pointer to clk_event_t.
1248     if (!Arg4->isNullPointerConstant(S.Context,
1249                                      Expr::NPC_ValueDependentIsNotNull) &&
1250         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1251       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1252              diag::err_opencl_builtin_expected_type)
1253           << TheCall->getDirectCallee()
1254           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1255       return true;
1256     }
1257 
1258     // Sixth argument is always passed as a pointer to clk_event_t.
1259     if (!Arg5->isNullPointerConstant(S.Context,
1260                                      Expr::NPC_ValueDependentIsNotNull) &&
1261         !(Arg5->getType()->isPointerType() &&
1262           Arg5->getType()->getPointeeType()->isClkEventT())) {
1263       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1264              diag::err_opencl_builtin_expected_type)
1265           << TheCall->getDirectCallee()
1266           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1267       return true;
1268     }
1269 
1270     if (NumArgs == 7)
1271       return false;
1272 
1273     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1274   }
1275 
1276   // None of the specific case has been detected, give generic error
1277   S.Diag(TheCall->getBeginLoc(),
1278          diag::err_opencl_enqueue_kernel_incorrect_args);
1279   return true;
1280 }
1281 
1282 /// Returns OpenCL access qual.
1283 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1284     return D->getAttr<OpenCLAccessAttr>();
1285 }
1286 
1287 /// Returns true if pipe element type is different from the pointer.
1288 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1289   const Expr *Arg0 = Call->getArg(0);
1290   // First argument type should always be pipe.
1291   if (!Arg0->getType()->isPipeType()) {
1292     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1293         << Call->getDirectCallee() << Arg0->getSourceRange();
1294     return true;
1295   }
1296   OpenCLAccessAttr *AccessQual =
1297       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1298   // Validates the access qualifier is compatible with the call.
1299   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1300   // read_only and write_only, and assumed to be read_only if no qualifier is
1301   // specified.
1302   switch (Call->getDirectCallee()->getBuiltinID()) {
1303   case Builtin::BIread_pipe:
1304   case Builtin::BIreserve_read_pipe:
1305   case Builtin::BIcommit_read_pipe:
1306   case Builtin::BIwork_group_reserve_read_pipe:
1307   case Builtin::BIsub_group_reserve_read_pipe:
1308   case Builtin::BIwork_group_commit_read_pipe:
1309   case Builtin::BIsub_group_commit_read_pipe:
1310     if (!(!AccessQual || AccessQual->isReadOnly())) {
1311       S.Diag(Arg0->getBeginLoc(),
1312              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1313           << "read_only" << Arg0->getSourceRange();
1314       return true;
1315     }
1316     break;
1317   case Builtin::BIwrite_pipe:
1318   case Builtin::BIreserve_write_pipe:
1319   case Builtin::BIcommit_write_pipe:
1320   case Builtin::BIwork_group_reserve_write_pipe:
1321   case Builtin::BIsub_group_reserve_write_pipe:
1322   case Builtin::BIwork_group_commit_write_pipe:
1323   case Builtin::BIsub_group_commit_write_pipe:
1324     if (!(AccessQual && AccessQual->isWriteOnly())) {
1325       S.Diag(Arg0->getBeginLoc(),
1326              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1327           << "write_only" << Arg0->getSourceRange();
1328       return true;
1329     }
1330     break;
1331   default:
1332     break;
1333   }
1334   return false;
1335 }
1336 
1337 /// Returns true if pipe element type is different from the pointer.
1338 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1339   const Expr *Arg0 = Call->getArg(0);
1340   const Expr *ArgIdx = Call->getArg(Idx);
1341   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1342   const QualType EltTy = PipeTy->getElementType();
1343   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1344   // The Idx argument should be a pointer and the type of the pointer and
1345   // the type of pipe element should also be the same.
1346   if (!ArgTy ||
1347       !S.Context.hasSameType(
1348           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1349     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1350         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1351         << ArgIdx->getType() << ArgIdx->getSourceRange();
1352     return true;
1353   }
1354   return false;
1355 }
1356 
1357 // Performs semantic analysis for the read/write_pipe call.
1358 // \param S Reference to the semantic analyzer.
1359 // \param Call A pointer to the builtin call.
1360 // \return True if a semantic error has been found, false otherwise.
1361 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1362   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1363   // functions have two forms.
1364   switch (Call->getNumArgs()) {
1365   case 2:
1366     if (checkOpenCLPipeArg(S, Call))
1367       return true;
1368     // The call with 2 arguments should be
1369     // read/write_pipe(pipe T, T*).
1370     // Check packet type T.
1371     if (checkOpenCLPipePacketType(S, Call, 1))
1372       return true;
1373     break;
1374 
1375   case 4: {
1376     if (checkOpenCLPipeArg(S, Call))
1377       return true;
1378     // The call with 4 arguments should be
1379     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1380     // Check reserve_id_t.
1381     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1382       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1383           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1384           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1385       return true;
1386     }
1387 
1388     // Check the index.
1389     const Expr *Arg2 = Call->getArg(2);
1390     if (!Arg2->getType()->isIntegerType() &&
1391         !Arg2->getType()->isUnsignedIntegerType()) {
1392       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1393           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1394           << Arg2->getType() << Arg2->getSourceRange();
1395       return true;
1396     }
1397 
1398     // Check packet type T.
1399     if (checkOpenCLPipePacketType(S, Call, 3))
1400       return true;
1401   } break;
1402   default:
1403     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1404         << Call->getDirectCallee() << Call->getSourceRange();
1405     return true;
1406   }
1407 
1408   return false;
1409 }
1410 
1411 // Performs a semantic analysis on the {work_group_/sub_group_
1412 //        /_}reserve_{read/write}_pipe
1413 // \param S Reference to the semantic analyzer.
1414 // \param Call The call to the builtin function to be analyzed.
1415 // \return True if a semantic error was found, false otherwise.
1416 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1417   if (checkArgCount(S, Call, 2))
1418     return true;
1419 
1420   if (checkOpenCLPipeArg(S, Call))
1421     return true;
1422 
1423   // Check the reserve size.
1424   if (!Call->getArg(1)->getType()->isIntegerType() &&
1425       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1426     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1427         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1428         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1429     return true;
1430   }
1431 
1432   // Since return type of reserve_read/write_pipe built-in function is
1433   // reserve_id_t, which is not defined in the builtin def file , we used int
1434   // as return type and need to override the return type of these functions.
1435   Call->setType(S.Context.OCLReserveIDTy);
1436 
1437   return false;
1438 }
1439 
1440 // Performs a semantic analysis on {work_group_/sub_group_
1441 //        /_}commit_{read/write}_pipe
1442 // \param S Reference to the semantic analyzer.
1443 // \param Call The call to the builtin function to be analyzed.
1444 // \return True if a semantic error was found, false otherwise.
1445 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1446   if (checkArgCount(S, Call, 2))
1447     return true;
1448 
1449   if (checkOpenCLPipeArg(S, Call))
1450     return true;
1451 
1452   // Check reserve_id_t.
1453   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1454     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1455         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1456         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1457     return true;
1458   }
1459 
1460   return false;
1461 }
1462 
1463 // Performs a semantic analysis on the call to built-in Pipe
1464 //        Query Functions.
1465 // \param S Reference to the semantic analyzer.
1466 // \param Call The call to the builtin function to be analyzed.
1467 // \return True if a semantic error was found, false otherwise.
1468 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1469   if (checkArgCount(S, Call, 1))
1470     return true;
1471 
1472   if (!Call->getArg(0)->getType()->isPipeType()) {
1473     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1474         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1475     return true;
1476   }
1477 
1478   return false;
1479 }
1480 
1481 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1482 // Performs semantic analysis for the to_global/local/private call.
1483 // \param S Reference to the semantic analyzer.
1484 // \param BuiltinID ID of the builtin function.
1485 // \param Call A pointer to the builtin call.
1486 // \return True if a semantic error has been found, false otherwise.
1487 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1488                                     CallExpr *Call) {
1489   if (checkArgCount(S, Call, 1))
1490     return true;
1491 
1492   auto RT = Call->getArg(0)->getType();
1493   if (!RT->isPointerType() || RT->getPointeeType()
1494       .getAddressSpace() == LangAS::opencl_constant) {
1495     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1496         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1497     return true;
1498   }
1499 
1500   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1501     S.Diag(Call->getArg(0)->getBeginLoc(),
1502            diag::warn_opencl_generic_address_space_arg)
1503         << Call->getDirectCallee()->getNameInfo().getAsString()
1504         << Call->getArg(0)->getSourceRange();
1505   }
1506 
1507   RT = RT->getPointeeType();
1508   auto Qual = RT.getQualifiers();
1509   switch (BuiltinID) {
1510   case Builtin::BIto_global:
1511     Qual.setAddressSpace(LangAS::opencl_global);
1512     break;
1513   case Builtin::BIto_local:
1514     Qual.setAddressSpace(LangAS::opencl_local);
1515     break;
1516   case Builtin::BIto_private:
1517     Qual.setAddressSpace(LangAS::opencl_private);
1518     break;
1519   default:
1520     llvm_unreachable("Invalid builtin function");
1521   }
1522   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1523       RT.getUnqualifiedType(), Qual)));
1524 
1525   return false;
1526 }
1527 
1528 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1529   if (checkArgCount(S, TheCall, 1))
1530     return ExprError();
1531 
1532   // Compute __builtin_launder's parameter type from the argument.
1533   // The parameter type is:
1534   //  * The type of the argument if it's not an array or function type,
1535   //  Otherwise,
1536   //  * The decayed argument type.
1537   QualType ParamTy = [&]() {
1538     QualType ArgTy = TheCall->getArg(0)->getType();
1539     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1540       return S.Context.getPointerType(Ty->getElementType());
1541     if (ArgTy->isFunctionType()) {
1542       return S.Context.getPointerType(ArgTy);
1543     }
1544     return ArgTy;
1545   }();
1546 
1547   TheCall->setType(ParamTy);
1548 
1549   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1550     if (!ParamTy->isPointerType())
1551       return 0;
1552     if (ParamTy->isFunctionPointerType())
1553       return 1;
1554     if (ParamTy->isVoidPointerType())
1555       return 2;
1556     return llvm::Optional<unsigned>{};
1557   }();
1558   if (DiagSelect.hasValue()) {
1559     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1560         << DiagSelect.getValue() << TheCall->getSourceRange();
1561     return ExprError();
1562   }
1563 
1564   // We either have an incomplete class type, or we have a class template
1565   // whose instantiation has not been forced. Example:
1566   //
1567   //   template <class T> struct Foo { T value; };
1568   //   Foo<int> *p = nullptr;
1569   //   auto *d = __builtin_launder(p);
1570   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1571                             diag::err_incomplete_type))
1572     return ExprError();
1573 
1574   assert(ParamTy->getPointeeType()->isObjectType() &&
1575          "Unhandled non-object pointer case");
1576 
1577   InitializedEntity Entity =
1578       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1579   ExprResult Arg =
1580       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1581   if (Arg.isInvalid())
1582     return ExprError();
1583   TheCall->setArg(0, Arg.get());
1584 
1585   return TheCall;
1586 }
1587 
1588 // Emit an error and return true if the current object format type is in the
1589 // list of unsupported types.
1590 static bool CheckBuiltinTargetNotInUnsupported(
1591     Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1592     ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
1593   llvm::Triple::ObjectFormatType CurObjFormat =
1594       S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
1595   if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
1596     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1597         << TheCall->getSourceRange();
1598     return true;
1599   }
1600   return false;
1601 }
1602 
1603 // Emit an error and return true if the current architecture is not in the list
1604 // of supported architectures.
1605 static bool
1606 CheckBuiltinTargetInSupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1607                               ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1608   llvm::Triple::ArchType CurArch =
1609       S.getASTContext().getTargetInfo().getTriple().getArch();
1610   if (llvm::is_contained(SupportedArchs, CurArch))
1611     return false;
1612   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1613       << TheCall->getSourceRange();
1614   return true;
1615 }
1616 
1617 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1618                                  SourceLocation CallSiteLoc);
1619 
1620 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1621                                       CallExpr *TheCall) {
1622   switch (TI.getTriple().getArch()) {
1623   default:
1624     // Some builtins don't require additional checking, so just consider these
1625     // acceptable.
1626     return false;
1627   case llvm::Triple::arm:
1628   case llvm::Triple::armeb:
1629   case llvm::Triple::thumb:
1630   case llvm::Triple::thumbeb:
1631     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1632   case llvm::Triple::aarch64:
1633   case llvm::Triple::aarch64_32:
1634   case llvm::Triple::aarch64_be:
1635     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1636   case llvm::Triple::bpfeb:
1637   case llvm::Triple::bpfel:
1638     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1639   case llvm::Triple::hexagon:
1640     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1641   case llvm::Triple::mips:
1642   case llvm::Triple::mipsel:
1643   case llvm::Triple::mips64:
1644   case llvm::Triple::mips64el:
1645     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1646   case llvm::Triple::systemz:
1647     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1648   case llvm::Triple::x86:
1649   case llvm::Triple::x86_64:
1650     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1651   case llvm::Triple::ppc:
1652   case llvm::Triple::ppcle:
1653   case llvm::Triple::ppc64:
1654   case llvm::Triple::ppc64le:
1655     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1656   case llvm::Triple::amdgcn:
1657     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1658   case llvm::Triple::riscv32:
1659   case llvm::Triple::riscv64:
1660     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1661   }
1662 }
1663 
1664 ExprResult
1665 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1666                                CallExpr *TheCall) {
1667   ExprResult TheCallResult(TheCall);
1668 
1669   // Find out if any arguments are required to be integer constant expressions.
1670   unsigned ICEArguments = 0;
1671   ASTContext::GetBuiltinTypeError Error;
1672   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1673   if (Error != ASTContext::GE_None)
1674     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1675 
1676   // If any arguments are required to be ICE's, check and diagnose.
1677   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1678     // Skip arguments not required to be ICE's.
1679     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1680 
1681     llvm::APSInt Result;
1682     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1683       return true;
1684     ICEArguments &= ~(1 << ArgNo);
1685   }
1686 
1687   switch (BuiltinID) {
1688   case Builtin::BI__builtin___CFStringMakeConstantString:
1689     // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
1690     // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
1691     if (CheckBuiltinTargetNotInUnsupported(
1692             *this, BuiltinID, TheCall,
1693             {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
1694       return ExprError();
1695     assert(TheCall->getNumArgs() == 1 &&
1696            "Wrong # arguments to builtin CFStringMakeConstantString");
1697     if (CheckObjCString(TheCall->getArg(0)))
1698       return ExprError();
1699     break;
1700   case Builtin::BI__builtin_ms_va_start:
1701   case Builtin::BI__builtin_stdarg_start:
1702   case Builtin::BI__builtin_va_start:
1703     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1704       return ExprError();
1705     break;
1706   case Builtin::BI__va_start: {
1707     switch (Context.getTargetInfo().getTriple().getArch()) {
1708     case llvm::Triple::aarch64:
1709     case llvm::Triple::arm:
1710     case llvm::Triple::thumb:
1711       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1712         return ExprError();
1713       break;
1714     default:
1715       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1716         return ExprError();
1717       break;
1718     }
1719     break;
1720   }
1721 
1722   // The acquire, release, and no fence variants are ARM and AArch64 only.
1723   case Builtin::BI_interlockedbittestandset_acq:
1724   case Builtin::BI_interlockedbittestandset_rel:
1725   case Builtin::BI_interlockedbittestandset_nf:
1726   case Builtin::BI_interlockedbittestandreset_acq:
1727   case Builtin::BI_interlockedbittestandreset_rel:
1728   case Builtin::BI_interlockedbittestandreset_nf:
1729     if (CheckBuiltinTargetInSupported(
1730             *this, BuiltinID, TheCall,
1731             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1732       return ExprError();
1733     break;
1734 
1735   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1736   case Builtin::BI_bittest64:
1737   case Builtin::BI_bittestandcomplement64:
1738   case Builtin::BI_bittestandreset64:
1739   case Builtin::BI_bittestandset64:
1740   case Builtin::BI_interlockedbittestandreset64:
1741   case Builtin::BI_interlockedbittestandset64:
1742     if (CheckBuiltinTargetInSupported(*this, BuiltinID, TheCall,
1743                                       {llvm::Triple::x86_64, llvm::Triple::arm,
1744                                        llvm::Triple::thumb,
1745                                        llvm::Triple::aarch64}))
1746       return ExprError();
1747     break;
1748 
1749   case Builtin::BI__builtin_isgreater:
1750   case Builtin::BI__builtin_isgreaterequal:
1751   case Builtin::BI__builtin_isless:
1752   case Builtin::BI__builtin_islessequal:
1753   case Builtin::BI__builtin_islessgreater:
1754   case Builtin::BI__builtin_isunordered:
1755     if (SemaBuiltinUnorderedCompare(TheCall))
1756       return ExprError();
1757     break;
1758   case Builtin::BI__builtin_fpclassify:
1759     if (SemaBuiltinFPClassification(TheCall, 6))
1760       return ExprError();
1761     break;
1762   case Builtin::BI__builtin_isfinite:
1763   case Builtin::BI__builtin_isinf:
1764   case Builtin::BI__builtin_isinf_sign:
1765   case Builtin::BI__builtin_isnan:
1766   case Builtin::BI__builtin_isnormal:
1767   case Builtin::BI__builtin_signbit:
1768   case Builtin::BI__builtin_signbitf:
1769   case Builtin::BI__builtin_signbitl:
1770     if (SemaBuiltinFPClassification(TheCall, 1))
1771       return ExprError();
1772     break;
1773   case Builtin::BI__builtin_shufflevector:
1774     return SemaBuiltinShuffleVector(TheCall);
1775     // TheCall will be freed by the smart pointer here, but that's fine, since
1776     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1777   case Builtin::BI__builtin_prefetch:
1778     if (SemaBuiltinPrefetch(TheCall))
1779       return ExprError();
1780     break;
1781   case Builtin::BI__builtin_alloca_with_align:
1782   case Builtin::BI__builtin_alloca_with_align_uninitialized:
1783     if (SemaBuiltinAllocaWithAlign(TheCall))
1784       return ExprError();
1785     LLVM_FALLTHROUGH;
1786   case Builtin::BI__builtin_alloca:
1787   case Builtin::BI__builtin_alloca_uninitialized:
1788     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1789         << TheCall->getDirectCallee();
1790     break;
1791   case Builtin::BI__arithmetic_fence:
1792     if (SemaBuiltinArithmeticFence(TheCall))
1793       return ExprError();
1794     break;
1795   case Builtin::BI__assume:
1796   case Builtin::BI__builtin_assume:
1797     if (SemaBuiltinAssume(TheCall))
1798       return ExprError();
1799     break;
1800   case Builtin::BI__builtin_assume_aligned:
1801     if (SemaBuiltinAssumeAligned(TheCall))
1802       return ExprError();
1803     break;
1804   case Builtin::BI__builtin_dynamic_object_size:
1805   case Builtin::BI__builtin_object_size:
1806     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1807       return ExprError();
1808     break;
1809   case Builtin::BI__builtin_longjmp:
1810     if (SemaBuiltinLongjmp(TheCall))
1811       return ExprError();
1812     break;
1813   case Builtin::BI__builtin_setjmp:
1814     if (SemaBuiltinSetjmp(TheCall))
1815       return ExprError();
1816     break;
1817   case Builtin::BI__builtin_classify_type:
1818     if (checkArgCount(*this, TheCall, 1)) return true;
1819     TheCall->setType(Context.IntTy);
1820     break;
1821   case Builtin::BI__builtin_complex:
1822     if (SemaBuiltinComplex(TheCall))
1823       return ExprError();
1824     break;
1825   case Builtin::BI__builtin_constant_p: {
1826     if (checkArgCount(*this, TheCall, 1)) return true;
1827     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1828     if (Arg.isInvalid()) return true;
1829     TheCall->setArg(0, Arg.get());
1830     TheCall->setType(Context.IntTy);
1831     break;
1832   }
1833   case Builtin::BI__builtin_launder:
1834     return SemaBuiltinLaunder(*this, TheCall);
1835   case Builtin::BI__sync_fetch_and_add:
1836   case Builtin::BI__sync_fetch_and_add_1:
1837   case Builtin::BI__sync_fetch_and_add_2:
1838   case Builtin::BI__sync_fetch_and_add_4:
1839   case Builtin::BI__sync_fetch_and_add_8:
1840   case Builtin::BI__sync_fetch_and_add_16:
1841   case Builtin::BI__sync_fetch_and_sub:
1842   case Builtin::BI__sync_fetch_and_sub_1:
1843   case Builtin::BI__sync_fetch_and_sub_2:
1844   case Builtin::BI__sync_fetch_and_sub_4:
1845   case Builtin::BI__sync_fetch_and_sub_8:
1846   case Builtin::BI__sync_fetch_and_sub_16:
1847   case Builtin::BI__sync_fetch_and_or:
1848   case Builtin::BI__sync_fetch_and_or_1:
1849   case Builtin::BI__sync_fetch_and_or_2:
1850   case Builtin::BI__sync_fetch_and_or_4:
1851   case Builtin::BI__sync_fetch_and_or_8:
1852   case Builtin::BI__sync_fetch_and_or_16:
1853   case Builtin::BI__sync_fetch_and_and:
1854   case Builtin::BI__sync_fetch_and_and_1:
1855   case Builtin::BI__sync_fetch_and_and_2:
1856   case Builtin::BI__sync_fetch_and_and_4:
1857   case Builtin::BI__sync_fetch_and_and_8:
1858   case Builtin::BI__sync_fetch_and_and_16:
1859   case Builtin::BI__sync_fetch_and_xor:
1860   case Builtin::BI__sync_fetch_and_xor_1:
1861   case Builtin::BI__sync_fetch_and_xor_2:
1862   case Builtin::BI__sync_fetch_and_xor_4:
1863   case Builtin::BI__sync_fetch_and_xor_8:
1864   case Builtin::BI__sync_fetch_and_xor_16:
1865   case Builtin::BI__sync_fetch_and_nand:
1866   case Builtin::BI__sync_fetch_and_nand_1:
1867   case Builtin::BI__sync_fetch_and_nand_2:
1868   case Builtin::BI__sync_fetch_and_nand_4:
1869   case Builtin::BI__sync_fetch_and_nand_8:
1870   case Builtin::BI__sync_fetch_and_nand_16:
1871   case Builtin::BI__sync_add_and_fetch:
1872   case Builtin::BI__sync_add_and_fetch_1:
1873   case Builtin::BI__sync_add_and_fetch_2:
1874   case Builtin::BI__sync_add_and_fetch_4:
1875   case Builtin::BI__sync_add_and_fetch_8:
1876   case Builtin::BI__sync_add_and_fetch_16:
1877   case Builtin::BI__sync_sub_and_fetch:
1878   case Builtin::BI__sync_sub_and_fetch_1:
1879   case Builtin::BI__sync_sub_and_fetch_2:
1880   case Builtin::BI__sync_sub_and_fetch_4:
1881   case Builtin::BI__sync_sub_and_fetch_8:
1882   case Builtin::BI__sync_sub_and_fetch_16:
1883   case Builtin::BI__sync_and_and_fetch:
1884   case Builtin::BI__sync_and_and_fetch_1:
1885   case Builtin::BI__sync_and_and_fetch_2:
1886   case Builtin::BI__sync_and_and_fetch_4:
1887   case Builtin::BI__sync_and_and_fetch_8:
1888   case Builtin::BI__sync_and_and_fetch_16:
1889   case Builtin::BI__sync_or_and_fetch:
1890   case Builtin::BI__sync_or_and_fetch_1:
1891   case Builtin::BI__sync_or_and_fetch_2:
1892   case Builtin::BI__sync_or_and_fetch_4:
1893   case Builtin::BI__sync_or_and_fetch_8:
1894   case Builtin::BI__sync_or_and_fetch_16:
1895   case Builtin::BI__sync_xor_and_fetch:
1896   case Builtin::BI__sync_xor_and_fetch_1:
1897   case Builtin::BI__sync_xor_and_fetch_2:
1898   case Builtin::BI__sync_xor_and_fetch_4:
1899   case Builtin::BI__sync_xor_and_fetch_8:
1900   case Builtin::BI__sync_xor_and_fetch_16:
1901   case Builtin::BI__sync_nand_and_fetch:
1902   case Builtin::BI__sync_nand_and_fetch_1:
1903   case Builtin::BI__sync_nand_and_fetch_2:
1904   case Builtin::BI__sync_nand_and_fetch_4:
1905   case Builtin::BI__sync_nand_and_fetch_8:
1906   case Builtin::BI__sync_nand_and_fetch_16:
1907   case Builtin::BI__sync_val_compare_and_swap:
1908   case Builtin::BI__sync_val_compare_and_swap_1:
1909   case Builtin::BI__sync_val_compare_and_swap_2:
1910   case Builtin::BI__sync_val_compare_and_swap_4:
1911   case Builtin::BI__sync_val_compare_and_swap_8:
1912   case Builtin::BI__sync_val_compare_and_swap_16:
1913   case Builtin::BI__sync_bool_compare_and_swap:
1914   case Builtin::BI__sync_bool_compare_and_swap_1:
1915   case Builtin::BI__sync_bool_compare_and_swap_2:
1916   case Builtin::BI__sync_bool_compare_and_swap_4:
1917   case Builtin::BI__sync_bool_compare_and_swap_8:
1918   case Builtin::BI__sync_bool_compare_and_swap_16:
1919   case Builtin::BI__sync_lock_test_and_set:
1920   case Builtin::BI__sync_lock_test_and_set_1:
1921   case Builtin::BI__sync_lock_test_and_set_2:
1922   case Builtin::BI__sync_lock_test_and_set_4:
1923   case Builtin::BI__sync_lock_test_and_set_8:
1924   case Builtin::BI__sync_lock_test_and_set_16:
1925   case Builtin::BI__sync_lock_release:
1926   case Builtin::BI__sync_lock_release_1:
1927   case Builtin::BI__sync_lock_release_2:
1928   case Builtin::BI__sync_lock_release_4:
1929   case Builtin::BI__sync_lock_release_8:
1930   case Builtin::BI__sync_lock_release_16:
1931   case Builtin::BI__sync_swap:
1932   case Builtin::BI__sync_swap_1:
1933   case Builtin::BI__sync_swap_2:
1934   case Builtin::BI__sync_swap_4:
1935   case Builtin::BI__sync_swap_8:
1936   case Builtin::BI__sync_swap_16:
1937     return SemaBuiltinAtomicOverloaded(TheCallResult);
1938   case Builtin::BI__sync_synchronize:
1939     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1940         << TheCall->getCallee()->getSourceRange();
1941     break;
1942   case Builtin::BI__builtin_nontemporal_load:
1943   case Builtin::BI__builtin_nontemporal_store:
1944     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1945   case Builtin::BI__builtin_memcpy_inline: {
1946     clang::Expr *SizeOp = TheCall->getArg(2);
1947     // We warn about copying to or from `nullptr` pointers when `size` is
1948     // greater than 0. When `size` is value dependent we cannot evaluate its
1949     // value so we bail out.
1950     if (SizeOp->isValueDependent())
1951       break;
1952     if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
1953       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1954       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1955     }
1956     break;
1957   }
1958 #define BUILTIN(ID, TYPE, ATTRS)
1959 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1960   case Builtin::BI##ID: \
1961     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1962 #include "clang/Basic/Builtins.def"
1963   case Builtin::BI__annotation:
1964     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1965       return ExprError();
1966     break;
1967   case Builtin::BI__builtin_annotation:
1968     if (SemaBuiltinAnnotation(*this, TheCall))
1969       return ExprError();
1970     break;
1971   case Builtin::BI__builtin_addressof:
1972     if (SemaBuiltinAddressof(*this, TheCall))
1973       return ExprError();
1974     break;
1975   case Builtin::BI__builtin_function_start:
1976     if (SemaBuiltinFunctionStart(*this, TheCall))
1977       return ExprError();
1978     break;
1979   case Builtin::BI__builtin_is_aligned:
1980   case Builtin::BI__builtin_align_up:
1981   case Builtin::BI__builtin_align_down:
1982     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1983       return ExprError();
1984     break;
1985   case Builtin::BI__builtin_add_overflow:
1986   case Builtin::BI__builtin_sub_overflow:
1987   case Builtin::BI__builtin_mul_overflow:
1988     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1989       return ExprError();
1990     break;
1991   case Builtin::BI__builtin_operator_new:
1992   case Builtin::BI__builtin_operator_delete: {
1993     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1994     ExprResult Res =
1995         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1996     if (Res.isInvalid())
1997       CorrectDelayedTyposInExpr(TheCallResult.get());
1998     return Res;
1999   }
2000   case Builtin::BI__builtin_dump_struct: {
2001     // We first want to ensure we are called with 2 arguments
2002     if (checkArgCount(*this, TheCall, 2))
2003       return ExprError();
2004     // Ensure that the first argument is of type 'struct XX *'
2005     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
2006     const QualType PtrArgType = PtrArg->getType();
2007     if (!PtrArgType->isPointerType() ||
2008         !PtrArgType->getPointeeType()->isRecordType()) {
2009       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2010           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
2011           << "structure pointer";
2012       return ExprError();
2013     }
2014 
2015     // Ensure that the second argument is of type 'FunctionType'
2016     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
2017     const QualType FnPtrArgType = FnPtrArg->getType();
2018     if (!FnPtrArgType->isPointerType()) {
2019       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2020           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
2021           << FnPtrArgType << "'int (*)(const char *, ...)'";
2022       return ExprError();
2023     }
2024 
2025     const auto *FuncType =
2026         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
2027 
2028     if (!FuncType) {
2029       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2030           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
2031           << FnPtrArgType << "'int (*)(const char *, ...)'";
2032       return ExprError();
2033     }
2034 
2035     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
2036       if (!FT->getNumParams()) {
2037         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2038             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
2039             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
2040         return ExprError();
2041       }
2042       QualType PT = FT->getParamType(0);
2043       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
2044           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
2045           !PT->getPointeeType().isConstQualified()) {
2046         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2047             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
2048             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
2049         return ExprError();
2050       }
2051     }
2052 
2053     TheCall->setType(Context.IntTy);
2054     break;
2055   }
2056   case Builtin::BI__builtin_expect_with_probability: {
2057     // We first want to ensure we are called with 3 arguments
2058     if (checkArgCount(*this, TheCall, 3))
2059       return ExprError();
2060     // then check probability is constant float in range [0.0, 1.0]
2061     const Expr *ProbArg = TheCall->getArg(2);
2062     SmallVector<PartialDiagnosticAt, 8> Notes;
2063     Expr::EvalResult Eval;
2064     Eval.Diag = &Notes;
2065     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
2066         !Eval.Val.isFloat()) {
2067       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
2068           << ProbArg->getSourceRange();
2069       for (const PartialDiagnosticAt &PDiag : Notes)
2070         Diag(PDiag.first, PDiag.second);
2071       return ExprError();
2072     }
2073     llvm::APFloat Probability = Eval.Val.getFloat();
2074     bool LoseInfo = false;
2075     Probability.convert(llvm::APFloat::IEEEdouble(),
2076                         llvm::RoundingMode::Dynamic, &LoseInfo);
2077     if (!(Probability >= llvm::APFloat(0.0) &&
2078           Probability <= llvm::APFloat(1.0))) {
2079       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
2080           << ProbArg->getSourceRange();
2081       return ExprError();
2082     }
2083     break;
2084   }
2085   case Builtin::BI__builtin_preserve_access_index:
2086     if (SemaBuiltinPreserveAI(*this, TheCall))
2087       return ExprError();
2088     break;
2089   case Builtin::BI__builtin_call_with_static_chain:
2090     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
2091       return ExprError();
2092     break;
2093   case Builtin::BI__exception_code:
2094   case Builtin::BI_exception_code:
2095     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
2096                                  diag::err_seh___except_block))
2097       return ExprError();
2098     break;
2099   case Builtin::BI__exception_info:
2100   case Builtin::BI_exception_info:
2101     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
2102                                  diag::err_seh___except_filter))
2103       return ExprError();
2104     break;
2105   case Builtin::BI__GetExceptionInfo:
2106     if (checkArgCount(*this, TheCall, 1))
2107       return ExprError();
2108 
2109     if (CheckCXXThrowOperand(
2110             TheCall->getBeginLoc(),
2111             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
2112             TheCall))
2113       return ExprError();
2114 
2115     TheCall->setType(Context.VoidPtrTy);
2116     break;
2117   // OpenCL v2.0, s6.13.16 - Pipe functions
2118   case Builtin::BIread_pipe:
2119   case Builtin::BIwrite_pipe:
2120     // Since those two functions are declared with var args, we need a semantic
2121     // check for the argument.
2122     if (SemaBuiltinRWPipe(*this, TheCall))
2123       return ExprError();
2124     break;
2125   case Builtin::BIreserve_read_pipe:
2126   case Builtin::BIreserve_write_pipe:
2127   case Builtin::BIwork_group_reserve_read_pipe:
2128   case Builtin::BIwork_group_reserve_write_pipe:
2129     if (SemaBuiltinReserveRWPipe(*this, TheCall))
2130       return ExprError();
2131     break;
2132   case Builtin::BIsub_group_reserve_read_pipe:
2133   case Builtin::BIsub_group_reserve_write_pipe:
2134     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2135         SemaBuiltinReserveRWPipe(*this, TheCall))
2136       return ExprError();
2137     break;
2138   case Builtin::BIcommit_read_pipe:
2139   case Builtin::BIcommit_write_pipe:
2140   case Builtin::BIwork_group_commit_read_pipe:
2141   case Builtin::BIwork_group_commit_write_pipe:
2142     if (SemaBuiltinCommitRWPipe(*this, TheCall))
2143       return ExprError();
2144     break;
2145   case Builtin::BIsub_group_commit_read_pipe:
2146   case Builtin::BIsub_group_commit_write_pipe:
2147     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2148         SemaBuiltinCommitRWPipe(*this, TheCall))
2149       return ExprError();
2150     break;
2151   case Builtin::BIget_pipe_num_packets:
2152   case Builtin::BIget_pipe_max_packets:
2153     if (SemaBuiltinPipePackets(*this, TheCall))
2154       return ExprError();
2155     break;
2156   case Builtin::BIto_global:
2157   case Builtin::BIto_local:
2158   case Builtin::BIto_private:
2159     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
2160       return ExprError();
2161     break;
2162   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
2163   case Builtin::BIenqueue_kernel:
2164     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
2165       return ExprError();
2166     break;
2167   case Builtin::BIget_kernel_work_group_size:
2168   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
2169     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
2170       return ExprError();
2171     break;
2172   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
2173   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
2174     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
2175       return ExprError();
2176     break;
2177   case Builtin::BI__builtin_os_log_format:
2178     Cleanup.setExprNeedsCleanups(true);
2179     LLVM_FALLTHROUGH;
2180   case Builtin::BI__builtin_os_log_format_buffer_size:
2181     if (SemaBuiltinOSLogFormat(TheCall))
2182       return ExprError();
2183     break;
2184   case Builtin::BI__builtin_frame_address:
2185   case Builtin::BI__builtin_return_address: {
2186     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
2187       return ExprError();
2188 
2189     // -Wframe-address warning if non-zero passed to builtin
2190     // return/frame address.
2191     Expr::EvalResult Result;
2192     if (!TheCall->getArg(0)->isValueDependent() &&
2193         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
2194         Result.Val.getInt() != 0)
2195       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
2196           << ((BuiltinID == Builtin::BI__builtin_return_address)
2197                   ? "__builtin_return_address"
2198                   : "__builtin_frame_address")
2199           << TheCall->getSourceRange();
2200     break;
2201   }
2202 
2203   // __builtin_elementwise_abs restricts the element type to signed integers or
2204   // floating point types only.
2205   case Builtin::BI__builtin_elementwise_abs: {
2206     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2207       return ExprError();
2208 
2209     QualType ArgTy = TheCall->getArg(0)->getType();
2210     QualType EltTy = ArgTy;
2211 
2212     if (auto *VecTy = EltTy->getAs<VectorType>())
2213       EltTy = VecTy->getElementType();
2214     if (EltTy->isUnsignedIntegerType()) {
2215       Diag(TheCall->getArg(0)->getBeginLoc(),
2216            diag::err_builtin_invalid_arg_type)
2217           << 1 << /* signed integer or float ty*/ 3 << ArgTy;
2218       return ExprError();
2219     }
2220     break;
2221   }
2222 
2223   // These builtins restrict the element type to floating point
2224   // types only.
2225   case Builtin::BI__builtin_elementwise_ceil:
2226   case Builtin::BI__builtin_elementwise_floor:
2227   case Builtin::BI__builtin_elementwise_roundeven:
2228   case Builtin::BI__builtin_elementwise_trunc: {
2229     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2230       return ExprError();
2231 
2232     QualType ArgTy = TheCall->getArg(0)->getType();
2233     QualType EltTy = ArgTy;
2234 
2235     if (auto *VecTy = EltTy->getAs<VectorType>())
2236       EltTy = VecTy->getElementType();
2237     if (!EltTy->isFloatingType()) {
2238       Diag(TheCall->getArg(0)->getBeginLoc(),
2239            diag::err_builtin_invalid_arg_type)
2240           << 1 << /* float ty*/ 5 << ArgTy;
2241 
2242       return ExprError();
2243     }
2244     break;
2245   }
2246 
2247   // These builtins restrict the element type to integer
2248   // types only.
2249   case Builtin::BI__builtin_elementwise_add_sat:
2250   case Builtin::BI__builtin_elementwise_sub_sat: {
2251     if (SemaBuiltinElementwiseMath(TheCall))
2252       return ExprError();
2253 
2254     const Expr *Arg = TheCall->getArg(0);
2255     QualType ArgTy = Arg->getType();
2256     QualType EltTy = ArgTy;
2257 
2258     if (auto *VecTy = EltTy->getAs<VectorType>())
2259       EltTy = VecTy->getElementType();
2260 
2261     if (!EltTy->isIntegerType()) {
2262       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2263           << 1 << /* integer ty */ 6 << ArgTy;
2264       return ExprError();
2265     }
2266     break;
2267   }
2268 
2269   case Builtin::BI__builtin_elementwise_min:
2270   case Builtin::BI__builtin_elementwise_max:
2271     if (SemaBuiltinElementwiseMath(TheCall))
2272       return ExprError();
2273     break;
2274   case Builtin::BI__builtin_reduce_max:
2275   case Builtin::BI__builtin_reduce_min: {
2276     if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2277       return ExprError();
2278 
2279     const Expr *Arg = TheCall->getArg(0);
2280     const auto *TyA = Arg->getType()->getAs<VectorType>();
2281     if (!TyA) {
2282       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2283           << 1 << /* vector ty*/ 4 << Arg->getType();
2284       return ExprError();
2285     }
2286 
2287     TheCall->setType(TyA->getElementType());
2288     break;
2289   }
2290 
2291   // These builtins support vectors of integers only.
2292   case Builtin::BI__builtin_reduce_xor:
2293   case Builtin::BI__builtin_reduce_or:
2294   case Builtin::BI__builtin_reduce_and: {
2295     if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2296       return ExprError();
2297 
2298     const Expr *Arg = TheCall->getArg(0);
2299     const auto *TyA = Arg->getType()->getAs<VectorType>();
2300     if (!TyA || !TyA->getElementType()->isIntegerType()) {
2301       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2302           << 1  << /* vector of integers */ 6 << Arg->getType();
2303       return ExprError();
2304     }
2305     TheCall->setType(TyA->getElementType());
2306     break;
2307   }
2308 
2309   case Builtin::BI__builtin_matrix_transpose:
2310     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
2311 
2312   case Builtin::BI__builtin_matrix_column_major_load:
2313     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
2314 
2315   case Builtin::BI__builtin_matrix_column_major_store:
2316     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
2317 
2318   case Builtin::BI__builtin_get_device_side_mangled_name: {
2319     auto Check = [](CallExpr *TheCall) {
2320       if (TheCall->getNumArgs() != 1)
2321         return false;
2322       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
2323       if (!DRE)
2324         return false;
2325       auto *D = DRE->getDecl();
2326       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
2327         return false;
2328       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
2329              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2330     };
2331     if (!Check(TheCall)) {
2332       Diag(TheCall->getBeginLoc(),
2333            diag::err_hip_invalid_args_builtin_mangled_name);
2334       return ExprError();
2335     }
2336   }
2337   }
2338 
2339   // Since the target specific builtins for each arch overlap, only check those
2340   // of the arch we are compiling for.
2341   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2342     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2343       assert(Context.getAuxTargetInfo() &&
2344              "Aux Target Builtin, but not an aux target?");
2345 
2346       if (CheckTSBuiltinFunctionCall(
2347               *Context.getAuxTargetInfo(),
2348               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2349         return ExprError();
2350     } else {
2351       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2352                                      TheCall))
2353         return ExprError();
2354     }
2355   }
2356 
2357   return TheCallResult;
2358 }
2359 
2360 // Get the valid immediate range for the specified NEON type code.
2361 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2362   NeonTypeFlags Type(t);
2363   int IsQuad = ForceQuad ? true : Type.isQuad();
2364   switch (Type.getEltType()) {
2365   case NeonTypeFlags::Int8:
2366   case NeonTypeFlags::Poly8:
2367     return shift ? 7 : (8 << IsQuad) - 1;
2368   case NeonTypeFlags::Int16:
2369   case NeonTypeFlags::Poly16:
2370     return shift ? 15 : (4 << IsQuad) - 1;
2371   case NeonTypeFlags::Int32:
2372     return shift ? 31 : (2 << IsQuad) - 1;
2373   case NeonTypeFlags::Int64:
2374   case NeonTypeFlags::Poly64:
2375     return shift ? 63 : (1 << IsQuad) - 1;
2376   case NeonTypeFlags::Poly128:
2377     return shift ? 127 : (1 << IsQuad) - 1;
2378   case NeonTypeFlags::Float16:
2379     assert(!shift && "cannot shift float types!");
2380     return (4 << IsQuad) - 1;
2381   case NeonTypeFlags::Float32:
2382     assert(!shift && "cannot shift float types!");
2383     return (2 << IsQuad) - 1;
2384   case NeonTypeFlags::Float64:
2385     assert(!shift && "cannot shift float types!");
2386     return (1 << IsQuad) - 1;
2387   case NeonTypeFlags::BFloat16:
2388     assert(!shift && "cannot shift float types!");
2389     return (4 << IsQuad) - 1;
2390   }
2391   llvm_unreachable("Invalid NeonTypeFlag!");
2392 }
2393 
2394 /// getNeonEltType - Return the QualType corresponding to the elements of
2395 /// the vector type specified by the NeonTypeFlags.  This is used to check
2396 /// the pointer arguments for Neon load/store intrinsics.
2397 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2398                                bool IsPolyUnsigned, bool IsInt64Long) {
2399   switch (Flags.getEltType()) {
2400   case NeonTypeFlags::Int8:
2401     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2402   case NeonTypeFlags::Int16:
2403     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2404   case NeonTypeFlags::Int32:
2405     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2406   case NeonTypeFlags::Int64:
2407     if (IsInt64Long)
2408       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2409     else
2410       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2411                                 : Context.LongLongTy;
2412   case NeonTypeFlags::Poly8:
2413     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2414   case NeonTypeFlags::Poly16:
2415     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2416   case NeonTypeFlags::Poly64:
2417     if (IsInt64Long)
2418       return Context.UnsignedLongTy;
2419     else
2420       return Context.UnsignedLongLongTy;
2421   case NeonTypeFlags::Poly128:
2422     break;
2423   case NeonTypeFlags::Float16:
2424     return Context.HalfTy;
2425   case NeonTypeFlags::Float32:
2426     return Context.FloatTy;
2427   case NeonTypeFlags::Float64:
2428     return Context.DoubleTy;
2429   case NeonTypeFlags::BFloat16:
2430     return Context.BFloat16Ty;
2431   }
2432   llvm_unreachable("Invalid NeonTypeFlag!");
2433 }
2434 
2435 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2436   // Range check SVE intrinsics that take immediate values.
2437   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2438 
2439   switch (BuiltinID) {
2440   default:
2441     return false;
2442 #define GET_SVE_IMMEDIATE_CHECK
2443 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2444 #undef GET_SVE_IMMEDIATE_CHECK
2445   }
2446 
2447   // Perform all the immediate checks for this builtin call.
2448   bool HasError = false;
2449   for (auto &I : ImmChecks) {
2450     int ArgNum, CheckTy, ElementSizeInBits;
2451     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2452 
2453     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2454 
2455     // Function that checks whether the operand (ArgNum) is an immediate
2456     // that is one of the predefined values.
2457     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2458                                    int ErrDiag) -> bool {
2459       // We can't check the value of a dependent argument.
2460       Expr *Arg = TheCall->getArg(ArgNum);
2461       if (Arg->isTypeDependent() || Arg->isValueDependent())
2462         return false;
2463 
2464       // Check constant-ness first.
2465       llvm::APSInt Imm;
2466       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2467         return true;
2468 
2469       if (!CheckImm(Imm.getSExtValue()))
2470         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2471       return false;
2472     };
2473 
2474     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2475     case SVETypeFlags::ImmCheck0_31:
2476       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2477         HasError = true;
2478       break;
2479     case SVETypeFlags::ImmCheck0_13:
2480       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2481         HasError = true;
2482       break;
2483     case SVETypeFlags::ImmCheck1_16:
2484       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2485         HasError = true;
2486       break;
2487     case SVETypeFlags::ImmCheck0_7:
2488       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2489         HasError = true;
2490       break;
2491     case SVETypeFlags::ImmCheckExtract:
2492       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2493                                       (2048 / ElementSizeInBits) - 1))
2494         HasError = true;
2495       break;
2496     case SVETypeFlags::ImmCheckShiftRight:
2497       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2498         HasError = true;
2499       break;
2500     case SVETypeFlags::ImmCheckShiftRightNarrow:
2501       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2502                                       ElementSizeInBits / 2))
2503         HasError = true;
2504       break;
2505     case SVETypeFlags::ImmCheckShiftLeft:
2506       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2507                                       ElementSizeInBits - 1))
2508         HasError = true;
2509       break;
2510     case SVETypeFlags::ImmCheckLaneIndex:
2511       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2512                                       (128 / (1 * ElementSizeInBits)) - 1))
2513         HasError = true;
2514       break;
2515     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2516       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2517                                       (128 / (2 * ElementSizeInBits)) - 1))
2518         HasError = true;
2519       break;
2520     case SVETypeFlags::ImmCheckLaneIndexDot:
2521       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2522                                       (128 / (4 * ElementSizeInBits)) - 1))
2523         HasError = true;
2524       break;
2525     case SVETypeFlags::ImmCheckComplexRot90_270:
2526       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2527                               diag::err_rotation_argument_to_cadd))
2528         HasError = true;
2529       break;
2530     case SVETypeFlags::ImmCheckComplexRotAll90:
2531       if (CheckImmediateInSet(
2532               [](int64_t V) {
2533                 return V == 0 || V == 90 || V == 180 || V == 270;
2534               },
2535               diag::err_rotation_argument_to_cmla))
2536         HasError = true;
2537       break;
2538     case SVETypeFlags::ImmCheck0_1:
2539       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2540         HasError = true;
2541       break;
2542     case SVETypeFlags::ImmCheck0_2:
2543       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2544         HasError = true;
2545       break;
2546     case SVETypeFlags::ImmCheck0_3:
2547       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2548         HasError = true;
2549       break;
2550     }
2551   }
2552 
2553   return HasError;
2554 }
2555 
2556 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2557                                         unsigned BuiltinID, CallExpr *TheCall) {
2558   llvm::APSInt Result;
2559   uint64_t mask = 0;
2560   unsigned TV = 0;
2561   int PtrArgNum = -1;
2562   bool HasConstPtr = false;
2563   switch (BuiltinID) {
2564 #define GET_NEON_OVERLOAD_CHECK
2565 #include "clang/Basic/arm_neon.inc"
2566 #include "clang/Basic/arm_fp16.inc"
2567 #undef GET_NEON_OVERLOAD_CHECK
2568   }
2569 
2570   // For NEON intrinsics which are overloaded on vector element type, validate
2571   // the immediate which specifies which variant to emit.
2572   unsigned ImmArg = TheCall->getNumArgs()-1;
2573   if (mask) {
2574     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2575       return true;
2576 
2577     TV = Result.getLimitedValue(64);
2578     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2579       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2580              << TheCall->getArg(ImmArg)->getSourceRange();
2581   }
2582 
2583   if (PtrArgNum >= 0) {
2584     // Check that pointer arguments have the specified type.
2585     Expr *Arg = TheCall->getArg(PtrArgNum);
2586     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2587       Arg = ICE->getSubExpr();
2588     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2589     QualType RHSTy = RHS.get()->getType();
2590 
2591     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2592     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2593                           Arch == llvm::Triple::aarch64_32 ||
2594                           Arch == llvm::Triple::aarch64_be;
2595     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2596     QualType EltTy =
2597         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2598     if (HasConstPtr)
2599       EltTy = EltTy.withConst();
2600     QualType LHSTy = Context.getPointerType(EltTy);
2601     AssignConvertType ConvTy;
2602     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2603     if (RHS.isInvalid())
2604       return true;
2605     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2606                                  RHS.get(), AA_Assigning))
2607       return true;
2608   }
2609 
2610   // For NEON intrinsics which take an immediate value as part of the
2611   // instruction, range check them here.
2612   unsigned i = 0, l = 0, u = 0;
2613   switch (BuiltinID) {
2614   default:
2615     return false;
2616   #define GET_NEON_IMMEDIATE_CHECK
2617   #include "clang/Basic/arm_neon.inc"
2618   #include "clang/Basic/arm_fp16.inc"
2619   #undef GET_NEON_IMMEDIATE_CHECK
2620   }
2621 
2622   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2623 }
2624 
2625 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2626   switch (BuiltinID) {
2627   default:
2628     return false;
2629   #include "clang/Basic/arm_mve_builtin_sema.inc"
2630   }
2631 }
2632 
2633 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2634                                        CallExpr *TheCall) {
2635   bool Err = false;
2636   switch (BuiltinID) {
2637   default:
2638     return false;
2639 #include "clang/Basic/arm_cde_builtin_sema.inc"
2640   }
2641 
2642   if (Err)
2643     return true;
2644 
2645   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2646 }
2647 
2648 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2649                                         const Expr *CoprocArg, bool WantCDE) {
2650   if (isConstantEvaluated())
2651     return false;
2652 
2653   // We can't check the value of a dependent argument.
2654   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2655     return false;
2656 
2657   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2658   int64_t CoprocNo = CoprocNoAP.getExtValue();
2659   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2660 
2661   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2662   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2663 
2664   if (IsCDECoproc != WantCDE)
2665     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2666            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2667 
2668   return false;
2669 }
2670 
2671 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2672                                         unsigned MaxWidth) {
2673   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2674           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2675           BuiltinID == ARM::BI__builtin_arm_strex ||
2676           BuiltinID == ARM::BI__builtin_arm_stlex ||
2677           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2678           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2679           BuiltinID == AArch64::BI__builtin_arm_strex ||
2680           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2681          "unexpected ARM builtin");
2682   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2683                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2684                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2685                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2686 
2687   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2688 
2689   // Ensure that we have the proper number of arguments.
2690   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2691     return true;
2692 
2693   // Inspect the pointer argument of the atomic builtin.  This should always be
2694   // a pointer type, whose element is an integral scalar or pointer type.
2695   // Because it is a pointer type, we don't have to worry about any implicit
2696   // casts here.
2697   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2698   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2699   if (PointerArgRes.isInvalid())
2700     return true;
2701   PointerArg = PointerArgRes.get();
2702 
2703   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2704   if (!pointerType) {
2705     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2706         << PointerArg->getType() << PointerArg->getSourceRange();
2707     return true;
2708   }
2709 
2710   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2711   // task is to insert the appropriate casts into the AST. First work out just
2712   // what the appropriate type is.
2713   QualType ValType = pointerType->getPointeeType();
2714   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2715   if (IsLdrex)
2716     AddrType.addConst();
2717 
2718   // Issue a warning if the cast is dodgy.
2719   CastKind CastNeeded = CK_NoOp;
2720   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2721     CastNeeded = CK_BitCast;
2722     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2723         << PointerArg->getType() << Context.getPointerType(AddrType)
2724         << AA_Passing << PointerArg->getSourceRange();
2725   }
2726 
2727   // Finally, do the cast and replace the argument with the corrected version.
2728   AddrType = Context.getPointerType(AddrType);
2729   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2730   if (PointerArgRes.isInvalid())
2731     return true;
2732   PointerArg = PointerArgRes.get();
2733 
2734   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2735 
2736   // In general, we allow ints, floats and pointers to be loaded and stored.
2737   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2738       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2739     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2740         << PointerArg->getType() << PointerArg->getSourceRange();
2741     return true;
2742   }
2743 
2744   // But ARM doesn't have instructions to deal with 128-bit versions.
2745   if (Context.getTypeSize(ValType) > MaxWidth) {
2746     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2747     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2748         << PointerArg->getType() << PointerArg->getSourceRange();
2749     return true;
2750   }
2751 
2752   switch (ValType.getObjCLifetime()) {
2753   case Qualifiers::OCL_None:
2754   case Qualifiers::OCL_ExplicitNone:
2755     // okay
2756     break;
2757 
2758   case Qualifiers::OCL_Weak:
2759   case Qualifiers::OCL_Strong:
2760   case Qualifiers::OCL_Autoreleasing:
2761     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2762         << ValType << PointerArg->getSourceRange();
2763     return true;
2764   }
2765 
2766   if (IsLdrex) {
2767     TheCall->setType(ValType);
2768     return false;
2769   }
2770 
2771   // Initialize the argument to be stored.
2772   ExprResult ValArg = TheCall->getArg(0);
2773   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2774       Context, ValType, /*consume*/ false);
2775   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2776   if (ValArg.isInvalid())
2777     return true;
2778   TheCall->setArg(0, ValArg.get());
2779 
2780   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2781   // but the custom checker bypasses all default analysis.
2782   TheCall->setType(Context.IntTy);
2783   return false;
2784 }
2785 
2786 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2787                                        CallExpr *TheCall) {
2788   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2789       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2790       BuiltinID == ARM::BI__builtin_arm_strex ||
2791       BuiltinID == ARM::BI__builtin_arm_stlex) {
2792     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2793   }
2794 
2795   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2796     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2797       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2798   }
2799 
2800   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2801       BuiltinID == ARM::BI__builtin_arm_wsr64)
2802     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2803 
2804   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2805       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2806       BuiltinID == ARM::BI__builtin_arm_wsr ||
2807       BuiltinID == ARM::BI__builtin_arm_wsrp)
2808     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2809 
2810   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2811     return true;
2812   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2813     return true;
2814   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2815     return true;
2816 
2817   // For intrinsics which take an immediate value as part of the instruction,
2818   // range check them here.
2819   // FIXME: VFP Intrinsics should error if VFP not present.
2820   switch (BuiltinID) {
2821   default: return false;
2822   case ARM::BI__builtin_arm_ssat:
2823     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2824   case ARM::BI__builtin_arm_usat:
2825     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2826   case ARM::BI__builtin_arm_ssat16:
2827     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2828   case ARM::BI__builtin_arm_usat16:
2829     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2830   case ARM::BI__builtin_arm_vcvtr_f:
2831   case ARM::BI__builtin_arm_vcvtr_d:
2832     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2833   case ARM::BI__builtin_arm_dmb:
2834   case ARM::BI__builtin_arm_dsb:
2835   case ARM::BI__builtin_arm_isb:
2836   case ARM::BI__builtin_arm_dbg:
2837     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2838   case ARM::BI__builtin_arm_cdp:
2839   case ARM::BI__builtin_arm_cdp2:
2840   case ARM::BI__builtin_arm_mcr:
2841   case ARM::BI__builtin_arm_mcr2:
2842   case ARM::BI__builtin_arm_mrc:
2843   case ARM::BI__builtin_arm_mrc2:
2844   case ARM::BI__builtin_arm_mcrr:
2845   case ARM::BI__builtin_arm_mcrr2:
2846   case ARM::BI__builtin_arm_mrrc:
2847   case ARM::BI__builtin_arm_mrrc2:
2848   case ARM::BI__builtin_arm_ldc:
2849   case ARM::BI__builtin_arm_ldcl:
2850   case ARM::BI__builtin_arm_ldc2:
2851   case ARM::BI__builtin_arm_ldc2l:
2852   case ARM::BI__builtin_arm_stc:
2853   case ARM::BI__builtin_arm_stcl:
2854   case ARM::BI__builtin_arm_stc2:
2855   case ARM::BI__builtin_arm_stc2l:
2856     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2857            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2858                                         /*WantCDE*/ false);
2859   }
2860 }
2861 
2862 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2863                                            unsigned BuiltinID,
2864                                            CallExpr *TheCall) {
2865   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2866       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2867       BuiltinID == AArch64::BI__builtin_arm_strex ||
2868       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2869     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2870   }
2871 
2872   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2873     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2874       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2875       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2876       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2877   }
2878 
2879   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2880       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2881     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2882 
2883   // Memory Tagging Extensions (MTE) Intrinsics
2884   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2885       BuiltinID == AArch64::BI__builtin_arm_addg ||
2886       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2887       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2888       BuiltinID == AArch64::BI__builtin_arm_stg ||
2889       BuiltinID == AArch64::BI__builtin_arm_subp) {
2890     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2891   }
2892 
2893   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2894       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2895       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2896       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2897     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2898 
2899   // Only check the valid encoding range. Any constant in this range would be
2900   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2901   // an exception for incorrect registers. This matches MSVC behavior.
2902   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2903       BuiltinID == AArch64::BI_WriteStatusReg)
2904     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2905 
2906   if (BuiltinID == AArch64::BI__getReg)
2907     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2908 
2909   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2910     return true;
2911 
2912   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2913     return true;
2914 
2915   // For intrinsics which take an immediate value as part of the instruction,
2916   // range check them here.
2917   unsigned i = 0, l = 0, u = 0;
2918   switch (BuiltinID) {
2919   default: return false;
2920   case AArch64::BI__builtin_arm_dmb:
2921   case AArch64::BI__builtin_arm_dsb:
2922   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2923   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2924   }
2925 
2926   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2927 }
2928 
2929 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2930   if (Arg->getType()->getAsPlaceholderType())
2931     return false;
2932 
2933   // The first argument needs to be a record field access.
2934   // If it is an array element access, we delay decision
2935   // to BPF backend to check whether the access is a
2936   // field access or not.
2937   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2938           isa<MemberExpr>(Arg->IgnoreParens()) ||
2939           isa<ArraySubscriptExpr>(Arg->IgnoreParens()));
2940 }
2941 
2942 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2943                             QualType VectorTy, QualType EltTy) {
2944   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2945   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2946     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2947         << Call->getSourceRange() << VectorEltTy << EltTy;
2948     return false;
2949   }
2950   return true;
2951 }
2952 
2953 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2954   QualType ArgType = Arg->getType();
2955   if (ArgType->getAsPlaceholderType())
2956     return false;
2957 
2958   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2959   // format:
2960   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2961   //   2. <type> var;
2962   //      __builtin_preserve_type_info(var, flag);
2963   if (!isa<DeclRefExpr>(Arg->IgnoreParens()) &&
2964       !isa<UnaryOperator>(Arg->IgnoreParens()))
2965     return false;
2966 
2967   // Typedef type.
2968   if (ArgType->getAs<TypedefType>())
2969     return true;
2970 
2971   // Record type or Enum type.
2972   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2973   if (const auto *RT = Ty->getAs<RecordType>()) {
2974     if (!RT->getDecl()->getDeclName().isEmpty())
2975       return true;
2976   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2977     if (!ET->getDecl()->getDeclName().isEmpty())
2978       return true;
2979   }
2980 
2981   return false;
2982 }
2983 
2984 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2985   QualType ArgType = Arg->getType();
2986   if (ArgType->getAsPlaceholderType())
2987     return false;
2988 
2989   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2990   // format:
2991   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2992   //                                 flag);
2993   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2994   if (!UO)
2995     return false;
2996 
2997   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2998   if (!CE)
2999     return false;
3000   if (CE->getCastKind() != CK_IntegralToPointer &&
3001       CE->getCastKind() != CK_NullToPointer)
3002     return false;
3003 
3004   // The integer must be from an EnumConstantDecl.
3005   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
3006   if (!DR)
3007     return false;
3008 
3009   const EnumConstantDecl *Enumerator =
3010       dyn_cast<EnumConstantDecl>(DR->getDecl());
3011   if (!Enumerator)
3012     return false;
3013 
3014   // The type must be EnumType.
3015   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
3016   const auto *ET = Ty->getAs<EnumType>();
3017   if (!ET)
3018     return false;
3019 
3020   // The enum value must be supported.
3021   return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
3022 }
3023 
3024 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
3025                                        CallExpr *TheCall) {
3026   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
3027           BuiltinID == BPF::BI__builtin_btf_type_id ||
3028           BuiltinID == BPF::BI__builtin_preserve_type_info ||
3029           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
3030          "unexpected BPF builtin");
3031 
3032   if (checkArgCount(*this, TheCall, 2))
3033     return true;
3034 
3035   // The second argument needs to be a constant int
3036   Expr *Arg = TheCall->getArg(1);
3037   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
3038   diag::kind kind;
3039   if (!Value) {
3040     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
3041       kind = diag::err_preserve_field_info_not_const;
3042     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
3043       kind = diag::err_btf_type_id_not_const;
3044     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
3045       kind = diag::err_preserve_type_info_not_const;
3046     else
3047       kind = diag::err_preserve_enum_value_not_const;
3048     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
3049     return true;
3050   }
3051 
3052   // The first argument
3053   Arg = TheCall->getArg(0);
3054   bool InvalidArg = false;
3055   bool ReturnUnsignedInt = true;
3056   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
3057     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
3058       InvalidArg = true;
3059       kind = diag::err_preserve_field_info_not_field;
3060     }
3061   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
3062     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
3063       InvalidArg = true;
3064       kind = diag::err_preserve_type_info_invalid;
3065     }
3066   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
3067     if (!isValidBPFPreserveEnumValueArg(Arg)) {
3068       InvalidArg = true;
3069       kind = diag::err_preserve_enum_value_invalid;
3070     }
3071     ReturnUnsignedInt = false;
3072   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
3073     ReturnUnsignedInt = false;
3074   }
3075 
3076   if (InvalidArg) {
3077     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
3078     return true;
3079   }
3080 
3081   if (ReturnUnsignedInt)
3082     TheCall->setType(Context.UnsignedIntTy);
3083   else
3084     TheCall->setType(Context.UnsignedLongTy);
3085   return false;
3086 }
3087 
3088 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3089   struct ArgInfo {
3090     uint8_t OpNum;
3091     bool IsSigned;
3092     uint8_t BitWidth;
3093     uint8_t Align;
3094   };
3095   struct BuiltinInfo {
3096     unsigned BuiltinID;
3097     ArgInfo Infos[2];
3098   };
3099 
3100   static BuiltinInfo Infos[] = {
3101     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
3102     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
3103     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
3104     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
3105     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
3106     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
3107     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
3108     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
3109     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
3110     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
3111     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
3112 
3113     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
3114     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
3115     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
3116     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
3117     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
3118     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
3119     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
3120     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
3121     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
3122     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
3123     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
3124 
3125     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
3126     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
3127     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
3128     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
3129     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
3130     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
3131     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
3132     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
3133     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
3134     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
3135     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
3136     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
3137     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
3138     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
3139     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
3140     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
3141     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
3142     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
3143     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
3144     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
3145     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
3146     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
3147     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
3148     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
3149     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
3150     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
3151     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
3152     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
3153     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
3154     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
3155     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
3156     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
3157     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
3158     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
3159     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
3160     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
3161     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
3162     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
3163     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
3164     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
3165     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
3166     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
3167     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
3168     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
3169     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
3170     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
3171     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
3172     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
3173     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
3174     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
3175     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
3176     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
3177                                                       {{ 1, false, 6,  0 }} },
3178     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
3179     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
3180     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
3181     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
3182     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
3183     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
3184     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
3185                                                       {{ 1, false, 5,  0 }} },
3186     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
3187     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
3188     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
3189     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
3190     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
3191     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
3192                                                        { 2, false, 5,  0 }} },
3193     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
3194                                                        { 2, false, 6,  0 }} },
3195     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
3196                                                        { 3, false, 5,  0 }} },
3197     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
3198                                                        { 3, false, 6,  0 }} },
3199     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
3200     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
3201     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
3202     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
3203     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
3204     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
3205     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
3206     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
3207     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
3208     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
3209     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
3210     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
3211     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
3212     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
3213     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
3214     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
3215                                                       {{ 2, false, 4,  0 },
3216                                                        { 3, false, 5,  0 }} },
3217     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
3218                                                       {{ 2, false, 4,  0 },
3219                                                        { 3, false, 5,  0 }} },
3220     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
3221                                                       {{ 2, false, 4,  0 },
3222                                                        { 3, false, 5,  0 }} },
3223     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
3224                                                       {{ 2, false, 4,  0 },
3225                                                        { 3, false, 5,  0 }} },
3226     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
3227     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
3228     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
3229     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
3230     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
3231     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
3232     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
3233     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
3234     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
3235     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
3236     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
3237                                                        { 2, false, 5,  0 }} },
3238     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
3239                                                        { 2, false, 6,  0 }} },
3240     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
3241     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
3242     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
3243     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
3244     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
3245     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
3246     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
3247     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
3248     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
3249                                                       {{ 1, false, 4,  0 }} },
3250     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
3251     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
3252                                                       {{ 1, false, 4,  0 }} },
3253     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
3254     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
3255     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
3256     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
3257     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
3258     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
3259     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
3260     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
3261     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
3262     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
3263     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
3264     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
3265     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
3266     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
3267     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
3268     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
3269     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
3270     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
3271     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
3272     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
3273                                                       {{ 3, false, 1,  0 }} },
3274     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
3275     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
3276     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
3277     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
3278                                                       {{ 3, false, 1,  0 }} },
3279     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
3280     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
3281     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
3282     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
3283                                                       {{ 3, false, 1,  0 }} },
3284   };
3285 
3286   // Use a dynamically initialized static to sort the table exactly once on
3287   // first run.
3288   static const bool SortOnce =
3289       (llvm::sort(Infos,
3290                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
3291                    return LHS.BuiltinID < RHS.BuiltinID;
3292                  }),
3293        true);
3294   (void)SortOnce;
3295 
3296   const BuiltinInfo *F = llvm::partition_point(
3297       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
3298   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
3299     return false;
3300 
3301   bool Error = false;
3302 
3303   for (const ArgInfo &A : F->Infos) {
3304     // Ignore empty ArgInfo elements.
3305     if (A.BitWidth == 0)
3306       continue;
3307 
3308     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
3309     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
3310     if (!A.Align) {
3311       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3312     } else {
3313       unsigned M = 1 << A.Align;
3314       Min *= M;
3315       Max *= M;
3316       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3317       Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
3318     }
3319   }
3320   return Error;
3321 }
3322 
3323 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
3324                                            CallExpr *TheCall) {
3325   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3326 }
3327 
3328 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
3329                                         unsigned BuiltinID, CallExpr *TheCall) {
3330   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
3331          CheckMipsBuiltinArgument(BuiltinID, TheCall);
3332 }
3333 
3334 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
3335                                CallExpr *TheCall) {
3336 
3337   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3338       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3339     if (!TI.hasFeature("dsp"))
3340       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3341   }
3342 
3343   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3344       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3345     if (!TI.hasFeature("dspr2"))
3346       return Diag(TheCall->getBeginLoc(),
3347                   diag::err_mips_builtin_requires_dspr2);
3348   }
3349 
3350   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3351       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3352     if (!TI.hasFeature("msa"))
3353       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3354   }
3355 
3356   return false;
3357 }
3358 
3359 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3360 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3361 // ordering for DSP is unspecified. MSA is ordered by the data format used
3362 // by the underlying instruction i.e., df/m, df/n and then by size.
3363 //
3364 // FIXME: The size tests here should instead be tablegen'd along with the
3365 //        definitions from include/clang/Basic/BuiltinsMips.def.
3366 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3367 //        be too.
3368 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3369   unsigned i = 0, l = 0, u = 0, m = 0;
3370   switch (BuiltinID) {
3371   default: return false;
3372   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3373   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3374   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3375   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3376   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3377   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3378   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3379   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3380   // df/m field.
3381   // These intrinsics take an unsigned 3 bit immediate.
3382   case Mips::BI__builtin_msa_bclri_b:
3383   case Mips::BI__builtin_msa_bnegi_b:
3384   case Mips::BI__builtin_msa_bseti_b:
3385   case Mips::BI__builtin_msa_sat_s_b:
3386   case Mips::BI__builtin_msa_sat_u_b:
3387   case Mips::BI__builtin_msa_slli_b:
3388   case Mips::BI__builtin_msa_srai_b:
3389   case Mips::BI__builtin_msa_srari_b:
3390   case Mips::BI__builtin_msa_srli_b:
3391   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3392   case Mips::BI__builtin_msa_binsli_b:
3393   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3394   // These intrinsics take an unsigned 4 bit immediate.
3395   case Mips::BI__builtin_msa_bclri_h:
3396   case Mips::BI__builtin_msa_bnegi_h:
3397   case Mips::BI__builtin_msa_bseti_h:
3398   case Mips::BI__builtin_msa_sat_s_h:
3399   case Mips::BI__builtin_msa_sat_u_h:
3400   case Mips::BI__builtin_msa_slli_h:
3401   case Mips::BI__builtin_msa_srai_h:
3402   case Mips::BI__builtin_msa_srari_h:
3403   case Mips::BI__builtin_msa_srli_h:
3404   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3405   case Mips::BI__builtin_msa_binsli_h:
3406   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3407   // These intrinsics take an unsigned 5 bit immediate.
3408   // The first block of intrinsics actually have an unsigned 5 bit field,
3409   // not a df/n field.
3410   case Mips::BI__builtin_msa_cfcmsa:
3411   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3412   case Mips::BI__builtin_msa_clei_u_b:
3413   case Mips::BI__builtin_msa_clei_u_h:
3414   case Mips::BI__builtin_msa_clei_u_w:
3415   case Mips::BI__builtin_msa_clei_u_d:
3416   case Mips::BI__builtin_msa_clti_u_b:
3417   case Mips::BI__builtin_msa_clti_u_h:
3418   case Mips::BI__builtin_msa_clti_u_w:
3419   case Mips::BI__builtin_msa_clti_u_d:
3420   case Mips::BI__builtin_msa_maxi_u_b:
3421   case Mips::BI__builtin_msa_maxi_u_h:
3422   case Mips::BI__builtin_msa_maxi_u_w:
3423   case Mips::BI__builtin_msa_maxi_u_d:
3424   case Mips::BI__builtin_msa_mini_u_b:
3425   case Mips::BI__builtin_msa_mini_u_h:
3426   case Mips::BI__builtin_msa_mini_u_w:
3427   case Mips::BI__builtin_msa_mini_u_d:
3428   case Mips::BI__builtin_msa_addvi_b:
3429   case Mips::BI__builtin_msa_addvi_h:
3430   case Mips::BI__builtin_msa_addvi_w:
3431   case Mips::BI__builtin_msa_addvi_d:
3432   case Mips::BI__builtin_msa_bclri_w:
3433   case Mips::BI__builtin_msa_bnegi_w:
3434   case Mips::BI__builtin_msa_bseti_w:
3435   case Mips::BI__builtin_msa_sat_s_w:
3436   case Mips::BI__builtin_msa_sat_u_w:
3437   case Mips::BI__builtin_msa_slli_w:
3438   case Mips::BI__builtin_msa_srai_w:
3439   case Mips::BI__builtin_msa_srari_w:
3440   case Mips::BI__builtin_msa_srli_w:
3441   case Mips::BI__builtin_msa_srlri_w:
3442   case Mips::BI__builtin_msa_subvi_b:
3443   case Mips::BI__builtin_msa_subvi_h:
3444   case Mips::BI__builtin_msa_subvi_w:
3445   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3446   case Mips::BI__builtin_msa_binsli_w:
3447   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3448   // These intrinsics take an unsigned 6 bit immediate.
3449   case Mips::BI__builtin_msa_bclri_d:
3450   case Mips::BI__builtin_msa_bnegi_d:
3451   case Mips::BI__builtin_msa_bseti_d:
3452   case Mips::BI__builtin_msa_sat_s_d:
3453   case Mips::BI__builtin_msa_sat_u_d:
3454   case Mips::BI__builtin_msa_slli_d:
3455   case Mips::BI__builtin_msa_srai_d:
3456   case Mips::BI__builtin_msa_srari_d:
3457   case Mips::BI__builtin_msa_srli_d:
3458   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3459   case Mips::BI__builtin_msa_binsli_d:
3460   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3461   // These intrinsics take a signed 5 bit immediate.
3462   case Mips::BI__builtin_msa_ceqi_b:
3463   case Mips::BI__builtin_msa_ceqi_h:
3464   case Mips::BI__builtin_msa_ceqi_w:
3465   case Mips::BI__builtin_msa_ceqi_d:
3466   case Mips::BI__builtin_msa_clti_s_b:
3467   case Mips::BI__builtin_msa_clti_s_h:
3468   case Mips::BI__builtin_msa_clti_s_w:
3469   case Mips::BI__builtin_msa_clti_s_d:
3470   case Mips::BI__builtin_msa_clei_s_b:
3471   case Mips::BI__builtin_msa_clei_s_h:
3472   case Mips::BI__builtin_msa_clei_s_w:
3473   case Mips::BI__builtin_msa_clei_s_d:
3474   case Mips::BI__builtin_msa_maxi_s_b:
3475   case Mips::BI__builtin_msa_maxi_s_h:
3476   case Mips::BI__builtin_msa_maxi_s_w:
3477   case Mips::BI__builtin_msa_maxi_s_d:
3478   case Mips::BI__builtin_msa_mini_s_b:
3479   case Mips::BI__builtin_msa_mini_s_h:
3480   case Mips::BI__builtin_msa_mini_s_w:
3481   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3482   // These intrinsics take an unsigned 8 bit immediate.
3483   case Mips::BI__builtin_msa_andi_b:
3484   case Mips::BI__builtin_msa_nori_b:
3485   case Mips::BI__builtin_msa_ori_b:
3486   case Mips::BI__builtin_msa_shf_b:
3487   case Mips::BI__builtin_msa_shf_h:
3488   case Mips::BI__builtin_msa_shf_w:
3489   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3490   case Mips::BI__builtin_msa_bseli_b:
3491   case Mips::BI__builtin_msa_bmnzi_b:
3492   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3493   // df/n format
3494   // These intrinsics take an unsigned 4 bit immediate.
3495   case Mips::BI__builtin_msa_copy_s_b:
3496   case Mips::BI__builtin_msa_copy_u_b:
3497   case Mips::BI__builtin_msa_insve_b:
3498   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3499   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3500   // These intrinsics take an unsigned 3 bit immediate.
3501   case Mips::BI__builtin_msa_copy_s_h:
3502   case Mips::BI__builtin_msa_copy_u_h:
3503   case Mips::BI__builtin_msa_insve_h:
3504   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3505   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3506   // These intrinsics take an unsigned 2 bit immediate.
3507   case Mips::BI__builtin_msa_copy_s_w:
3508   case Mips::BI__builtin_msa_copy_u_w:
3509   case Mips::BI__builtin_msa_insve_w:
3510   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3511   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3512   // These intrinsics take an unsigned 1 bit immediate.
3513   case Mips::BI__builtin_msa_copy_s_d:
3514   case Mips::BI__builtin_msa_copy_u_d:
3515   case Mips::BI__builtin_msa_insve_d:
3516   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3517   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3518   // Memory offsets and immediate loads.
3519   // These intrinsics take a signed 10 bit immediate.
3520   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3521   case Mips::BI__builtin_msa_ldi_h:
3522   case Mips::BI__builtin_msa_ldi_w:
3523   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3524   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3525   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3526   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3527   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3528   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3529   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3530   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3531   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3532   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3533   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3534   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3535   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3536   }
3537 
3538   if (!m)
3539     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3540 
3541   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3542          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3543 }
3544 
3545 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3546 /// advancing the pointer over the consumed characters. The decoded type is
3547 /// returned. If the decoded type represents a constant integer with a
3548 /// constraint on its value then Mask is set to that value. The type descriptors
3549 /// used in Str are specific to PPC MMA builtins and are documented in the file
3550 /// defining the PPC builtins.
3551 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3552                                         unsigned &Mask) {
3553   bool RequireICE = false;
3554   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3555   switch (*Str++) {
3556   case 'V':
3557     return Context.getVectorType(Context.UnsignedCharTy, 16,
3558                                  VectorType::VectorKind::AltiVecVector);
3559   case 'i': {
3560     char *End;
3561     unsigned size = strtoul(Str, &End, 10);
3562     assert(End != Str && "Missing constant parameter constraint");
3563     Str = End;
3564     Mask = size;
3565     return Context.IntTy;
3566   }
3567   case 'W': {
3568     char *End;
3569     unsigned size = strtoul(Str, &End, 10);
3570     assert(End != Str && "Missing PowerPC MMA type size");
3571     Str = End;
3572     QualType Type;
3573     switch (size) {
3574   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3575     case size: Type = Context.Id##Ty; break;
3576   #include "clang/Basic/PPCTypes.def"
3577     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3578     }
3579     bool CheckVectorArgs = false;
3580     while (!CheckVectorArgs) {
3581       switch (*Str++) {
3582       case '*':
3583         Type = Context.getPointerType(Type);
3584         break;
3585       case 'C':
3586         Type = Type.withConst();
3587         break;
3588       default:
3589         CheckVectorArgs = true;
3590         --Str;
3591         break;
3592       }
3593     }
3594     return Type;
3595   }
3596   default:
3597     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3598   }
3599 }
3600 
3601 static bool isPPC_64Builtin(unsigned BuiltinID) {
3602   // These builtins only work on PPC 64bit targets.
3603   switch (BuiltinID) {
3604   case PPC::BI__builtin_divde:
3605   case PPC::BI__builtin_divdeu:
3606   case PPC::BI__builtin_bpermd:
3607   case PPC::BI__builtin_pdepd:
3608   case PPC::BI__builtin_pextd:
3609   case PPC::BI__builtin_ppc_ldarx:
3610   case PPC::BI__builtin_ppc_stdcx:
3611   case PPC::BI__builtin_ppc_tdw:
3612   case PPC::BI__builtin_ppc_trapd:
3613   case PPC::BI__builtin_ppc_cmpeqb:
3614   case PPC::BI__builtin_ppc_setb:
3615   case PPC::BI__builtin_ppc_mulhd:
3616   case PPC::BI__builtin_ppc_mulhdu:
3617   case PPC::BI__builtin_ppc_maddhd:
3618   case PPC::BI__builtin_ppc_maddhdu:
3619   case PPC::BI__builtin_ppc_maddld:
3620   case PPC::BI__builtin_ppc_load8r:
3621   case PPC::BI__builtin_ppc_store8r:
3622   case PPC::BI__builtin_ppc_insert_exp:
3623   case PPC::BI__builtin_ppc_extract_sig:
3624   case PPC::BI__builtin_ppc_addex:
3625   case PPC::BI__builtin_darn:
3626   case PPC::BI__builtin_darn_raw:
3627   case PPC::BI__builtin_ppc_compare_and_swaplp:
3628   case PPC::BI__builtin_ppc_fetch_and_addlp:
3629   case PPC::BI__builtin_ppc_fetch_and_andlp:
3630   case PPC::BI__builtin_ppc_fetch_and_orlp:
3631   case PPC::BI__builtin_ppc_fetch_and_swaplp:
3632     return true;
3633   }
3634   return false;
3635 }
3636 
3637 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3638                              StringRef FeatureToCheck, unsigned DiagID,
3639                              StringRef DiagArg = "") {
3640   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3641     return false;
3642 
3643   if (DiagArg.empty())
3644     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3645   else
3646     S.Diag(TheCall->getBeginLoc(), DiagID)
3647         << DiagArg << TheCall->getSourceRange();
3648 
3649   return true;
3650 }
3651 
3652 /// Returns true if the argument consists of one contiguous run of 1s with any
3653 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3654 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3655 /// since all 1s are not contiguous.
3656 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3657   llvm::APSInt Result;
3658   // We can't check the value of a dependent argument.
3659   Expr *Arg = TheCall->getArg(ArgNum);
3660   if (Arg->isTypeDependent() || Arg->isValueDependent())
3661     return false;
3662 
3663   // Check constant-ness first.
3664   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3665     return true;
3666 
3667   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3668   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3669     return false;
3670 
3671   return Diag(TheCall->getBeginLoc(),
3672               diag::err_argument_not_contiguous_bit_field)
3673          << ArgNum << Arg->getSourceRange();
3674 }
3675 
3676 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3677                                        CallExpr *TheCall) {
3678   unsigned i = 0, l = 0, u = 0;
3679   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3680   llvm::APSInt Result;
3681 
3682   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3683     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3684            << TheCall->getSourceRange();
3685 
3686   switch (BuiltinID) {
3687   default: return false;
3688   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3689   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3690     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3691            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3692   case PPC::BI__builtin_altivec_dss:
3693     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3694   case PPC::BI__builtin_tbegin:
3695   case PPC::BI__builtin_tend:
3696     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 1) ||
3697            SemaFeatureCheck(*this, TheCall, "htm",
3698                             diag::err_ppc_builtin_requires_htm);
3699   case PPC::BI__builtin_tsr:
3700     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3701            SemaFeatureCheck(*this, TheCall, "htm",
3702                             diag::err_ppc_builtin_requires_htm);
3703   case PPC::BI__builtin_tabortwc:
3704   case PPC::BI__builtin_tabortdc:
3705     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3706            SemaFeatureCheck(*this, TheCall, "htm",
3707                             diag::err_ppc_builtin_requires_htm);
3708   case PPC::BI__builtin_tabortwci:
3709   case PPC::BI__builtin_tabortdci:
3710     return SemaFeatureCheck(*this, TheCall, "htm",
3711                             diag::err_ppc_builtin_requires_htm) ||
3712            (SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3713             SemaBuiltinConstantArgRange(TheCall, 2, 0, 31));
3714   case PPC::BI__builtin_tabort:
3715   case PPC::BI__builtin_tcheck:
3716   case PPC::BI__builtin_treclaim:
3717   case PPC::BI__builtin_trechkpt:
3718   case PPC::BI__builtin_tendall:
3719   case PPC::BI__builtin_tresume:
3720   case PPC::BI__builtin_tsuspend:
3721   case PPC::BI__builtin_get_texasr:
3722   case PPC::BI__builtin_get_texasru:
3723   case PPC::BI__builtin_get_tfhar:
3724   case PPC::BI__builtin_get_tfiar:
3725   case PPC::BI__builtin_set_texasr:
3726   case PPC::BI__builtin_set_texasru:
3727   case PPC::BI__builtin_set_tfhar:
3728   case PPC::BI__builtin_set_tfiar:
3729   case PPC::BI__builtin_ttest:
3730     return SemaFeatureCheck(*this, TheCall, "htm",
3731                             diag::err_ppc_builtin_requires_htm);
3732   // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05',
3733   // __builtin_(un)pack_longdouble are available only if long double uses IBM
3734   // extended double representation.
3735   case PPC::BI__builtin_unpack_longdouble:
3736     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1))
3737       return true;
3738     LLVM_FALLTHROUGH;
3739   case PPC::BI__builtin_pack_longdouble:
3740     if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble())
3741       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi)
3742              << "ibmlongdouble";
3743     return false;
3744   case PPC::BI__builtin_altivec_dst:
3745   case PPC::BI__builtin_altivec_dstt:
3746   case PPC::BI__builtin_altivec_dstst:
3747   case PPC::BI__builtin_altivec_dststt:
3748     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3749   case PPC::BI__builtin_vsx_xxpermdi:
3750   case PPC::BI__builtin_vsx_xxsldwi:
3751     return SemaBuiltinVSX(TheCall);
3752   case PPC::BI__builtin_divwe:
3753   case PPC::BI__builtin_divweu:
3754   case PPC::BI__builtin_divde:
3755   case PPC::BI__builtin_divdeu:
3756     return SemaFeatureCheck(*this, TheCall, "extdiv",
3757                             diag::err_ppc_builtin_only_on_arch, "7");
3758   case PPC::BI__builtin_bpermd:
3759     return SemaFeatureCheck(*this, TheCall, "bpermd",
3760                             diag::err_ppc_builtin_only_on_arch, "7");
3761   case PPC::BI__builtin_unpack_vector_int128:
3762     return SemaFeatureCheck(*this, TheCall, "vsx",
3763                             diag::err_ppc_builtin_only_on_arch, "7") ||
3764            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3765   case PPC::BI__builtin_pack_vector_int128:
3766     return SemaFeatureCheck(*this, TheCall, "vsx",
3767                             diag::err_ppc_builtin_only_on_arch, "7");
3768   case PPC::BI__builtin_pdepd:
3769   case PPC::BI__builtin_pextd:
3770     return SemaFeatureCheck(*this, TheCall, "isa-v31-instructions",
3771                             diag::err_ppc_builtin_only_on_arch, "10");
3772   case PPC::BI__builtin_altivec_vgnb:
3773      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3774   case PPC::BI__builtin_altivec_vec_replace_elt:
3775   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3776     QualType VecTy = TheCall->getArg(0)->getType();
3777     QualType EltTy = TheCall->getArg(1)->getType();
3778     unsigned Width = Context.getIntWidth(EltTy);
3779     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3780            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3781   }
3782   case PPC::BI__builtin_vsx_xxeval:
3783      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3784   case PPC::BI__builtin_altivec_vsldbi:
3785      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3786   case PPC::BI__builtin_altivec_vsrdbi:
3787      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3788   case PPC::BI__builtin_vsx_xxpermx:
3789      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3790   case PPC::BI__builtin_ppc_tw:
3791   case PPC::BI__builtin_ppc_tdw:
3792     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3793   case PPC::BI__builtin_ppc_cmpeqb:
3794   case PPC::BI__builtin_ppc_setb:
3795   case PPC::BI__builtin_ppc_maddhd:
3796   case PPC::BI__builtin_ppc_maddhdu:
3797   case PPC::BI__builtin_ppc_maddld:
3798     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3799                             diag::err_ppc_builtin_only_on_arch, "9");
3800   case PPC::BI__builtin_ppc_cmprb:
3801     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3802                             diag::err_ppc_builtin_only_on_arch, "9") ||
3803            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3804   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3805   // be a constant that represents a contiguous bit field.
3806   case PPC::BI__builtin_ppc_rlwnm:
3807     return SemaValueIsRunOfOnes(TheCall, 2);
3808   case PPC::BI__builtin_ppc_rlwimi:
3809   case PPC::BI__builtin_ppc_rldimi:
3810     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3811            SemaValueIsRunOfOnes(TheCall, 3);
3812   case PPC::BI__builtin_ppc_extract_exp:
3813   case PPC::BI__builtin_ppc_extract_sig:
3814   case PPC::BI__builtin_ppc_insert_exp:
3815     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3816                             diag::err_ppc_builtin_only_on_arch, "9");
3817   case PPC::BI__builtin_ppc_addex: {
3818     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3819                          diag::err_ppc_builtin_only_on_arch, "9") ||
3820         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
3821       return true;
3822     // Output warning for reserved values 1 to 3.
3823     int ArgValue =
3824         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
3825     if (ArgValue != 0)
3826       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
3827           << ArgValue;
3828     return false;
3829   }
3830   case PPC::BI__builtin_ppc_mtfsb0:
3831   case PPC::BI__builtin_ppc_mtfsb1:
3832     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3833   case PPC::BI__builtin_ppc_mtfsf:
3834     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3835   case PPC::BI__builtin_ppc_mtfsfi:
3836     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3837            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3838   case PPC::BI__builtin_ppc_alignx:
3839     return SemaBuiltinConstantArgPower2(TheCall, 0);
3840   case PPC::BI__builtin_ppc_rdlam:
3841     return SemaValueIsRunOfOnes(TheCall, 2);
3842   case PPC::BI__builtin_ppc_icbt:
3843   case PPC::BI__builtin_ppc_sthcx:
3844   case PPC::BI__builtin_ppc_stbcx:
3845   case PPC::BI__builtin_ppc_lharx:
3846   case PPC::BI__builtin_ppc_lbarx:
3847     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3848                             diag::err_ppc_builtin_only_on_arch, "8");
3849   case PPC::BI__builtin_vsx_ldrmb:
3850   case PPC::BI__builtin_vsx_strmb:
3851     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3852                             diag::err_ppc_builtin_only_on_arch, "8") ||
3853            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3854   case PPC::BI__builtin_altivec_vcntmbb:
3855   case PPC::BI__builtin_altivec_vcntmbh:
3856   case PPC::BI__builtin_altivec_vcntmbw:
3857   case PPC::BI__builtin_altivec_vcntmbd:
3858     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3859   case PPC::BI__builtin_darn:
3860   case PPC::BI__builtin_darn_raw:
3861   case PPC::BI__builtin_darn_32:
3862     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3863                             diag::err_ppc_builtin_only_on_arch, "9");
3864   case PPC::BI__builtin_vsx_xxgenpcvbm:
3865   case PPC::BI__builtin_vsx_xxgenpcvhm:
3866   case PPC::BI__builtin_vsx_xxgenpcvwm:
3867   case PPC::BI__builtin_vsx_xxgenpcvdm:
3868     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3869   case PPC::BI__builtin_ppc_compare_exp_uo:
3870   case PPC::BI__builtin_ppc_compare_exp_lt:
3871   case PPC::BI__builtin_ppc_compare_exp_gt:
3872   case PPC::BI__builtin_ppc_compare_exp_eq:
3873     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3874                             diag::err_ppc_builtin_only_on_arch, "9") ||
3875            SemaFeatureCheck(*this, TheCall, "vsx",
3876                             diag::err_ppc_builtin_requires_vsx);
3877   case PPC::BI__builtin_ppc_test_data_class: {
3878     // Check if the first argument of the __builtin_ppc_test_data_class call is
3879     // valid. The argument must be either a 'float' or a 'double'.
3880     QualType ArgType = TheCall->getArg(0)->getType();
3881     if (ArgType != QualType(Context.FloatTy) &&
3882         ArgType != QualType(Context.DoubleTy))
3883       return Diag(TheCall->getBeginLoc(),
3884                   diag::err_ppc_invalid_test_data_class_type);
3885     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3886                             diag::err_ppc_builtin_only_on_arch, "9") ||
3887            SemaFeatureCheck(*this, TheCall, "vsx",
3888                             diag::err_ppc_builtin_requires_vsx) ||
3889            SemaBuiltinConstantArgRange(TheCall, 1, 0, 127);
3890   }
3891   case PPC::BI__builtin_ppc_load8r:
3892   case PPC::BI__builtin_ppc_store8r:
3893     return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions",
3894                             diag::err_ppc_builtin_only_on_arch, "7");
3895 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc)                                 \
3896   case PPC::BI__builtin_##Name:                                                \
3897     return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types);
3898 #include "clang/Basic/BuiltinsPPC.def"
3899   }
3900   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3901 }
3902 
3903 // Check if the given type is a non-pointer PPC MMA type. This function is used
3904 // in Sema to prevent invalid uses of restricted PPC MMA types.
3905 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3906   if (Type->isPointerType() || Type->isArrayType())
3907     return false;
3908 
3909   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3910 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3911   if (false
3912 #include "clang/Basic/PPCTypes.def"
3913      ) {
3914     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3915     return true;
3916   }
3917   return false;
3918 }
3919 
3920 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3921                                           CallExpr *TheCall) {
3922   // position of memory order and scope arguments in the builtin
3923   unsigned OrderIndex, ScopeIndex;
3924   switch (BuiltinID) {
3925   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3926   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3927   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3928   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3929     OrderIndex = 2;
3930     ScopeIndex = 3;
3931     break;
3932   case AMDGPU::BI__builtin_amdgcn_fence:
3933     OrderIndex = 0;
3934     ScopeIndex = 1;
3935     break;
3936   default:
3937     return false;
3938   }
3939 
3940   ExprResult Arg = TheCall->getArg(OrderIndex);
3941   auto ArgExpr = Arg.get();
3942   Expr::EvalResult ArgResult;
3943 
3944   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3945     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3946            << ArgExpr->getType();
3947   auto Ord = ArgResult.Val.getInt().getZExtValue();
3948 
3949   // Check validity of memory ordering as per C11 / C++11's memody model.
3950   // Only fence needs check. Atomic dec/inc allow all memory orders.
3951   if (!llvm::isValidAtomicOrderingCABI(Ord))
3952     return Diag(ArgExpr->getBeginLoc(),
3953                 diag::warn_atomic_op_has_invalid_memory_order)
3954            << ArgExpr->getSourceRange();
3955   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3956   case llvm::AtomicOrderingCABI::relaxed:
3957   case llvm::AtomicOrderingCABI::consume:
3958     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3959       return Diag(ArgExpr->getBeginLoc(),
3960                   diag::warn_atomic_op_has_invalid_memory_order)
3961              << ArgExpr->getSourceRange();
3962     break;
3963   case llvm::AtomicOrderingCABI::acquire:
3964   case llvm::AtomicOrderingCABI::release:
3965   case llvm::AtomicOrderingCABI::acq_rel:
3966   case llvm::AtomicOrderingCABI::seq_cst:
3967     break;
3968   }
3969 
3970   Arg = TheCall->getArg(ScopeIndex);
3971   ArgExpr = Arg.get();
3972   Expr::EvalResult ArgResult1;
3973   // Check that sync scope is a constant literal
3974   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3975     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3976            << ArgExpr->getType();
3977 
3978   return false;
3979 }
3980 
3981 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3982   llvm::APSInt Result;
3983 
3984   // We can't check the value of a dependent argument.
3985   Expr *Arg = TheCall->getArg(ArgNum);
3986   if (Arg->isTypeDependent() || Arg->isValueDependent())
3987     return false;
3988 
3989   // Check constant-ness first.
3990   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3991     return true;
3992 
3993   int64_t Val = Result.getSExtValue();
3994   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3995     return false;
3996 
3997   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3998          << Arg->getSourceRange();
3999 }
4000 
4001 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
4002                                          unsigned BuiltinID,
4003                                          CallExpr *TheCall) {
4004   // CodeGenFunction can also detect this, but this gives a better error
4005   // message.
4006   bool FeatureMissing = false;
4007   SmallVector<StringRef> ReqFeatures;
4008   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
4009   Features.split(ReqFeatures, ',');
4010 
4011   // Check if each required feature is included
4012   for (StringRef F : ReqFeatures) {
4013     SmallVector<StringRef> ReqOpFeatures;
4014     F.split(ReqOpFeatures, '|');
4015     bool HasFeature = false;
4016     for (StringRef OF : ReqOpFeatures) {
4017       if (TI.hasFeature(OF)) {
4018         HasFeature = true;
4019         continue;
4020       }
4021     }
4022 
4023     if (!HasFeature) {
4024       std::string FeatureStrs;
4025       for (StringRef OF : ReqOpFeatures) {
4026         // If the feature is 64bit, alter the string so it will print better in
4027         // the diagnostic.
4028         if (OF == "64bit")
4029           OF = "RV64";
4030 
4031         // Convert features like "zbr" and "experimental-zbr" to "Zbr".
4032         OF.consume_front("experimental-");
4033         std::string FeatureStr = OF.str();
4034         FeatureStr[0] = std::toupper(FeatureStr[0]);
4035         // Combine strings.
4036         FeatureStrs += FeatureStrs == "" ? "" : ", ";
4037         FeatureStrs += "'";
4038         FeatureStrs += FeatureStr;
4039         FeatureStrs += "'";
4040       }
4041       // Error message
4042       FeatureMissing = true;
4043       Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
4044           << TheCall->getSourceRange() << StringRef(FeatureStrs);
4045     }
4046   }
4047 
4048   if (FeatureMissing)
4049     return true;
4050 
4051   switch (BuiltinID) {
4052   case RISCVVector::BI__builtin_rvv_vsetvli:
4053     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
4054            CheckRISCVLMUL(TheCall, 2);
4055   case RISCVVector::BI__builtin_rvv_vsetvlimax:
4056     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
4057            CheckRISCVLMUL(TheCall, 1);
4058   }
4059 
4060   return false;
4061 }
4062 
4063 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
4064                                            CallExpr *TheCall) {
4065   if (BuiltinID == SystemZ::BI__builtin_tabort) {
4066     Expr *Arg = TheCall->getArg(0);
4067     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
4068       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
4069         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
4070                << Arg->getSourceRange();
4071   }
4072 
4073   // For intrinsics which take an immediate value as part of the instruction,
4074   // range check them here.
4075   unsigned i = 0, l = 0, u = 0;
4076   switch (BuiltinID) {
4077   default: return false;
4078   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
4079   case SystemZ::BI__builtin_s390_verimb:
4080   case SystemZ::BI__builtin_s390_verimh:
4081   case SystemZ::BI__builtin_s390_verimf:
4082   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
4083   case SystemZ::BI__builtin_s390_vfaeb:
4084   case SystemZ::BI__builtin_s390_vfaeh:
4085   case SystemZ::BI__builtin_s390_vfaef:
4086   case SystemZ::BI__builtin_s390_vfaebs:
4087   case SystemZ::BI__builtin_s390_vfaehs:
4088   case SystemZ::BI__builtin_s390_vfaefs:
4089   case SystemZ::BI__builtin_s390_vfaezb:
4090   case SystemZ::BI__builtin_s390_vfaezh:
4091   case SystemZ::BI__builtin_s390_vfaezf:
4092   case SystemZ::BI__builtin_s390_vfaezbs:
4093   case SystemZ::BI__builtin_s390_vfaezhs:
4094   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
4095   case SystemZ::BI__builtin_s390_vfisb:
4096   case SystemZ::BI__builtin_s390_vfidb:
4097     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
4098            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
4099   case SystemZ::BI__builtin_s390_vftcisb:
4100   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
4101   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
4102   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
4103   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
4104   case SystemZ::BI__builtin_s390_vstrcb:
4105   case SystemZ::BI__builtin_s390_vstrch:
4106   case SystemZ::BI__builtin_s390_vstrcf:
4107   case SystemZ::BI__builtin_s390_vstrczb:
4108   case SystemZ::BI__builtin_s390_vstrczh:
4109   case SystemZ::BI__builtin_s390_vstrczf:
4110   case SystemZ::BI__builtin_s390_vstrcbs:
4111   case SystemZ::BI__builtin_s390_vstrchs:
4112   case SystemZ::BI__builtin_s390_vstrcfs:
4113   case SystemZ::BI__builtin_s390_vstrczbs:
4114   case SystemZ::BI__builtin_s390_vstrczhs:
4115   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
4116   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
4117   case SystemZ::BI__builtin_s390_vfminsb:
4118   case SystemZ::BI__builtin_s390_vfmaxsb:
4119   case SystemZ::BI__builtin_s390_vfmindb:
4120   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
4121   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
4122   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
4123   case SystemZ::BI__builtin_s390_vclfnhs:
4124   case SystemZ::BI__builtin_s390_vclfnls:
4125   case SystemZ::BI__builtin_s390_vcfn:
4126   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
4127   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
4128   }
4129   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
4130 }
4131 
4132 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
4133 /// This checks that the target supports __builtin_cpu_supports and
4134 /// that the string argument is constant and valid.
4135 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
4136                                    CallExpr *TheCall) {
4137   Expr *Arg = TheCall->getArg(0);
4138 
4139   // Check if the argument is a string literal.
4140   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4141     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4142            << Arg->getSourceRange();
4143 
4144   // Check the contents of the string.
4145   StringRef Feature =
4146       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4147   if (!TI.validateCpuSupports(Feature))
4148     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
4149            << Arg->getSourceRange();
4150   return false;
4151 }
4152 
4153 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
4154 /// This checks that the target supports __builtin_cpu_is and
4155 /// that the string argument is constant and valid.
4156 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
4157   Expr *Arg = TheCall->getArg(0);
4158 
4159   // Check if the argument is a string literal.
4160   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4161     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4162            << Arg->getSourceRange();
4163 
4164   // Check the contents of the string.
4165   StringRef Feature =
4166       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4167   if (!TI.validateCpuIs(Feature))
4168     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
4169            << Arg->getSourceRange();
4170   return false;
4171 }
4172 
4173 // Check if the rounding mode is legal.
4174 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
4175   // Indicates if this instruction has rounding control or just SAE.
4176   bool HasRC = false;
4177 
4178   unsigned ArgNum = 0;
4179   switch (BuiltinID) {
4180   default:
4181     return false;
4182   case X86::BI__builtin_ia32_vcvttsd2si32:
4183   case X86::BI__builtin_ia32_vcvttsd2si64:
4184   case X86::BI__builtin_ia32_vcvttsd2usi32:
4185   case X86::BI__builtin_ia32_vcvttsd2usi64:
4186   case X86::BI__builtin_ia32_vcvttss2si32:
4187   case X86::BI__builtin_ia32_vcvttss2si64:
4188   case X86::BI__builtin_ia32_vcvttss2usi32:
4189   case X86::BI__builtin_ia32_vcvttss2usi64:
4190   case X86::BI__builtin_ia32_vcvttsh2si32:
4191   case X86::BI__builtin_ia32_vcvttsh2si64:
4192   case X86::BI__builtin_ia32_vcvttsh2usi32:
4193   case X86::BI__builtin_ia32_vcvttsh2usi64:
4194     ArgNum = 1;
4195     break;
4196   case X86::BI__builtin_ia32_maxpd512:
4197   case X86::BI__builtin_ia32_maxps512:
4198   case X86::BI__builtin_ia32_minpd512:
4199   case X86::BI__builtin_ia32_minps512:
4200   case X86::BI__builtin_ia32_maxph512:
4201   case X86::BI__builtin_ia32_minph512:
4202     ArgNum = 2;
4203     break;
4204   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
4205   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
4206   case X86::BI__builtin_ia32_cvtps2pd512_mask:
4207   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
4208   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
4209   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
4210   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
4211   case X86::BI__builtin_ia32_cvttps2dq512_mask:
4212   case X86::BI__builtin_ia32_cvttps2qq512_mask:
4213   case X86::BI__builtin_ia32_cvttps2udq512_mask:
4214   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
4215   case X86::BI__builtin_ia32_vcvttph2w512_mask:
4216   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
4217   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
4218   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
4219   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
4220   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
4221   case X86::BI__builtin_ia32_exp2pd_mask:
4222   case X86::BI__builtin_ia32_exp2ps_mask:
4223   case X86::BI__builtin_ia32_getexppd512_mask:
4224   case X86::BI__builtin_ia32_getexpps512_mask:
4225   case X86::BI__builtin_ia32_getexpph512_mask:
4226   case X86::BI__builtin_ia32_rcp28pd_mask:
4227   case X86::BI__builtin_ia32_rcp28ps_mask:
4228   case X86::BI__builtin_ia32_rsqrt28pd_mask:
4229   case X86::BI__builtin_ia32_rsqrt28ps_mask:
4230   case X86::BI__builtin_ia32_vcomisd:
4231   case X86::BI__builtin_ia32_vcomiss:
4232   case X86::BI__builtin_ia32_vcomish:
4233   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
4234     ArgNum = 3;
4235     break;
4236   case X86::BI__builtin_ia32_cmppd512_mask:
4237   case X86::BI__builtin_ia32_cmpps512_mask:
4238   case X86::BI__builtin_ia32_cmpsd_mask:
4239   case X86::BI__builtin_ia32_cmpss_mask:
4240   case X86::BI__builtin_ia32_cmpsh_mask:
4241   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
4242   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
4243   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
4244   case X86::BI__builtin_ia32_getexpsd128_round_mask:
4245   case X86::BI__builtin_ia32_getexpss128_round_mask:
4246   case X86::BI__builtin_ia32_getexpsh128_round_mask:
4247   case X86::BI__builtin_ia32_getmantpd512_mask:
4248   case X86::BI__builtin_ia32_getmantps512_mask:
4249   case X86::BI__builtin_ia32_getmantph512_mask:
4250   case X86::BI__builtin_ia32_maxsd_round_mask:
4251   case X86::BI__builtin_ia32_maxss_round_mask:
4252   case X86::BI__builtin_ia32_maxsh_round_mask:
4253   case X86::BI__builtin_ia32_minsd_round_mask:
4254   case X86::BI__builtin_ia32_minss_round_mask:
4255   case X86::BI__builtin_ia32_minsh_round_mask:
4256   case X86::BI__builtin_ia32_rcp28sd_round_mask:
4257   case X86::BI__builtin_ia32_rcp28ss_round_mask:
4258   case X86::BI__builtin_ia32_reducepd512_mask:
4259   case X86::BI__builtin_ia32_reduceps512_mask:
4260   case X86::BI__builtin_ia32_reduceph512_mask:
4261   case X86::BI__builtin_ia32_rndscalepd_mask:
4262   case X86::BI__builtin_ia32_rndscaleps_mask:
4263   case X86::BI__builtin_ia32_rndscaleph_mask:
4264   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
4265   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
4266     ArgNum = 4;
4267     break;
4268   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4269   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4270   case X86::BI__builtin_ia32_fixupimmps512_mask:
4271   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4272   case X86::BI__builtin_ia32_fixupimmsd_mask:
4273   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4274   case X86::BI__builtin_ia32_fixupimmss_mask:
4275   case X86::BI__builtin_ia32_fixupimmss_maskz:
4276   case X86::BI__builtin_ia32_getmantsd_round_mask:
4277   case X86::BI__builtin_ia32_getmantss_round_mask:
4278   case X86::BI__builtin_ia32_getmantsh_round_mask:
4279   case X86::BI__builtin_ia32_rangepd512_mask:
4280   case X86::BI__builtin_ia32_rangeps512_mask:
4281   case X86::BI__builtin_ia32_rangesd128_round_mask:
4282   case X86::BI__builtin_ia32_rangess128_round_mask:
4283   case X86::BI__builtin_ia32_reducesd_mask:
4284   case X86::BI__builtin_ia32_reducess_mask:
4285   case X86::BI__builtin_ia32_reducesh_mask:
4286   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4287   case X86::BI__builtin_ia32_rndscaless_round_mask:
4288   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4289     ArgNum = 5;
4290     break;
4291   case X86::BI__builtin_ia32_vcvtsd2si64:
4292   case X86::BI__builtin_ia32_vcvtsd2si32:
4293   case X86::BI__builtin_ia32_vcvtsd2usi32:
4294   case X86::BI__builtin_ia32_vcvtsd2usi64:
4295   case X86::BI__builtin_ia32_vcvtss2si32:
4296   case X86::BI__builtin_ia32_vcvtss2si64:
4297   case X86::BI__builtin_ia32_vcvtss2usi32:
4298   case X86::BI__builtin_ia32_vcvtss2usi64:
4299   case X86::BI__builtin_ia32_vcvtsh2si32:
4300   case X86::BI__builtin_ia32_vcvtsh2si64:
4301   case X86::BI__builtin_ia32_vcvtsh2usi32:
4302   case X86::BI__builtin_ia32_vcvtsh2usi64:
4303   case X86::BI__builtin_ia32_sqrtpd512:
4304   case X86::BI__builtin_ia32_sqrtps512:
4305   case X86::BI__builtin_ia32_sqrtph512:
4306     ArgNum = 1;
4307     HasRC = true;
4308     break;
4309   case X86::BI__builtin_ia32_addph512:
4310   case X86::BI__builtin_ia32_divph512:
4311   case X86::BI__builtin_ia32_mulph512:
4312   case X86::BI__builtin_ia32_subph512:
4313   case X86::BI__builtin_ia32_addpd512:
4314   case X86::BI__builtin_ia32_addps512:
4315   case X86::BI__builtin_ia32_divpd512:
4316   case X86::BI__builtin_ia32_divps512:
4317   case X86::BI__builtin_ia32_mulpd512:
4318   case X86::BI__builtin_ia32_mulps512:
4319   case X86::BI__builtin_ia32_subpd512:
4320   case X86::BI__builtin_ia32_subps512:
4321   case X86::BI__builtin_ia32_cvtsi2sd64:
4322   case X86::BI__builtin_ia32_cvtsi2ss32:
4323   case X86::BI__builtin_ia32_cvtsi2ss64:
4324   case X86::BI__builtin_ia32_cvtusi2sd64:
4325   case X86::BI__builtin_ia32_cvtusi2ss32:
4326   case X86::BI__builtin_ia32_cvtusi2ss64:
4327   case X86::BI__builtin_ia32_vcvtusi2sh:
4328   case X86::BI__builtin_ia32_vcvtusi642sh:
4329   case X86::BI__builtin_ia32_vcvtsi2sh:
4330   case X86::BI__builtin_ia32_vcvtsi642sh:
4331     ArgNum = 2;
4332     HasRC = true;
4333     break;
4334   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
4335   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
4336   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
4337   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
4338   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
4339   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
4340   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
4341   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
4342   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
4343   case X86::BI__builtin_ia32_cvtps2dq512_mask:
4344   case X86::BI__builtin_ia32_cvtps2qq512_mask:
4345   case X86::BI__builtin_ia32_cvtps2udq512_mask:
4346   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
4347   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
4348   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
4349   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
4350   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
4351   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
4352   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
4353   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
4354   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
4355   case X86::BI__builtin_ia32_vcvtph2w512_mask:
4356   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
4357   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
4358   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
4359   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
4360   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
4361   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
4362   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
4363     ArgNum = 3;
4364     HasRC = true;
4365     break;
4366   case X86::BI__builtin_ia32_addsh_round_mask:
4367   case X86::BI__builtin_ia32_addss_round_mask:
4368   case X86::BI__builtin_ia32_addsd_round_mask:
4369   case X86::BI__builtin_ia32_divsh_round_mask:
4370   case X86::BI__builtin_ia32_divss_round_mask:
4371   case X86::BI__builtin_ia32_divsd_round_mask:
4372   case X86::BI__builtin_ia32_mulsh_round_mask:
4373   case X86::BI__builtin_ia32_mulss_round_mask:
4374   case X86::BI__builtin_ia32_mulsd_round_mask:
4375   case X86::BI__builtin_ia32_subsh_round_mask:
4376   case X86::BI__builtin_ia32_subss_round_mask:
4377   case X86::BI__builtin_ia32_subsd_round_mask:
4378   case X86::BI__builtin_ia32_scalefph512_mask:
4379   case X86::BI__builtin_ia32_scalefpd512_mask:
4380   case X86::BI__builtin_ia32_scalefps512_mask:
4381   case X86::BI__builtin_ia32_scalefsd_round_mask:
4382   case X86::BI__builtin_ia32_scalefss_round_mask:
4383   case X86::BI__builtin_ia32_scalefsh_round_mask:
4384   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4385   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4386   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4387   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4388   case X86::BI__builtin_ia32_sqrtss_round_mask:
4389   case X86::BI__builtin_ia32_sqrtsh_round_mask:
4390   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4391   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4392   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4393   case X86::BI__builtin_ia32_vfmaddss3_mask:
4394   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4395   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4396   case X86::BI__builtin_ia32_vfmaddsh3_mask:
4397   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4398   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4399   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4400   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4401   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4402   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4403   case X86::BI__builtin_ia32_vfmaddps512_mask:
4404   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4405   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4406   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4407   case X86::BI__builtin_ia32_vfmaddph512_mask:
4408   case X86::BI__builtin_ia32_vfmaddph512_maskz:
4409   case X86::BI__builtin_ia32_vfmaddph512_mask3:
4410   case X86::BI__builtin_ia32_vfmsubph512_mask3:
4411   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4412   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4413   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4414   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4415   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4416   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4417   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4418   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4419   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4420   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4421   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4422   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4423   case X86::BI__builtin_ia32_vfmaddcsh_mask:
4424   case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
4425   case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
4426   case X86::BI__builtin_ia32_vfmaddcph512_mask:
4427   case X86::BI__builtin_ia32_vfmaddcph512_maskz:
4428   case X86::BI__builtin_ia32_vfmaddcph512_mask3:
4429   case X86::BI__builtin_ia32_vfcmaddcsh_mask:
4430   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
4431   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
4432   case X86::BI__builtin_ia32_vfcmaddcph512_mask:
4433   case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
4434   case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
4435   case X86::BI__builtin_ia32_vfmulcsh_mask:
4436   case X86::BI__builtin_ia32_vfmulcph512_mask:
4437   case X86::BI__builtin_ia32_vfcmulcsh_mask:
4438   case X86::BI__builtin_ia32_vfcmulcph512_mask:
4439     ArgNum = 4;
4440     HasRC = true;
4441     break;
4442   }
4443 
4444   llvm::APSInt Result;
4445 
4446   // We can't check the value of a dependent argument.
4447   Expr *Arg = TheCall->getArg(ArgNum);
4448   if (Arg->isTypeDependent() || Arg->isValueDependent())
4449     return false;
4450 
4451   // Check constant-ness first.
4452   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4453     return true;
4454 
4455   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4456   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4457   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4458   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4459   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4460       Result == 8/*ROUND_NO_EXC*/ ||
4461       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4462       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4463     return false;
4464 
4465   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4466          << Arg->getSourceRange();
4467 }
4468 
4469 // Check if the gather/scatter scale is legal.
4470 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4471                                              CallExpr *TheCall) {
4472   unsigned ArgNum = 0;
4473   switch (BuiltinID) {
4474   default:
4475     return false;
4476   case X86::BI__builtin_ia32_gatherpfdpd:
4477   case X86::BI__builtin_ia32_gatherpfdps:
4478   case X86::BI__builtin_ia32_gatherpfqpd:
4479   case X86::BI__builtin_ia32_gatherpfqps:
4480   case X86::BI__builtin_ia32_scatterpfdpd:
4481   case X86::BI__builtin_ia32_scatterpfdps:
4482   case X86::BI__builtin_ia32_scatterpfqpd:
4483   case X86::BI__builtin_ia32_scatterpfqps:
4484     ArgNum = 3;
4485     break;
4486   case X86::BI__builtin_ia32_gatherd_pd:
4487   case X86::BI__builtin_ia32_gatherd_pd256:
4488   case X86::BI__builtin_ia32_gatherq_pd:
4489   case X86::BI__builtin_ia32_gatherq_pd256:
4490   case X86::BI__builtin_ia32_gatherd_ps:
4491   case X86::BI__builtin_ia32_gatherd_ps256:
4492   case X86::BI__builtin_ia32_gatherq_ps:
4493   case X86::BI__builtin_ia32_gatherq_ps256:
4494   case X86::BI__builtin_ia32_gatherd_q:
4495   case X86::BI__builtin_ia32_gatherd_q256:
4496   case X86::BI__builtin_ia32_gatherq_q:
4497   case X86::BI__builtin_ia32_gatherq_q256:
4498   case X86::BI__builtin_ia32_gatherd_d:
4499   case X86::BI__builtin_ia32_gatherd_d256:
4500   case X86::BI__builtin_ia32_gatherq_d:
4501   case X86::BI__builtin_ia32_gatherq_d256:
4502   case X86::BI__builtin_ia32_gather3div2df:
4503   case X86::BI__builtin_ia32_gather3div2di:
4504   case X86::BI__builtin_ia32_gather3div4df:
4505   case X86::BI__builtin_ia32_gather3div4di:
4506   case X86::BI__builtin_ia32_gather3div4sf:
4507   case X86::BI__builtin_ia32_gather3div4si:
4508   case X86::BI__builtin_ia32_gather3div8sf:
4509   case X86::BI__builtin_ia32_gather3div8si:
4510   case X86::BI__builtin_ia32_gather3siv2df:
4511   case X86::BI__builtin_ia32_gather3siv2di:
4512   case X86::BI__builtin_ia32_gather3siv4df:
4513   case X86::BI__builtin_ia32_gather3siv4di:
4514   case X86::BI__builtin_ia32_gather3siv4sf:
4515   case X86::BI__builtin_ia32_gather3siv4si:
4516   case X86::BI__builtin_ia32_gather3siv8sf:
4517   case X86::BI__builtin_ia32_gather3siv8si:
4518   case X86::BI__builtin_ia32_gathersiv8df:
4519   case X86::BI__builtin_ia32_gathersiv16sf:
4520   case X86::BI__builtin_ia32_gatherdiv8df:
4521   case X86::BI__builtin_ia32_gatherdiv16sf:
4522   case X86::BI__builtin_ia32_gathersiv8di:
4523   case X86::BI__builtin_ia32_gathersiv16si:
4524   case X86::BI__builtin_ia32_gatherdiv8di:
4525   case X86::BI__builtin_ia32_gatherdiv16si:
4526   case X86::BI__builtin_ia32_scatterdiv2df:
4527   case X86::BI__builtin_ia32_scatterdiv2di:
4528   case X86::BI__builtin_ia32_scatterdiv4df:
4529   case X86::BI__builtin_ia32_scatterdiv4di:
4530   case X86::BI__builtin_ia32_scatterdiv4sf:
4531   case X86::BI__builtin_ia32_scatterdiv4si:
4532   case X86::BI__builtin_ia32_scatterdiv8sf:
4533   case X86::BI__builtin_ia32_scatterdiv8si:
4534   case X86::BI__builtin_ia32_scattersiv2df:
4535   case X86::BI__builtin_ia32_scattersiv2di:
4536   case X86::BI__builtin_ia32_scattersiv4df:
4537   case X86::BI__builtin_ia32_scattersiv4di:
4538   case X86::BI__builtin_ia32_scattersiv4sf:
4539   case X86::BI__builtin_ia32_scattersiv4si:
4540   case X86::BI__builtin_ia32_scattersiv8sf:
4541   case X86::BI__builtin_ia32_scattersiv8si:
4542   case X86::BI__builtin_ia32_scattersiv8df:
4543   case X86::BI__builtin_ia32_scattersiv16sf:
4544   case X86::BI__builtin_ia32_scatterdiv8df:
4545   case X86::BI__builtin_ia32_scatterdiv16sf:
4546   case X86::BI__builtin_ia32_scattersiv8di:
4547   case X86::BI__builtin_ia32_scattersiv16si:
4548   case X86::BI__builtin_ia32_scatterdiv8di:
4549   case X86::BI__builtin_ia32_scatterdiv16si:
4550     ArgNum = 4;
4551     break;
4552   }
4553 
4554   llvm::APSInt Result;
4555 
4556   // We can't check the value of a dependent argument.
4557   Expr *Arg = TheCall->getArg(ArgNum);
4558   if (Arg->isTypeDependent() || Arg->isValueDependent())
4559     return false;
4560 
4561   // Check constant-ness first.
4562   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4563     return true;
4564 
4565   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4566     return false;
4567 
4568   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4569          << Arg->getSourceRange();
4570 }
4571 
4572 enum { TileRegLow = 0, TileRegHigh = 7 };
4573 
4574 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4575                                              ArrayRef<int> ArgNums) {
4576   for (int ArgNum : ArgNums) {
4577     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4578       return true;
4579   }
4580   return false;
4581 }
4582 
4583 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4584                                         ArrayRef<int> ArgNums) {
4585   // Because the max number of tile register is TileRegHigh + 1, so here we use
4586   // each bit to represent the usage of them in bitset.
4587   std::bitset<TileRegHigh + 1> ArgValues;
4588   for (int ArgNum : ArgNums) {
4589     Expr *Arg = TheCall->getArg(ArgNum);
4590     if (Arg->isTypeDependent() || Arg->isValueDependent())
4591       continue;
4592 
4593     llvm::APSInt Result;
4594     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4595       return true;
4596     int ArgExtValue = Result.getExtValue();
4597     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4598            "Incorrect tile register num.");
4599     if (ArgValues.test(ArgExtValue))
4600       return Diag(TheCall->getBeginLoc(),
4601                   diag::err_x86_builtin_tile_arg_duplicate)
4602              << TheCall->getArg(ArgNum)->getSourceRange();
4603     ArgValues.set(ArgExtValue);
4604   }
4605   return false;
4606 }
4607 
4608 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4609                                                 ArrayRef<int> ArgNums) {
4610   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4611          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4612 }
4613 
4614 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4615   switch (BuiltinID) {
4616   default:
4617     return false;
4618   case X86::BI__builtin_ia32_tileloadd64:
4619   case X86::BI__builtin_ia32_tileloaddt164:
4620   case X86::BI__builtin_ia32_tilestored64:
4621   case X86::BI__builtin_ia32_tilezero:
4622     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4623   case X86::BI__builtin_ia32_tdpbssd:
4624   case X86::BI__builtin_ia32_tdpbsud:
4625   case X86::BI__builtin_ia32_tdpbusd:
4626   case X86::BI__builtin_ia32_tdpbuud:
4627   case X86::BI__builtin_ia32_tdpbf16ps:
4628     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4629   }
4630 }
4631 static bool isX86_32Builtin(unsigned BuiltinID) {
4632   // These builtins only work on x86-32 targets.
4633   switch (BuiltinID) {
4634   case X86::BI__builtin_ia32_readeflags_u32:
4635   case X86::BI__builtin_ia32_writeeflags_u32:
4636     return true;
4637   }
4638 
4639   return false;
4640 }
4641 
4642 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4643                                        CallExpr *TheCall) {
4644   if (BuiltinID == X86::BI__builtin_cpu_supports)
4645     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4646 
4647   if (BuiltinID == X86::BI__builtin_cpu_is)
4648     return SemaBuiltinCpuIs(*this, TI, TheCall);
4649 
4650   // Check for 32-bit only builtins on a 64-bit target.
4651   const llvm::Triple &TT = TI.getTriple();
4652   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4653     return Diag(TheCall->getCallee()->getBeginLoc(),
4654                 diag::err_32_bit_builtin_64_bit_tgt);
4655 
4656   // If the intrinsic has rounding or SAE make sure its valid.
4657   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4658     return true;
4659 
4660   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4661   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4662     return true;
4663 
4664   // If the intrinsic has a tile arguments, make sure they are valid.
4665   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4666     return true;
4667 
4668   // For intrinsics which take an immediate value as part of the instruction,
4669   // range check them here.
4670   int i = 0, l = 0, u = 0;
4671   switch (BuiltinID) {
4672   default:
4673     return false;
4674   case X86::BI__builtin_ia32_vec_ext_v2si:
4675   case X86::BI__builtin_ia32_vec_ext_v2di:
4676   case X86::BI__builtin_ia32_vextractf128_pd256:
4677   case X86::BI__builtin_ia32_vextractf128_ps256:
4678   case X86::BI__builtin_ia32_vextractf128_si256:
4679   case X86::BI__builtin_ia32_extract128i256:
4680   case X86::BI__builtin_ia32_extractf64x4_mask:
4681   case X86::BI__builtin_ia32_extracti64x4_mask:
4682   case X86::BI__builtin_ia32_extractf32x8_mask:
4683   case X86::BI__builtin_ia32_extracti32x8_mask:
4684   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4685   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4686   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4687   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4688     i = 1; l = 0; u = 1;
4689     break;
4690   case X86::BI__builtin_ia32_vec_set_v2di:
4691   case X86::BI__builtin_ia32_vinsertf128_pd256:
4692   case X86::BI__builtin_ia32_vinsertf128_ps256:
4693   case X86::BI__builtin_ia32_vinsertf128_si256:
4694   case X86::BI__builtin_ia32_insert128i256:
4695   case X86::BI__builtin_ia32_insertf32x8:
4696   case X86::BI__builtin_ia32_inserti32x8:
4697   case X86::BI__builtin_ia32_insertf64x4:
4698   case X86::BI__builtin_ia32_inserti64x4:
4699   case X86::BI__builtin_ia32_insertf64x2_256:
4700   case X86::BI__builtin_ia32_inserti64x2_256:
4701   case X86::BI__builtin_ia32_insertf32x4_256:
4702   case X86::BI__builtin_ia32_inserti32x4_256:
4703     i = 2; l = 0; u = 1;
4704     break;
4705   case X86::BI__builtin_ia32_vpermilpd:
4706   case X86::BI__builtin_ia32_vec_ext_v4hi:
4707   case X86::BI__builtin_ia32_vec_ext_v4si:
4708   case X86::BI__builtin_ia32_vec_ext_v4sf:
4709   case X86::BI__builtin_ia32_vec_ext_v4di:
4710   case X86::BI__builtin_ia32_extractf32x4_mask:
4711   case X86::BI__builtin_ia32_extracti32x4_mask:
4712   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4713   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4714     i = 1; l = 0; u = 3;
4715     break;
4716   case X86::BI_mm_prefetch:
4717   case X86::BI__builtin_ia32_vec_ext_v8hi:
4718   case X86::BI__builtin_ia32_vec_ext_v8si:
4719     i = 1; l = 0; u = 7;
4720     break;
4721   case X86::BI__builtin_ia32_sha1rnds4:
4722   case X86::BI__builtin_ia32_blendpd:
4723   case X86::BI__builtin_ia32_shufpd:
4724   case X86::BI__builtin_ia32_vec_set_v4hi:
4725   case X86::BI__builtin_ia32_vec_set_v4si:
4726   case X86::BI__builtin_ia32_vec_set_v4di:
4727   case X86::BI__builtin_ia32_shuf_f32x4_256:
4728   case X86::BI__builtin_ia32_shuf_f64x2_256:
4729   case X86::BI__builtin_ia32_shuf_i32x4_256:
4730   case X86::BI__builtin_ia32_shuf_i64x2_256:
4731   case X86::BI__builtin_ia32_insertf64x2_512:
4732   case X86::BI__builtin_ia32_inserti64x2_512:
4733   case X86::BI__builtin_ia32_insertf32x4:
4734   case X86::BI__builtin_ia32_inserti32x4:
4735     i = 2; l = 0; u = 3;
4736     break;
4737   case X86::BI__builtin_ia32_vpermil2pd:
4738   case X86::BI__builtin_ia32_vpermil2pd256:
4739   case X86::BI__builtin_ia32_vpermil2ps:
4740   case X86::BI__builtin_ia32_vpermil2ps256:
4741     i = 3; l = 0; u = 3;
4742     break;
4743   case X86::BI__builtin_ia32_cmpb128_mask:
4744   case X86::BI__builtin_ia32_cmpw128_mask:
4745   case X86::BI__builtin_ia32_cmpd128_mask:
4746   case X86::BI__builtin_ia32_cmpq128_mask:
4747   case X86::BI__builtin_ia32_cmpb256_mask:
4748   case X86::BI__builtin_ia32_cmpw256_mask:
4749   case X86::BI__builtin_ia32_cmpd256_mask:
4750   case X86::BI__builtin_ia32_cmpq256_mask:
4751   case X86::BI__builtin_ia32_cmpb512_mask:
4752   case X86::BI__builtin_ia32_cmpw512_mask:
4753   case X86::BI__builtin_ia32_cmpd512_mask:
4754   case X86::BI__builtin_ia32_cmpq512_mask:
4755   case X86::BI__builtin_ia32_ucmpb128_mask:
4756   case X86::BI__builtin_ia32_ucmpw128_mask:
4757   case X86::BI__builtin_ia32_ucmpd128_mask:
4758   case X86::BI__builtin_ia32_ucmpq128_mask:
4759   case X86::BI__builtin_ia32_ucmpb256_mask:
4760   case X86::BI__builtin_ia32_ucmpw256_mask:
4761   case X86::BI__builtin_ia32_ucmpd256_mask:
4762   case X86::BI__builtin_ia32_ucmpq256_mask:
4763   case X86::BI__builtin_ia32_ucmpb512_mask:
4764   case X86::BI__builtin_ia32_ucmpw512_mask:
4765   case X86::BI__builtin_ia32_ucmpd512_mask:
4766   case X86::BI__builtin_ia32_ucmpq512_mask:
4767   case X86::BI__builtin_ia32_vpcomub:
4768   case X86::BI__builtin_ia32_vpcomuw:
4769   case X86::BI__builtin_ia32_vpcomud:
4770   case X86::BI__builtin_ia32_vpcomuq:
4771   case X86::BI__builtin_ia32_vpcomb:
4772   case X86::BI__builtin_ia32_vpcomw:
4773   case X86::BI__builtin_ia32_vpcomd:
4774   case X86::BI__builtin_ia32_vpcomq:
4775   case X86::BI__builtin_ia32_vec_set_v8hi:
4776   case X86::BI__builtin_ia32_vec_set_v8si:
4777     i = 2; l = 0; u = 7;
4778     break;
4779   case X86::BI__builtin_ia32_vpermilpd256:
4780   case X86::BI__builtin_ia32_roundps:
4781   case X86::BI__builtin_ia32_roundpd:
4782   case X86::BI__builtin_ia32_roundps256:
4783   case X86::BI__builtin_ia32_roundpd256:
4784   case X86::BI__builtin_ia32_getmantpd128_mask:
4785   case X86::BI__builtin_ia32_getmantpd256_mask:
4786   case X86::BI__builtin_ia32_getmantps128_mask:
4787   case X86::BI__builtin_ia32_getmantps256_mask:
4788   case X86::BI__builtin_ia32_getmantpd512_mask:
4789   case X86::BI__builtin_ia32_getmantps512_mask:
4790   case X86::BI__builtin_ia32_getmantph128_mask:
4791   case X86::BI__builtin_ia32_getmantph256_mask:
4792   case X86::BI__builtin_ia32_getmantph512_mask:
4793   case X86::BI__builtin_ia32_vec_ext_v16qi:
4794   case X86::BI__builtin_ia32_vec_ext_v16hi:
4795     i = 1; l = 0; u = 15;
4796     break;
4797   case X86::BI__builtin_ia32_pblendd128:
4798   case X86::BI__builtin_ia32_blendps:
4799   case X86::BI__builtin_ia32_blendpd256:
4800   case X86::BI__builtin_ia32_shufpd256:
4801   case X86::BI__builtin_ia32_roundss:
4802   case X86::BI__builtin_ia32_roundsd:
4803   case X86::BI__builtin_ia32_rangepd128_mask:
4804   case X86::BI__builtin_ia32_rangepd256_mask:
4805   case X86::BI__builtin_ia32_rangepd512_mask:
4806   case X86::BI__builtin_ia32_rangeps128_mask:
4807   case X86::BI__builtin_ia32_rangeps256_mask:
4808   case X86::BI__builtin_ia32_rangeps512_mask:
4809   case X86::BI__builtin_ia32_getmantsd_round_mask:
4810   case X86::BI__builtin_ia32_getmantss_round_mask:
4811   case X86::BI__builtin_ia32_getmantsh_round_mask:
4812   case X86::BI__builtin_ia32_vec_set_v16qi:
4813   case X86::BI__builtin_ia32_vec_set_v16hi:
4814     i = 2; l = 0; u = 15;
4815     break;
4816   case X86::BI__builtin_ia32_vec_ext_v32qi:
4817     i = 1; l = 0; u = 31;
4818     break;
4819   case X86::BI__builtin_ia32_cmpps:
4820   case X86::BI__builtin_ia32_cmpss:
4821   case X86::BI__builtin_ia32_cmppd:
4822   case X86::BI__builtin_ia32_cmpsd:
4823   case X86::BI__builtin_ia32_cmpps256:
4824   case X86::BI__builtin_ia32_cmppd256:
4825   case X86::BI__builtin_ia32_cmpps128_mask:
4826   case X86::BI__builtin_ia32_cmppd128_mask:
4827   case X86::BI__builtin_ia32_cmpps256_mask:
4828   case X86::BI__builtin_ia32_cmppd256_mask:
4829   case X86::BI__builtin_ia32_cmpps512_mask:
4830   case X86::BI__builtin_ia32_cmppd512_mask:
4831   case X86::BI__builtin_ia32_cmpsd_mask:
4832   case X86::BI__builtin_ia32_cmpss_mask:
4833   case X86::BI__builtin_ia32_vec_set_v32qi:
4834     i = 2; l = 0; u = 31;
4835     break;
4836   case X86::BI__builtin_ia32_permdf256:
4837   case X86::BI__builtin_ia32_permdi256:
4838   case X86::BI__builtin_ia32_permdf512:
4839   case X86::BI__builtin_ia32_permdi512:
4840   case X86::BI__builtin_ia32_vpermilps:
4841   case X86::BI__builtin_ia32_vpermilps256:
4842   case X86::BI__builtin_ia32_vpermilpd512:
4843   case X86::BI__builtin_ia32_vpermilps512:
4844   case X86::BI__builtin_ia32_pshufd:
4845   case X86::BI__builtin_ia32_pshufd256:
4846   case X86::BI__builtin_ia32_pshufd512:
4847   case X86::BI__builtin_ia32_pshufhw:
4848   case X86::BI__builtin_ia32_pshufhw256:
4849   case X86::BI__builtin_ia32_pshufhw512:
4850   case X86::BI__builtin_ia32_pshuflw:
4851   case X86::BI__builtin_ia32_pshuflw256:
4852   case X86::BI__builtin_ia32_pshuflw512:
4853   case X86::BI__builtin_ia32_vcvtps2ph:
4854   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4855   case X86::BI__builtin_ia32_vcvtps2ph256:
4856   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4857   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4858   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4859   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4860   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4861   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4862   case X86::BI__builtin_ia32_rndscaleps_mask:
4863   case X86::BI__builtin_ia32_rndscalepd_mask:
4864   case X86::BI__builtin_ia32_rndscaleph_mask:
4865   case X86::BI__builtin_ia32_reducepd128_mask:
4866   case X86::BI__builtin_ia32_reducepd256_mask:
4867   case X86::BI__builtin_ia32_reducepd512_mask:
4868   case X86::BI__builtin_ia32_reduceps128_mask:
4869   case X86::BI__builtin_ia32_reduceps256_mask:
4870   case X86::BI__builtin_ia32_reduceps512_mask:
4871   case X86::BI__builtin_ia32_reduceph128_mask:
4872   case X86::BI__builtin_ia32_reduceph256_mask:
4873   case X86::BI__builtin_ia32_reduceph512_mask:
4874   case X86::BI__builtin_ia32_prold512:
4875   case X86::BI__builtin_ia32_prolq512:
4876   case X86::BI__builtin_ia32_prold128:
4877   case X86::BI__builtin_ia32_prold256:
4878   case X86::BI__builtin_ia32_prolq128:
4879   case X86::BI__builtin_ia32_prolq256:
4880   case X86::BI__builtin_ia32_prord512:
4881   case X86::BI__builtin_ia32_prorq512:
4882   case X86::BI__builtin_ia32_prord128:
4883   case X86::BI__builtin_ia32_prord256:
4884   case X86::BI__builtin_ia32_prorq128:
4885   case X86::BI__builtin_ia32_prorq256:
4886   case X86::BI__builtin_ia32_fpclasspd128_mask:
4887   case X86::BI__builtin_ia32_fpclasspd256_mask:
4888   case X86::BI__builtin_ia32_fpclassps128_mask:
4889   case X86::BI__builtin_ia32_fpclassps256_mask:
4890   case X86::BI__builtin_ia32_fpclassps512_mask:
4891   case X86::BI__builtin_ia32_fpclasspd512_mask:
4892   case X86::BI__builtin_ia32_fpclassph128_mask:
4893   case X86::BI__builtin_ia32_fpclassph256_mask:
4894   case X86::BI__builtin_ia32_fpclassph512_mask:
4895   case X86::BI__builtin_ia32_fpclasssd_mask:
4896   case X86::BI__builtin_ia32_fpclassss_mask:
4897   case X86::BI__builtin_ia32_fpclasssh_mask:
4898   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4899   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4900   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4901   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4902   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4903   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4904   case X86::BI__builtin_ia32_kshiftliqi:
4905   case X86::BI__builtin_ia32_kshiftlihi:
4906   case X86::BI__builtin_ia32_kshiftlisi:
4907   case X86::BI__builtin_ia32_kshiftlidi:
4908   case X86::BI__builtin_ia32_kshiftriqi:
4909   case X86::BI__builtin_ia32_kshiftrihi:
4910   case X86::BI__builtin_ia32_kshiftrisi:
4911   case X86::BI__builtin_ia32_kshiftridi:
4912     i = 1; l = 0; u = 255;
4913     break;
4914   case X86::BI__builtin_ia32_vperm2f128_pd256:
4915   case X86::BI__builtin_ia32_vperm2f128_ps256:
4916   case X86::BI__builtin_ia32_vperm2f128_si256:
4917   case X86::BI__builtin_ia32_permti256:
4918   case X86::BI__builtin_ia32_pblendw128:
4919   case X86::BI__builtin_ia32_pblendw256:
4920   case X86::BI__builtin_ia32_blendps256:
4921   case X86::BI__builtin_ia32_pblendd256:
4922   case X86::BI__builtin_ia32_palignr128:
4923   case X86::BI__builtin_ia32_palignr256:
4924   case X86::BI__builtin_ia32_palignr512:
4925   case X86::BI__builtin_ia32_alignq512:
4926   case X86::BI__builtin_ia32_alignd512:
4927   case X86::BI__builtin_ia32_alignd128:
4928   case X86::BI__builtin_ia32_alignd256:
4929   case X86::BI__builtin_ia32_alignq128:
4930   case X86::BI__builtin_ia32_alignq256:
4931   case X86::BI__builtin_ia32_vcomisd:
4932   case X86::BI__builtin_ia32_vcomiss:
4933   case X86::BI__builtin_ia32_shuf_f32x4:
4934   case X86::BI__builtin_ia32_shuf_f64x2:
4935   case X86::BI__builtin_ia32_shuf_i32x4:
4936   case X86::BI__builtin_ia32_shuf_i64x2:
4937   case X86::BI__builtin_ia32_shufpd512:
4938   case X86::BI__builtin_ia32_shufps:
4939   case X86::BI__builtin_ia32_shufps256:
4940   case X86::BI__builtin_ia32_shufps512:
4941   case X86::BI__builtin_ia32_dbpsadbw128:
4942   case X86::BI__builtin_ia32_dbpsadbw256:
4943   case X86::BI__builtin_ia32_dbpsadbw512:
4944   case X86::BI__builtin_ia32_vpshldd128:
4945   case X86::BI__builtin_ia32_vpshldd256:
4946   case X86::BI__builtin_ia32_vpshldd512:
4947   case X86::BI__builtin_ia32_vpshldq128:
4948   case X86::BI__builtin_ia32_vpshldq256:
4949   case X86::BI__builtin_ia32_vpshldq512:
4950   case X86::BI__builtin_ia32_vpshldw128:
4951   case X86::BI__builtin_ia32_vpshldw256:
4952   case X86::BI__builtin_ia32_vpshldw512:
4953   case X86::BI__builtin_ia32_vpshrdd128:
4954   case X86::BI__builtin_ia32_vpshrdd256:
4955   case X86::BI__builtin_ia32_vpshrdd512:
4956   case X86::BI__builtin_ia32_vpshrdq128:
4957   case X86::BI__builtin_ia32_vpshrdq256:
4958   case X86::BI__builtin_ia32_vpshrdq512:
4959   case X86::BI__builtin_ia32_vpshrdw128:
4960   case X86::BI__builtin_ia32_vpshrdw256:
4961   case X86::BI__builtin_ia32_vpshrdw512:
4962     i = 2; l = 0; u = 255;
4963     break;
4964   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4965   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4966   case X86::BI__builtin_ia32_fixupimmps512_mask:
4967   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4968   case X86::BI__builtin_ia32_fixupimmsd_mask:
4969   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4970   case X86::BI__builtin_ia32_fixupimmss_mask:
4971   case X86::BI__builtin_ia32_fixupimmss_maskz:
4972   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4973   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4974   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4975   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4976   case X86::BI__builtin_ia32_fixupimmps128_mask:
4977   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4978   case X86::BI__builtin_ia32_fixupimmps256_mask:
4979   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4980   case X86::BI__builtin_ia32_pternlogd512_mask:
4981   case X86::BI__builtin_ia32_pternlogd512_maskz:
4982   case X86::BI__builtin_ia32_pternlogq512_mask:
4983   case X86::BI__builtin_ia32_pternlogq512_maskz:
4984   case X86::BI__builtin_ia32_pternlogd128_mask:
4985   case X86::BI__builtin_ia32_pternlogd128_maskz:
4986   case X86::BI__builtin_ia32_pternlogd256_mask:
4987   case X86::BI__builtin_ia32_pternlogd256_maskz:
4988   case X86::BI__builtin_ia32_pternlogq128_mask:
4989   case X86::BI__builtin_ia32_pternlogq128_maskz:
4990   case X86::BI__builtin_ia32_pternlogq256_mask:
4991   case X86::BI__builtin_ia32_pternlogq256_maskz:
4992     i = 3; l = 0; u = 255;
4993     break;
4994   case X86::BI__builtin_ia32_gatherpfdpd:
4995   case X86::BI__builtin_ia32_gatherpfdps:
4996   case X86::BI__builtin_ia32_gatherpfqpd:
4997   case X86::BI__builtin_ia32_gatherpfqps:
4998   case X86::BI__builtin_ia32_scatterpfdpd:
4999   case X86::BI__builtin_ia32_scatterpfdps:
5000   case X86::BI__builtin_ia32_scatterpfqpd:
5001   case X86::BI__builtin_ia32_scatterpfqps:
5002     i = 4; l = 2; u = 3;
5003     break;
5004   case X86::BI__builtin_ia32_reducesd_mask:
5005   case X86::BI__builtin_ia32_reducess_mask:
5006   case X86::BI__builtin_ia32_rndscalesd_round_mask:
5007   case X86::BI__builtin_ia32_rndscaless_round_mask:
5008   case X86::BI__builtin_ia32_rndscalesh_round_mask:
5009   case X86::BI__builtin_ia32_reducesh_mask:
5010     i = 4; l = 0; u = 255;
5011     break;
5012   }
5013 
5014   // Note that we don't force a hard error on the range check here, allowing
5015   // template-generated or macro-generated dead code to potentially have out-of-
5016   // range values. These need to code generate, but don't need to necessarily
5017   // make any sense. We use a warning that defaults to an error.
5018   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
5019 }
5020 
5021 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
5022 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
5023 /// Returns true when the format fits the function and the FormatStringInfo has
5024 /// been populated.
5025 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
5026                                FormatStringInfo *FSI) {
5027   FSI->HasVAListArg = Format->getFirstArg() == 0;
5028   FSI->FormatIdx = Format->getFormatIdx() - 1;
5029   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
5030 
5031   // The way the format attribute works in GCC, the implicit this argument
5032   // of member functions is counted. However, it doesn't appear in our own
5033   // lists, so decrement format_idx in that case.
5034   if (IsCXXMember) {
5035     if(FSI->FormatIdx == 0)
5036       return false;
5037     --FSI->FormatIdx;
5038     if (FSI->FirstDataArg != 0)
5039       --FSI->FirstDataArg;
5040   }
5041   return true;
5042 }
5043 
5044 /// Checks if a the given expression evaluates to null.
5045 ///
5046 /// Returns true if the value evaluates to null.
5047 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
5048   // If the expression has non-null type, it doesn't evaluate to null.
5049   if (auto nullability
5050         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
5051     if (*nullability == NullabilityKind::NonNull)
5052       return false;
5053   }
5054 
5055   // As a special case, transparent unions initialized with zero are
5056   // considered null for the purposes of the nonnull attribute.
5057   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
5058     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
5059       if (const CompoundLiteralExpr *CLE =
5060           dyn_cast<CompoundLiteralExpr>(Expr))
5061         if (const InitListExpr *ILE =
5062             dyn_cast<InitListExpr>(CLE->getInitializer()))
5063           Expr = ILE->getInit(0);
5064   }
5065 
5066   bool Result;
5067   return (!Expr->isValueDependent() &&
5068           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
5069           !Result);
5070 }
5071 
5072 static void CheckNonNullArgument(Sema &S,
5073                                  const Expr *ArgExpr,
5074                                  SourceLocation CallSiteLoc) {
5075   if (CheckNonNullExpr(S, ArgExpr))
5076     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
5077                           S.PDiag(diag::warn_null_arg)
5078                               << ArgExpr->getSourceRange());
5079 }
5080 
5081 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
5082   FormatStringInfo FSI;
5083   if ((GetFormatStringType(Format) == FST_NSString) &&
5084       getFormatStringInfo(Format, false, &FSI)) {
5085     Idx = FSI.FormatIdx;
5086     return true;
5087   }
5088   return false;
5089 }
5090 
5091 /// Diagnose use of %s directive in an NSString which is being passed
5092 /// as formatting string to formatting method.
5093 static void
5094 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
5095                                         const NamedDecl *FDecl,
5096                                         Expr **Args,
5097                                         unsigned NumArgs) {
5098   unsigned Idx = 0;
5099   bool Format = false;
5100   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
5101   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
5102     Idx = 2;
5103     Format = true;
5104   }
5105   else
5106     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5107       if (S.GetFormatNSStringIdx(I, Idx)) {
5108         Format = true;
5109         break;
5110       }
5111     }
5112   if (!Format || NumArgs <= Idx)
5113     return;
5114   const Expr *FormatExpr = Args[Idx];
5115   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
5116     FormatExpr = CSCE->getSubExpr();
5117   const StringLiteral *FormatString;
5118   if (const ObjCStringLiteral *OSL =
5119       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
5120     FormatString = OSL->getString();
5121   else
5122     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
5123   if (!FormatString)
5124     return;
5125   if (S.FormatStringHasSArg(FormatString)) {
5126     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
5127       << "%s" << 1 << 1;
5128     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
5129       << FDecl->getDeclName();
5130   }
5131 }
5132 
5133 /// Determine whether the given type has a non-null nullability annotation.
5134 static bool isNonNullType(ASTContext &ctx, QualType type) {
5135   if (auto nullability = type->getNullability(ctx))
5136     return *nullability == NullabilityKind::NonNull;
5137 
5138   return false;
5139 }
5140 
5141 static void CheckNonNullArguments(Sema &S,
5142                                   const NamedDecl *FDecl,
5143                                   const FunctionProtoType *Proto,
5144                                   ArrayRef<const Expr *> Args,
5145                                   SourceLocation CallSiteLoc) {
5146   assert((FDecl || Proto) && "Need a function declaration or prototype");
5147 
5148   // Already checked by by constant evaluator.
5149   if (S.isConstantEvaluated())
5150     return;
5151   // Check the attributes attached to the method/function itself.
5152   llvm::SmallBitVector NonNullArgs;
5153   if (FDecl) {
5154     // Handle the nonnull attribute on the function/method declaration itself.
5155     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
5156       if (!NonNull->args_size()) {
5157         // Easy case: all pointer arguments are nonnull.
5158         for (const auto *Arg : Args)
5159           if (S.isValidPointerAttrType(Arg->getType()))
5160             CheckNonNullArgument(S, Arg, CallSiteLoc);
5161         return;
5162       }
5163 
5164       for (const ParamIdx &Idx : NonNull->args()) {
5165         unsigned IdxAST = Idx.getASTIndex();
5166         if (IdxAST >= Args.size())
5167           continue;
5168         if (NonNullArgs.empty())
5169           NonNullArgs.resize(Args.size());
5170         NonNullArgs.set(IdxAST);
5171       }
5172     }
5173   }
5174 
5175   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
5176     // Handle the nonnull attribute on the parameters of the
5177     // function/method.
5178     ArrayRef<ParmVarDecl*> parms;
5179     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
5180       parms = FD->parameters();
5181     else
5182       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
5183 
5184     unsigned ParamIndex = 0;
5185     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
5186          I != E; ++I, ++ParamIndex) {
5187       const ParmVarDecl *PVD = *I;
5188       if (PVD->hasAttr<NonNullAttr>() ||
5189           isNonNullType(S.Context, PVD->getType())) {
5190         if (NonNullArgs.empty())
5191           NonNullArgs.resize(Args.size());
5192 
5193         NonNullArgs.set(ParamIndex);
5194       }
5195     }
5196   } else {
5197     // If we have a non-function, non-method declaration but no
5198     // function prototype, try to dig out the function prototype.
5199     if (!Proto) {
5200       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
5201         QualType type = VD->getType().getNonReferenceType();
5202         if (auto pointerType = type->getAs<PointerType>())
5203           type = pointerType->getPointeeType();
5204         else if (auto blockType = type->getAs<BlockPointerType>())
5205           type = blockType->getPointeeType();
5206         // FIXME: data member pointers?
5207 
5208         // Dig out the function prototype, if there is one.
5209         Proto = type->getAs<FunctionProtoType>();
5210       }
5211     }
5212 
5213     // Fill in non-null argument information from the nullability
5214     // information on the parameter types (if we have them).
5215     if (Proto) {
5216       unsigned Index = 0;
5217       for (auto paramType : Proto->getParamTypes()) {
5218         if (isNonNullType(S.Context, paramType)) {
5219           if (NonNullArgs.empty())
5220             NonNullArgs.resize(Args.size());
5221 
5222           NonNullArgs.set(Index);
5223         }
5224 
5225         ++Index;
5226       }
5227     }
5228   }
5229 
5230   // Check for non-null arguments.
5231   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
5232        ArgIndex != ArgIndexEnd; ++ArgIndex) {
5233     if (NonNullArgs[ArgIndex])
5234       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
5235   }
5236 }
5237 
5238 /// Warn if a pointer or reference argument passed to a function points to an
5239 /// object that is less aligned than the parameter. This can happen when
5240 /// creating a typedef with a lower alignment than the original type and then
5241 /// calling functions defined in terms of the original type.
5242 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
5243                              StringRef ParamName, QualType ArgTy,
5244                              QualType ParamTy) {
5245 
5246   // If a function accepts a pointer or reference type
5247   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
5248     return;
5249 
5250   // If the parameter is a pointer type, get the pointee type for the
5251   // argument too. If the parameter is a reference type, don't try to get
5252   // the pointee type for the argument.
5253   if (ParamTy->isPointerType())
5254     ArgTy = ArgTy->getPointeeType();
5255 
5256   // Remove reference or pointer
5257   ParamTy = ParamTy->getPointeeType();
5258 
5259   // Find expected alignment, and the actual alignment of the passed object.
5260   // getTypeAlignInChars requires complete types
5261   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
5262       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
5263       ArgTy->isUndeducedType())
5264     return;
5265 
5266   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
5267   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
5268 
5269   // If the argument is less aligned than the parameter, there is a
5270   // potential alignment issue.
5271   if (ArgAlign < ParamAlign)
5272     Diag(Loc, diag::warn_param_mismatched_alignment)
5273         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
5274         << ParamName << (FDecl != nullptr) << FDecl;
5275 }
5276 
5277 /// Handles the checks for format strings, non-POD arguments to vararg
5278 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
5279 /// attributes.
5280 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
5281                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
5282                      bool IsMemberFunction, SourceLocation Loc,
5283                      SourceRange Range, VariadicCallType CallType) {
5284   // FIXME: We should check as much as we can in the template definition.
5285   if (CurContext->isDependentContext())
5286     return;
5287 
5288   // Printf and scanf checking.
5289   llvm::SmallBitVector CheckedVarArgs;
5290   if (FDecl) {
5291     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5292       // Only create vector if there are format attributes.
5293       CheckedVarArgs.resize(Args.size());
5294 
5295       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
5296                            CheckedVarArgs);
5297     }
5298   }
5299 
5300   // Refuse POD arguments that weren't caught by the format string
5301   // checks above.
5302   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
5303   if (CallType != VariadicDoesNotApply &&
5304       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
5305     unsigned NumParams = Proto ? Proto->getNumParams()
5306                        : FDecl && isa<FunctionDecl>(FDecl)
5307                            ? cast<FunctionDecl>(FDecl)->getNumParams()
5308                        : FDecl && isa<ObjCMethodDecl>(FDecl)
5309                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
5310                        : 0;
5311 
5312     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
5313       // Args[ArgIdx] can be null in malformed code.
5314       if (const Expr *Arg = Args[ArgIdx]) {
5315         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
5316           checkVariadicArgument(Arg, CallType);
5317       }
5318     }
5319   }
5320 
5321   if (FDecl || Proto) {
5322     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
5323 
5324     // Type safety checking.
5325     if (FDecl) {
5326       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
5327         CheckArgumentWithTypeTag(I, Args, Loc);
5328     }
5329   }
5330 
5331   // Check that passed arguments match the alignment of original arguments.
5332   // Try to get the missing prototype from the declaration.
5333   if (!Proto && FDecl) {
5334     const auto *FT = FDecl->getFunctionType();
5335     if (isa_and_nonnull<FunctionProtoType>(FT))
5336       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
5337   }
5338   if (Proto) {
5339     // For variadic functions, we may have more args than parameters.
5340     // For some K&R functions, we may have less args than parameters.
5341     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
5342     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
5343       // Args[ArgIdx] can be null in malformed code.
5344       if (const Expr *Arg = Args[ArgIdx]) {
5345         if (Arg->containsErrors())
5346           continue;
5347 
5348         QualType ParamTy = Proto->getParamType(ArgIdx);
5349         QualType ArgTy = Arg->getType();
5350         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
5351                           ArgTy, ParamTy);
5352       }
5353     }
5354   }
5355 
5356   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
5357     auto *AA = FDecl->getAttr<AllocAlignAttr>();
5358     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
5359     if (!Arg->isValueDependent()) {
5360       Expr::EvalResult Align;
5361       if (Arg->EvaluateAsInt(Align, Context)) {
5362         const llvm::APSInt &I = Align.Val.getInt();
5363         if (!I.isPowerOf2())
5364           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
5365               << Arg->getSourceRange();
5366 
5367         if (I > Sema::MaximumAlignment)
5368           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
5369               << Arg->getSourceRange() << Sema::MaximumAlignment;
5370       }
5371     }
5372   }
5373 
5374   if (FD)
5375     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
5376 }
5377 
5378 /// CheckConstructorCall - Check a constructor call for correctness and safety
5379 /// properties not enforced by the C type system.
5380 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5381                                 ArrayRef<const Expr *> Args,
5382                                 const FunctionProtoType *Proto,
5383                                 SourceLocation Loc) {
5384   VariadicCallType CallType =
5385       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5386 
5387   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5388   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5389                     Context.getPointerType(Ctor->getThisObjectType()));
5390 
5391   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5392             Loc, SourceRange(), CallType);
5393 }
5394 
5395 /// CheckFunctionCall - Check a direct function call for various correctness
5396 /// and safety properties not strictly enforced by the C type system.
5397 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5398                              const FunctionProtoType *Proto) {
5399   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5400                               isa<CXXMethodDecl>(FDecl);
5401   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5402                           IsMemberOperatorCall;
5403   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5404                                                   TheCall->getCallee());
5405   Expr** Args = TheCall->getArgs();
5406   unsigned NumArgs = TheCall->getNumArgs();
5407 
5408   Expr *ImplicitThis = nullptr;
5409   if (IsMemberOperatorCall) {
5410     // If this is a call to a member operator, hide the first argument
5411     // from checkCall.
5412     // FIXME: Our choice of AST representation here is less than ideal.
5413     ImplicitThis = Args[0];
5414     ++Args;
5415     --NumArgs;
5416   } else if (IsMemberFunction)
5417     ImplicitThis =
5418         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5419 
5420   if (ImplicitThis) {
5421     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5422     // used.
5423     QualType ThisType = ImplicitThis->getType();
5424     if (!ThisType->isPointerType()) {
5425       assert(!ThisType->isReferenceType());
5426       ThisType = Context.getPointerType(ThisType);
5427     }
5428 
5429     QualType ThisTypeFromDecl =
5430         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5431 
5432     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5433                       ThisTypeFromDecl);
5434   }
5435 
5436   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5437             IsMemberFunction, TheCall->getRParenLoc(),
5438             TheCall->getCallee()->getSourceRange(), CallType);
5439 
5440   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5441   // None of the checks below are needed for functions that don't have
5442   // simple names (e.g., C++ conversion functions).
5443   if (!FnInfo)
5444     return false;
5445 
5446   CheckTCBEnforcement(TheCall, FDecl);
5447 
5448   CheckAbsoluteValueFunction(TheCall, FDecl);
5449   CheckMaxUnsignedZero(TheCall, FDecl);
5450 
5451   if (getLangOpts().ObjC)
5452     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5453 
5454   unsigned CMId = FDecl->getMemoryFunctionKind();
5455 
5456   // Handle memory setting and copying functions.
5457   switch (CMId) {
5458   case 0:
5459     return false;
5460   case Builtin::BIstrlcpy: // fallthrough
5461   case Builtin::BIstrlcat:
5462     CheckStrlcpycatArguments(TheCall, FnInfo);
5463     break;
5464   case Builtin::BIstrncat:
5465     CheckStrncatArguments(TheCall, FnInfo);
5466     break;
5467   case Builtin::BIfree:
5468     CheckFreeArguments(TheCall);
5469     break;
5470   default:
5471     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5472   }
5473 
5474   return false;
5475 }
5476 
5477 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5478                                ArrayRef<const Expr *> Args) {
5479   VariadicCallType CallType =
5480       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5481 
5482   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5483             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5484             CallType);
5485 
5486   return false;
5487 }
5488 
5489 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5490                             const FunctionProtoType *Proto) {
5491   QualType Ty;
5492   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5493     Ty = V->getType().getNonReferenceType();
5494   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5495     Ty = F->getType().getNonReferenceType();
5496   else
5497     return false;
5498 
5499   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5500       !Ty->isFunctionProtoType())
5501     return false;
5502 
5503   VariadicCallType CallType;
5504   if (!Proto || !Proto->isVariadic()) {
5505     CallType = VariadicDoesNotApply;
5506   } else if (Ty->isBlockPointerType()) {
5507     CallType = VariadicBlock;
5508   } else { // Ty->isFunctionPointerType()
5509     CallType = VariadicFunction;
5510   }
5511 
5512   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5513             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5514             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5515             TheCall->getCallee()->getSourceRange(), CallType);
5516 
5517   return false;
5518 }
5519 
5520 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5521 /// such as function pointers returned from functions.
5522 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5523   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5524                                                   TheCall->getCallee());
5525   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5526             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5527             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5528             TheCall->getCallee()->getSourceRange(), CallType);
5529 
5530   return false;
5531 }
5532 
5533 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5534   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5535     return false;
5536 
5537   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5538   switch (Op) {
5539   case AtomicExpr::AO__c11_atomic_init:
5540   case AtomicExpr::AO__opencl_atomic_init:
5541     llvm_unreachable("There is no ordering argument for an init");
5542 
5543   case AtomicExpr::AO__c11_atomic_load:
5544   case AtomicExpr::AO__opencl_atomic_load:
5545   case AtomicExpr::AO__hip_atomic_load:
5546   case AtomicExpr::AO__atomic_load_n:
5547   case AtomicExpr::AO__atomic_load:
5548     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5549            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5550 
5551   case AtomicExpr::AO__c11_atomic_store:
5552   case AtomicExpr::AO__opencl_atomic_store:
5553   case AtomicExpr::AO__hip_atomic_store:
5554   case AtomicExpr::AO__atomic_store:
5555   case AtomicExpr::AO__atomic_store_n:
5556     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5557            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5558            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5559 
5560   default:
5561     return true;
5562   }
5563 }
5564 
5565 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5566                                          AtomicExpr::AtomicOp Op) {
5567   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5568   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5569   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5570   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5571                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5572                          Op);
5573 }
5574 
5575 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5576                                  SourceLocation RParenLoc, MultiExprArg Args,
5577                                  AtomicExpr::AtomicOp Op,
5578                                  AtomicArgumentOrder ArgOrder) {
5579   // All the non-OpenCL operations take one of the following forms.
5580   // The OpenCL operations take the __c11 forms with one extra argument for
5581   // synchronization scope.
5582   enum {
5583     // C    __c11_atomic_init(A *, C)
5584     Init,
5585 
5586     // C    __c11_atomic_load(A *, int)
5587     Load,
5588 
5589     // void __atomic_load(A *, CP, int)
5590     LoadCopy,
5591 
5592     // void __atomic_store(A *, CP, int)
5593     Copy,
5594 
5595     // C    __c11_atomic_add(A *, M, int)
5596     Arithmetic,
5597 
5598     // C    __atomic_exchange_n(A *, CP, int)
5599     Xchg,
5600 
5601     // void __atomic_exchange(A *, C *, CP, int)
5602     GNUXchg,
5603 
5604     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5605     C11CmpXchg,
5606 
5607     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5608     GNUCmpXchg
5609   } Form = Init;
5610 
5611   const unsigned NumForm = GNUCmpXchg + 1;
5612   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5613   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5614   // where:
5615   //   C is an appropriate type,
5616   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5617   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5618   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5619   //   the int parameters are for orderings.
5620 
5621   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5622       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5623       "need to update code for modified forms");
5624   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5625                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5626                         AtomicExpr::AO__atomic_load,
5627                 "need to update code for modified C11 atomics");
5628   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5629                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5630   bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load &&
5631                Op <= AtomicExpr::AO__hip_atomic_fetch_max;
5632   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5633                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5634                IsOpenCL;
5635   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5636              Op == AtomicExpr::AO__atomic_store_n ||
5637              Op == AtomicExpr::AO__atomic_exchange_n ||
5638              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5639   bool IsAddSub = false;
5640 
5641   switch (Op) {
5642   case AtomicExpr::AO__c11_atomic_init:
5643   case AtomicExpr::AO__opencl_atomic_init:
5644     Form = Init;
5645     break;
5646 
5647   case AtomicExpr::AO__c11_atomic_load:
5648   case AtomicExpr::AO__opencl_atomic_load:
5649   case AtomicExpr::AO__hip_atomic_load:
5650   case AtomicExpr::AO__atomic_load_n:
5651     Form = Load;
5652     break;
5653 
5654   case AtomicExpr::AO__atomic_load:
5655     Form = LoadCopy;
5656     break;
5657 
5658   case AtomicExpr::AO__c11_atomic_store:
5659   case AtomicExpr::AO__opencl_atomic_store:
5660   case AtomicExpr::AO__hip_atomic_store:
5661   case AtomicExpr::AO__atomic_store:
5662   case AtomicExpr::AO__atomic_store_n:
5663     Form = Copy;
5664     break;
5665   case AtomicExpr::AO__hip_atomic_fetch_add:
5666   case AtomicExpr::AO__hip_atomic_fetch_min:
5667   case AtomicExpr::AO__hip_atomic_fetch_max:
5668   case AtomicExpr::AO__c11_atomic_fetch_add:
5669   case AtomicExpr::AO__c11_atomic_fetch_sub:
5670   case AtomicExpr::AO__opencl_atomic_fetch_add:
5671   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5672   case AtomicExpr::AO__atomic_fetch_add:
5673   case AtomicExpr::AO__atomic_fetch_sub:
5674   case AtomicExpr::AO__atomic_add_fetch:
5675   case AtomicExpr::AO__atomic_sub_fetch:
5676     IsAddSub = true;
5677     Form = Arithmetic;
5678     break;
5679   case AtomicExpr::AO__c11_atomic_fetch_and:
5680   case AtomicExpr::AO__c11_atomic_fetch_or:
5681   case AtomicExpr::AO__c11_atomic_fetch_xor:
5682   case AtomicExpr::AO__hip_atomic_fetch_and:
5683   case AtomicExpr::AO__hip_atomic_fetch_or:
5684   case AtomicExpr::AO__hip_atomic_fetch_xor:
5685   case AtomicExpr::AO__c11_atomic_fetch_nand:
5686   case AtomicExpr::AO__opencl_atomic_fetch_and:
5687   case AtomicExpr::AO__opencl_atomic_fetch_or:
5688   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5689   case AtomicExpr::AO__atomic_fetch_and:
5690   case AtomicExpr::AO__atomic_fetch_or:
5691   case AtomicExpr::AO__atomic_fetch_xor:
5692   case AtomicExpr::AO__atomic_fetch_nand:
5693   case AtomicExpr::AO__atomic_and_fetch:
5694   case AtomicExpr::AO__atomic_or_fetch:
5695   case AtomicExpr::AO__atomic_xor_fetch:
5696   case AtomicExpr::AO__atomic_nand_fetch:
5697     Form = Arithmetic;
5698     break;
5699   case AtomicExpr::AO__c11_atomic_fetch_min:
5700   case AtomicExpr::AO__c11_atomic_fetch_max:
5701   case AtomicExpr::AO__opencl_atomic_fetch_min:
5702   case AtomicExpr::AO__opencl_atomic_fetch_max:
5703   case AtomicExpr::AO__atomic_min_fetch:
5704   case AtomicExpr::AO__atomic_max_fetch:
5705   case AtomicExpr::AO__atomic_fetch_min:
5706   case AtomicExpr::AO__atomic_fetch_max:
5707     Form = Arithmetic;
5708     break;
5709 
5710   case AtomicExpr::AO__c11_atomic_exchange:
5711   case AtomicExpr::AO__hip_atomic_exchange:
5712   case AtomicExpr::AO__opencl_atomic_exchange:
5713   case AtomicExpr::AO__atomic_exchange_n:
5714     Form = Xchg;
5715     break;
5716 
5717   case AtomicExpr::AO__atomic_exchange:
5718     Form = GNUXchg;
5719     break;
5720 
5721   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5722   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5723   case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5724   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5725   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5726   case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5727     Form = C11CmpXchg;
5728     break;
5729 
5730   case AtomicExpr::AO__atomic_compare_exchange:
5731   case AtomicExpr::AO__atomic_compare_exchange_n:
5732     Form = GNUCmpXchg;
5733     break;
5734   }
5735 
5736   unsigned AdjustedNumArgs = NumArgs[Form];
5737   if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init)
5738     ++AdjustedNumArgs;
5739   // Check we have the right number of arguments.
5740   if (Args.size() < AdjustedNumArgs) {
5741     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5742         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5743         << ExprRange;
5744     return ExprError();
5745   } else if (Args.size() > AdjustedNumArgs) {
5746     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5747          diag::err_typecheck_call_too_many_args)
5748         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5749         << ExprRange;
5750     return ExprError();
5751   }
5752 
5753   // Inspect the first argument of the atomic operation.
5754   Expr *Ptr = Args[0];
5755   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5756   if (ConvertedPtr.isInvalid())
5757     return ExprError();
5758 
5759   Ptr = ConvertedPtr.get();
5760   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5761   if (!pointerType) {
5762     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5763         << Ptr->getType() << Ptr->getSourceRange();
5764     return ExprError();
5765   }
5766 
5767   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5768   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5769   QualType ValType = AtomTy; // 'C'
5770   if (IsC11) {
5771     if (!AtomTy->isAtomicType()) {
5772       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5773           << Ptr->getType() << Ptr->getSourceRange();
5774       return ExprError();
5775     }
5776     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5777         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5778       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5779           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5780           << Ptr->getSourceRange();
5781       return ExprError();
5782     }
5783     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5784   } else if (Form != Load && Form != LoadCopy) {
5785     if (ValType.isConstQualified()) {
5786       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5787           << Ptr->getType() << Ptr->getSourceRange();
5788       return ExprError();
5789     }
5790   }
5791 
5792   // For an arithmetic operation, the implied arithmetic must be well-formed.
5793   if (Form == Arithmetic) {
5794     // GCC does not enforce these rules for GNU atomics, but we do to help catch
5795     // trivial type errors.
5796     auto IsAllowedValueType = [&](QualType ValType) {
5797       if (ValType->isIntegerType())
5798         return true;
5799       if (ValType->isPointerType())
5800         return true;
5801       if (!ValType->isFloatingType())
5802         return false;
5803       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5804       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5805           &Context.getTargetInfo().getLongDoubleFormat() ==
5806               &llvm::APFloat::x87DoubleExtended())
5807         return false;
5808       return true;
5809     };
5810     if (IsAddSub && !IsAllowedValueType(ValType)) {
5811       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5812           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5813       return ExprError();
5814     }
5815     if (!IsAddSub && !ValType->isIntegerType()) {
5816       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5817           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5818       return ExprError();
5819     }
5820     if (IsC11 && ValType->isPointerType() &&
5821         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5822                             diag::err_incomplete_type)) {
5823       return ExprError();
5824     }
5825   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5826     // For __atomic_*_n operations, the value type must be a scalar integral or
5827     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5828     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5829         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5830     return ExprError();
5831   }
5832 
5833   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5834       !AtomTy->isScalarType()) {
5835     // For GNU atomics, require a trivially-copyable type. This is not part of
5836     // the GNU atomics specification but we enforce it for consistency with
5837     // other atomics which generally all require a trivially-copyable type. This
5838     // is because atomics just copy bits.
5839     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5840         << Ptr->getType() << Ptr->getSourceRange();
5841     return ExprError();
5842   }
5843 
5844   switch (ValType.getObjCLifetime()) {
5845   case Qualifiers::OCL_None:
5846   case Qualifiers::OCL_ExplicitNone:
5847     // okay
5848     break;
5849 
5850   case Qualifiers::OCL_Weak:
5851   case Qualifiers::OCL_Strong:
5852   case Qualifiers::OCL_Autoreleasing:
5853     // FIXME: Can this happen? By this point, ValType should be known
5854     // to be trivially copyable.
5855     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5856         << ValType << Ptr->getSourceRange();
5857     return ExprError();
5858   }
5859 
5860   // All atomic operations have an overload which takes a pointer to a volatile
5861   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5862   // into the result or the other operands. Similarly atomic_load takes a
5863   // pointer to a const 'A'.
5864   ValType.removeLocalVolatile();
5865   ValType.removeLocalConst();
5866   QualType ResultType = ValType;
5867   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5868       Form == Init)
5869     ResultType = Context.VoidTy;
5870   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5871     ResultType = Context.BoolTy;
5872 
5873   // The type of a parameter passed 'by value'. In the GNU atomics, such
5874   // arguments are actually passed as pointers.
5875   QualType ByValType = ValType; // 'CP'
5876   bool IsPassedByAddress = false;
5877   if (!IsC11 && !IsHIP && !IsN) {
5878     ByValType = Ptr->getType();
5879     IsPassedByAddress = true;
5880   }
5881 
5882   SmallVector<Expr *, 5> APIOrderedArgs;
5883   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5884     APIOrderedArgs.push_back(Args[0]);
5885     switch (Form) {
5886     case Init:
5887     case Load:
5888       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5889       break;
5890     case LoadCopy:
5891     case Copy:
5892     case Arithmetic:
5893     case Xchg:
5894       APIOrderedArgs.push_back(Args[2]); // Val1
5895       APIOrderedArgs.push_back(Args[1]); // Order
5896       break;
5897     case GNUXchg:
5898       APIOrderedArgs.push_back(Args[2]); // Val1
5899       APIOrderedArgs.push_back(Args[3]); // Val2
5900       APIOrderedArgs.push_back(Args[1]); // Order
5901       break;
5902     case C11CmpXchg:
5903       APIOrderedArgs.push_back(Args[2]); // Val1
5904       APIOrderedArgs.push_back(Args[4]); // Val2
5905       APIOrderedArgs.push_back(Args[1]); // Order
5906       APIOrderedArgs.push_back(Args[3]); // OrderFail
5907       break;
5908     case GNUCmpXchg:
5909       APIOrderedArgs.push_back(Args[2]); // Val1
5910       APIOrderedArgs.push_back(Args[4]); // Val2
5911       APIOrderedArgs.push_back(Args[5]); // Weak
5912       APIOrderedArgs.push_back(Args[1]); // Order
5913       APIOrderedArgs.push_back(Args[3]); // OrderFail
5914       break;
5915     }
5916   } else
5917     APIOrderedArgs.append(Args.begin(), Args.end());
5918 
5919   // The first argument's non-CV pointer type is used to deduce the type of
5920   // subsequent arguments, except for:
5921   //  - weak flag (always converted to bool)
5922   //  - memory order (always converted to int)
5923   //  - scope  (always converted to int)
5924   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5925     QualType Ty;
5926     if (i < NumVals[Form] + 1) {
5927       switch (i) {
5928       case 0:
5929         // The first argument is always a pointer. It has a fixed type.
5930         // It is always dereferenced, a nullptr is undefined.
5931         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5932         // Nothing else to do: we already know all we want about this pointer.
5933         continue;
5934       case 1:
5935         // The second argument is the non-atomic operand. For arithmetic, this
5936         // is always passed by value, and for a compare_exchange it is always
5937         // passed by address. For the rest, GNU uses by-address and C11 uses
5938         // by-value.
5939         assert(Form != Load);
5940         if (Form == Arithmetic && ValType->isPointerType())
5941           Ty = Context.getPointerDiffType();
5942         else if (Form == Init || Form == Arithmetic)
5943           Ty = ValType;
5944         else if (Form == Copy || Form == Xchg) {
5945           if (IsPassedByAddress) {
5946             // The value pointer is always dereferenced, a nullptr is undefined.
5947             CheckNonNullArgument(*this, APIOrderedArgs[i],
5948                                  ExprRange.getBegin());
5949           }
5950           Ty = ByValType;
5951         } else {
5952           Expr *ValArg = APIOrderedArgs[i];
5953           // The value pointer is always dereferenced, a nullptr is undefined.
5954           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5955           LangAS AS = LangAS::Default;
5956           // Keep address space of non-atomic pointer type.
5957           if (const PointerType *PtrTy =
5958                   ValArg->getType()->getAs<PointerType>()) {
5959             AS = PtrTy->getPointeeType().getAddressSpace();
5960           }
5961           Ty = Context.getPointerType(
5962               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5963         }
5964         break;
5965       case 2:
5966         // The third argument to compare_exchange / GNU exchange is the desired
5967         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5968         if (IsPassedByAddress)
5969           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5970         Ty = ByValType;
5971         break;
5972       case 3:
5973         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5974         Ty = Context.BoolTy;
5975         break;
5976       }
5977     } else {
5978       // The order(s) and scope are always converted to int.
5979       Ty = Context.IntTy;
5980     }
5981 
5982     InitializedEntity Entity =
5983         InitializedEntity::InitializeParameter(Context, Ty, false);
5984     ExprResult Arg = APIOrderedArgs[i];
5985     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5986     if (Arg.isInvalid())
5987       return true;
5988     APIOrderedArgs[i] = Arg.get();
5989   }
5990 
5991   // Permute the arguments into a 'consistent' order.
5992   SmallVector<Expr*, 5> SubExprs;
5993   SubExprs.push_back(Ptr);
5994   switch (Form) {
5995   case Init:
5996     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5997     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5998     break;
5999   case Load:
6000     SubExprs.push_back(APIOrderedArgs[1]); // Order
6001     break;
6002   case LoadCopy:
6003   case Copy:
6004   case Arithmetic:
6005   case Xchg:
6006     SubExprs.push_back(APIOrderedArgs[2]); // Order
6007     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6008     break;
6009   case GNUXchg:
6010     // Note, AtomicExpr::getVal2() has a special case for this atomic.
6011     SubExprs.push_back(APIOrderedArgs[3]); // Order
6012     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6013     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6014     break;
6015   case C11CmpXchg:
6016     SubExprs.push_back(APIOrderedArgs[3]); // Order
6017     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6018     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
6019     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6020     break;
6021   case GNUCmpXchg:
6022     SubExprs.push_back(APIOrderedArgs[4]); // Order
6023     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6024     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
6025     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6026     SubExprs.push_back(APIOrderedArgs[3]); // Weak
6027     break;
6028   }
6029 
6030   if (SubExprs.size() >= 2 && Form != Init) {
6031     if (Optional<llvm::APSInt> Result =
6032             SubExprs[1]->getIntegerConstantExpr(Context))
6033       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
6034         Diag(SubExprs[1]->getBeginLoc(),
6035              diag::warn_atomic_op_has_invalid_memory_order)
6036             << SubExprs[1]->getSourceRange();
6037   }
6038 
6039   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
6040     auto *Scope = Args[Args.size() - 1];
6041     if (Optional<llvm::APSInt> Result =
6042             Scope->getIntegerConstantExpr(Context)) {
6043       if (!ScopeModel->isValid(Result->getZExtValue()))
6044         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
6045             << Scope->getSourceRange();
6046     }
6047     SubExprs.push_back(Scope);
6048   }
6049 
6050   AtomicExpr *AE = new (Context)
6051       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
6052 
6053   if ((Op == AtomicExpr::AO__c11_atomic_load ||
6054        Op == AtomicExpr::AO__c11_atomic_store ||
6055        Op == AtomicExpr::AO__opencl_atomic_load ||
6056        Op == AtomicExpr::AO__hip_atomic_load ||
6057        Op == AtomicExpr::AO__opencl_atomic_store ||
6058        Op == AtomicExpr::AO__hip_atomic_store) &&
6059       Context.AtomicUsesUnsupportedLibcall(AE))
6060     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
6061         << ((Op == AtomicExpr::AO__c11_atomic_load ||
6062              Op == AtomicExpr::AO__opencl_atomic_load ||
6063              Op == AtomicExpr::AO__hip_atomic_load)
6064                 ? 0
6065                 : 1);
6066 
6067   if (ValType->isBitIntType()) {
6068     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
6069     return ExprError();
6070   }
6071 
6072   return AE;
6073 }
6074 
6075 /// checkBuiltinArgument - Given a call to a builtin function, perform
6076 /// normal type-checking on the given argument, updating the call in
6077 /// place.  This is useful when a builtin function requires custom
6078 /// type-checking for some of its arguments but not necessarily all of
6079 /// them.
6080 ///
6081 /// Returns true on error.
6082 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
6083   FunctionDecl *Fn = E->getDirectCallee();
6084   assert(Fn && "builtin call without direct callee!");
6085 
6086   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
6087   InitializedEntity Entity =
6088     InitializedEntity::InitializeParameter(S.Context, Param);
6089 
6090   ExprResult Arg = E->getArg(0);
6091   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
6092   if (Arg.isInvalid())
6093     return true;
6094 
6095   E->setArg(ArgIndex, Arg.get());
6096   return false;
6097 }
6098 
6099 /// We have a call to a function like __sync_fetch_and_add, which is an
6100 /// overloaded function based on the pointer type of its first argument.
6101 /// The main BuildCallExpr routines have already promoted the types of
6102 /// arguments because all of these calls are prototyped as void(...).
6103 ///
6104 /// This function goes through and does final semantic checking for these
6105 /// builtins, as well as generating any warnings.
6106 ExprResult
6107 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
6108   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
6109   Expr *Callee = TheCall->getCallee();
6110   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
6111   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6112 
6113   // Ensure that we have at least one argument to do type inference from.
6114   if (TheCall->getNumArgs() < 1) {
6115     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6116         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
6117     return ExprError();
6118   }
6119 
6120   // Inspect the first argument of the atomic builtin.  This should always be
6121   // a pointer type, whose element is an integral scalar or pointer type.
6122   // Because it is a pointer type, we don't have to worry about any implicit
6123   // casts here.
6124   // FIXME: We don't allow floating point scalars as input.
6125   Expr *FirstArg = TheCall->getArg(0);
6126   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
6127   if (FirstArgResult.isInvalid())
6128     return ExprError();
6129   FirstArg = FirstArgResult.get();
6130   TheCall->setArg(0, FirstArg);
6131 
6132   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
6133   if (!pointerType) {
6134     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
6135         << FirstArg->getType() << FirstArg->getSourceRange();
6136     return ExprError();
6137   }
6138 
6139   QualType ValType = pointerType->getPointeeType();
6140   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6141       !ValType->isBlockPointerType()) {
6142     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
6143         << FirstArg->getType() << FirstArg->getSourceRange();
6144     return ExprError();
6145   }
6146 
6147   if (ValType.isConstQualified()) {
6148     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
6149         << FirstArg->getType() << FirstArg->getSourceRange();
6150     return ExprError();
6151   }
6152 
6153   switch (ValType.getObjCLifetime()) {
6154   case Qualifiers::OCL_None:
6155   case Qualifiers::OCL_ExplicitNone:
6156     // okay
6157     break;
6158 
6159   case Qualifiers::OCL_Weak:
6160   case Qualifiers::OCL_Strong:
6161   case Qualifiers::OCL_Autoreleasing:
6162     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
6163         << ValType << FirstArg->getSourceRange();
6164     return ExprError();
6165   }
6166 
6167   // Strip any qualifiers off ValType.
6168   ValType = ValType.getUnqualifiedType();
6169 
6170   // The majority of builtins return a value, but a few have special return
6171   // types, so allow them to override appropriately below.
6172   QualType ResultType = ValType;
6173 
6174   // We need to figure out which concrete builtin this maps onto.  For example,
6175   // __sync_fetch_and_add with a 2 byte object turns into
6176   // __sync_fetch_and_add_2.
6177 #define BUILTIN_ROW(x) \
6178   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
6179     Builtin::BI##x##_8, Builtin::BI##x##_16 }
6180 
6181   static const unsigned BuiltinIndices[][5] = {
6182     BUILTIN_ROW(__sync_fetch_and_add),
6183     BUILTIN_ROW(__sync_fetch_and_sub),
6184     BUILTIN_ROW(__sync_fetch_and_or),
6185     BUILTIN_ROW(__sync_fetch_and_and),
6186     BUILTIN_ROW(__sync_fetch_and_xor),
6187     BUILTIN_ROW(__sync_fetch_and_nand),
6188 
6189     BUILTIN_ROW(__sync_add_and_fetch),
6190     BUILTIN_ROW(__sync_sub_and_fetch),
6191     BUILTIN_ROW(__sync_and_and_fetch),
6192     BUILTIN_ROW(__sync_or_and_fetch),
6193     BUILTIN_ROW(__sync_xor_and_fetch),
6194     BUILTIN_ROW(__sync_nand_and_fetch),
6195 
6196     BUILTIN_ROW(__sync_val_compare_and_swap),
6197     BUILTIN_ROW(__sync_bool_compare_and_swap),
6198     BUILTIN_ROW(__sync_lock_test_and_set),
6199     BUILTIN_ROW(__sync_lock_release),
6200     BUILTIN_ROW(__sync_swap)
6201   };
6202 #undef BUILTIN_ROW
6203 
6204   // Determine the index of the size.
6205   unsigned SizeIndex;
6206   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
6207   case 1: SizeIndex = 0; break;
6208   case 2: SizeIndex = 1; break;
6209   case 4: SizeIndex = 2; break;
6210   case 8: SizeIndex = 3; break;
6211   case 16: SizeIndex = 4; break;
6212   default:
6213     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
6214         << FirstArg->getType() << FirstArg->getSourceRange();
6215     return ExprError();
6216   }
6217 
6218   // Each of these builtins has one pointer argument, followed by some number of
6219   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
6220   // that we ignore.  Find out which row of BuiltinIndices to read from as well
6221   // as the number of fixed args.
6222   unsigned BuiltinID = FDecl->getBuiltinID();
6223   unsigned BuiltinIndex, NumFixed = 1;
6224   bool WarnAboutSemanticsChange = false;
6225   switch (BuiltinID) {
6226   default: llvm_unreachable("Unknown overloaded atomic builtin!");
6227   case Builtin::BI__sync_fetch_and_add:
6228   case Builtin::BI__sync_fetch_and_add_1:
6229   case Builtin::BI__sync_fetch_and_add_2:
6230   case Builtin::BI__sync_fetch_and_add_4:
6231   case Builtin::BI__sync_fetch_and_add_8:
6232   case Builtin::BI__sync_fetch_and_add_16:
6233     BuiltinIndex = 0;
6234     break;
6235 
6236   case Builtin::BI__sync_fetch_and_sub:
6237   case Builtin::BI__sync_fetch_and_sub_1:
6238   case Builtin::BI__sync_fetch_and_sub_2:
6239   case Builtin::BI__sync_fetch_and_sub_4:
6240   case Builtin::BI__sync_fetch_and_sub_8:
6241   case Builtin::BI__sync_fetch_and_sub_16:
6242     BuiltinIndex = 1;
6243     break;
6244 
6245   case Builtin::BI__sync_fetch_and_or:
6246   case Builtin::BI__sync_fetch_and_or_1:
6247   case Builtin::BI__sync_fetch_and_or_2:
6248   case Builtin::BI__sync_fetch_and_or_4:
6249   case Builtin::BI__sync_fetch_and_or_8:
6250   case Builtin::BI__sync_fetch_and_or_16:
6251     BuiltinIndex = 2;
6252     break;
6253 
6254   case Builtin::BI__sync_fetch_and_and:
6255   case Builtin::BI__sync_fetch_and_and_1:
6256   case Builtin::BI__sync_fetch_and_and_2:
6257   case Builtin::BI__sync_fetch_and_and_4:
6258   case Builtin::BI__sync_fetch_and_and_8:
6259   case Builtin::BI__sync_fetch_and_and_16:
6260     BuiltinIndex = 3;
6261     break;
6262 
6263   case Builtin::BI__sync_fetch_and_xor:
6264   case Builtin::BI__sync_fetch_and_xor_1:
6265   case Builtin::BI__sync_fetch_and_xor_2:
6266   case Builtin::BI__sync_fetch_and_xor_4:
6267   case Builtin::BI__sync_fetch_and_xor_8:
6268   case Builtin::BI__sync_fetch_and_xor_16:
6269     BuiltinIndex = 4;
6270     break;
6271 
6272   case Builtin::BI__sync_fetch_and_nand:
6273   case Builtin::BI__sync_fetch_and_nand_1:
6274   case Builtin::BI__sync_fetch_and_nand_2:
6275   case Builtin::BI__sync_fetch_and_nand_4:
6276   case Builtin::BI__sync_fetch_and_nand_8:
6277   case Builtin::BI__sync_fetch_and_nand_16:
6278     BuiltinIndex = 5;
6279     WarnAboutSemanticsChange = true;
6280     break;
6281 
6282   case Builtin::BI__sync_add_and_fetch:
6283   case Builtin::BI__sync_add_and_fetch_1:
6284   case Builtin::BI__sync_add_and_fetch_2:
6285   case Builtin::BI__sync_add_and_fetch_4:
6286   case Builtin::BI__sync_add_and_fetch_8:
6287   case Builtin::BI__sync_add_and_fetch_16:
6288     BuiltinIndex = 6;
6289     break;
6290 
6291   case Builtin::BI__sync_sub_and_fetch:
6292   case Builtin::BI__sync_sub_and_fetch_1:
6293   case Builtin::BI__sync_sub_and_fetch_2:
6294   case Builtin::BI__sync_sub_and_fetch_4:
6295   case Builtin::BI__sync_sub_and_fetch_8:
6296   case Builtin::BI__sync_sub_and_fetch_16:
6297     BuiltinIndex = 7;
6298     break;
6299 
6300   case Builtin::BI__sync_and_and_fetch:
6301   case Builtin::BI__sync_and_and_fetch_1:
6302   case Builtin::BI__sync_and_and_fetch_2:
6303   case Builtin::BI__sync_and_and_fetch_4:
6304   case Builtin::BI__sync_and_and_fetch_8:
6305   case Builtin::BI__sync_and_and_fetch_16:
6306     BuiltinIndex = 8;
6307     break;
6308 
6309   case Builtin::BI__sync_or_and_fetch:
6310   case Builtin::BI__sync_or_and_fetch_1:
6311   case Builtin::BI__sync_or_and_fetch_2:
6312   case Builtin::BI__sync_or_and_fetch_4:
6313   case Builtin::BI__sync_or_and_fetch_8:
6314   case Builtin::BI__sync_or_and_fetch_16:
6315     BuiltinIndex = 9;
6316     break;
6317 
6318   case Builtin::BI__sync_xor_and_fetch:
6319   case Builtin::BI__sync_xor_and_fetch_1:
6320   case Builtin::BI__sync_xor_and_fetch_2:
6321   case Builtin::BI__sync_xor_and_fetch_4:
6322   case Builtin::BI__sync_xor_and_fetch_8:
6323   case Builtin::BI__sync_xor_and_fetch_16:
6324     BuiltinIndex = 10;
6325     break;
6326 
6327   case Builtin::BI__sync_nand_and_fetch:
6328   case Builtin::BI__sync_nand_and_fetch_1:
6329   case Builtin::BI__sync_nand_and_fetch_2:
6330   case Builtin::BI__sync_nand_and_fetch_4:
6331   case Builtin::BI__sync_nand_and_fetch_8:
6332   case Builtin::BI__sync_nand_and_fetch_16:
6333     BuiltinIndex = 11;
6334     WarnAboutSemanticsChange = true;
6335     break;
6336 
6337   case Builtin::BI__sync_val_compare_and_swap:
6338   case Builtin::BI__sync_val_compare_and_swap_1:
6339   case Builtin::BI__sync_val_compare_and_swap_2:
6340   case Builtin::BI__sync_val_compare_and_swap_4:
6341   case Builtin::BI__sync_val_compare_and_swap_8:
6342   case Builtin::BI__sync_val_compare_and_swap_16:
6343     BuiltinIndex = 12;
6344     NumFixed = 2;
6345     break;
6346 
6347   case Builtin::BI__sync_bool_compare_and_swap:
6348   case Builtin::BI__sync_bool_compare_and_swap_1:
6349   case Builtin::BI__sync_bool_compare_and_swap_2:
6350   case Builtin::BI__sync_bool_compare_and_swap_4:
6351   case Builtin::BI__sync_bool_compare_and_swap_8:
6352   case Builtin::BI__sync_bool_compare_and_swap_16:
6353     BuiltinIndex = 13;
6354     NumFixed = 2;
6355     ResultType = Context.BoolTy;
6356     break;
6357 
6358   case Builtin::BI__sync_lock_test_and_set:
6359   case Builtin::BI__sync_lock_test_and_set_1:
6360   case Builtin::BI__sync_lock_test_and_set_2:
6361   case Builtin::BI__sync_lock_test_and_set_4:
6362   case Builtin::BI__sync_lock_test_and_set_8:
6363   case Builtin::BI__sync_lock_test_and_set_16:
6364     BuiltinIndex = 14;
6365     break;
6366 
6367   case Builtin::BI__sync_lock_release:
6368   case Builtin::BI__sync_lock_release_1:
6369   case Builtin::BI__sync_lock_release_2:
6370   case Builtin::BI__sync_lock_release_4:
6371   case Builtin::BI__sync_lock_release_8:
6372   case Builtin::BI__sync_lock_release_16:
6373     BuiltinIndex = 15;
6374     NumFixed = 0;
6375     ResultType = Context.VoidTy;
6376     break;
6377 
6378   case Builtin::BI__sync_swap:
6379   case Builtin::BI__sync_swap_1:
6380   case Builtin::BI__sync_swap_2:
6381   case Builtin::BI__sync_swap_4:
6382   case Builtin::BI__sync_swap_8:
6383   case Builtin::BI__sync_swap_16:
6384     BuiltinIndex = 16;
6385     break;
6386   }
6387 
6388   // Now that we know how many fixed arguments we expect, first check that we
6389   // have at least that many.
6390   if (TheCall->getNumArgs() < 1+NumFixed) {
6391     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6392         << 0 << 1 + NumFixed << TheCall->getNumArgs()
6393         << Callee->getSourceRange();
6394     return ExprError();
6395   }
6396 
6397   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6398       << Callee->getSourceRange();
6399 
6400   if (WarnAboutSemanticsChange) {
6401     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6402         << Callee->getSourceRange();
6403   }
6404 
6405   // Get the decl for the concrete builtin from this, we can tell what the
6406   // concrete integer type we should convert to is.
6407   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6408   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6409   FunctionDecl *NewBuiltinDecl;
6410   if (NewBuiltinID == BuiltinID)
6411     NewBuiltinDecl = FDecl;
6412   else {
6413     // Perform builtin lookup to avoid redeclaring it.
6414     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6415     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6416     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6417     assert(Res.getFoundDecl());
6418     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6419     if (!NewBuiltinDecl)
6420       return ExprError();
6421   }
6422 
6423   // The first argument --- the pointer --- has a fixed type; we
6424   // deduce the types of the rest of the arguments accordingly.  Walk
6425   // the remaining arguments, converting them to the deduced value type.
6426   for (unsigned i = 0; i != NumFixed; ++i) {
6427     ExprResult Arg = TheCall->getArg(i+1);
6428 
6429     // GCC does an implicit conversion to the pointer or integer ValType.  This
6430     // can fail in some cases (1i -> int**), check for this error case now.
6431     // Initialize the argument.
6432     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6433                                                    ValType, /*consume*/ false);
6434     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6435     if (Arg.isInvalid())
6436       return ExprError();
6437 
6438     // Okay, we have something that *can* be converted to the right type.  Check
6439     // to see if there is a potentially weird extension going on here.  This can
6440     // happen when you do an atomic operation on something like an char* and
6441     // pass in 42.  The 42 gets converted to char.  This is even more strange
6442     // for things like 45.123 -> char, etc.
6443     // FIXME: Do this check.
6444     TheCall->setArg(i+1, Arg.get());
6445   }
6446 
6447   // Create a new DeclRefExpr to refer to the new decl.
6448   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6449       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6450       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6451       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6452 
6453   // Set the callee in the CallExpr.
6454   // FIXME: This loses syntactic information.
6455   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6456   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6457                                               CK_BuiltinFnToFnPtr);
6458   TheCall->setCallee(PromotedCall.get());
6459 
6460   // Change the result type of the call to match the original value type. This
6461   // is arbitrary, but the codegen for these builtins ins design to handle it
6462   // gracefully.
6463   TheCall->setType(ResultType);
6464 
6465   // Prohibit problematic uses of bit-precise integer types with atomic
6466   // builtins. The arguments would have already been converted to the first
6467   // argument's type, so only need to check the first argument.
6468   const auto *BitIntValType = ValType->getAs<BitIntType>();
6469   if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
6470     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6471     return ExprError();
6472   }
6473 
6474   return TheCallResult;
6475 }
6476 
6477 /// SemaBuiltinNontemporalOverloaded - We have a call to
6478 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6479 /// overloaded function based on the pointer type of its last argument.
6480 ///
6481 /// This function goes through and does final semantic checking for these
6482 /// builtins.
6483 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6484   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6485   DeclRefExpr *DRE =
6486       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6487   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6488   unsigned BuiltinID = FDecl->getBuiltinID();
6489   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6490           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6491          "Unexpected nontemporal load/store builtin!");
6492   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6493   unsigned numArgs = isStore ? 2 : 1;
6494 
6495   // Ensure that we have the proper number of arguments.
6496   if (checkArgCount(*this, TheCall, numArgs))
6497     return ExprError();
6498 
6499   // Inspect the last argument of the nontemporal builtin.  This should always
6500   // be a pointer type, from which we imply the type of the memory access.
6501   // Because it is a pointer type, we don't have to worry about any implicit
6502   // casts here.
6503   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6504   ExprResult PointerArgResult =
6505       DefaultFunctionArrayLvalueConversion(PointerArg);
6506 
6507   if (PointerArgResult.isInvalid())
6508     return ExprError();
6509   PointerArg = PointerArgResult.get();
6510   TheCall->setArg(numArgs - 1, PointerArg);
6511 
6512   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6513   if (!pointerType) {
6514     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6515         << PointerArg->getType() << PointerArg->getSourceRange();
6516     return ExprError();
6517   }
6518 
6519   QualType ValType = pointerType->getPointeeType();
6520 
6521   // Strip any qualifiers off ValType.
6522   ValType = ValType.getUnqualifiedType();
6523   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6524       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6525       !ValType->isVectorType()) {
6526     Diag(DRE->getBeginLoc(),
6527          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6528         << PointerArg->getType() << PointerArg->getSourceRange();
6529     return ExprError();
6530   }
6531 
6532   if (!isStore) {
6533     TheCall->setType(ValType);
6534     return TheCallResult;
6535   }
6536 
6537   ExprResult ValArg = TheCall->getArg(0);
6538   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6539       Context, ValType, /*consume*/ false);
6540   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6541   if (ValArg.isInvalid())
6542     return ExprError();
6543 
6544   TheCall->setArg(0, ValArg.get());
6545   TheCall->setType(Context.VoidTy);
6546   return TheCallResult;
6547 }
6548 
6549 /// CheckObjCString - Checks that the argument to the builtin
6550 /// CFString constructor is correct
6551 /// Note: It might also make sense to do the UTF-16 conversion here (would
6552 /// simplify the backend).
6553 bool Sema::CheckObjCString(Expr *Arg) {
6554   Arg = Arg->IgnoreParenCasts();
6555   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6556 
6557   if (!Literal || !Literal->isAscii()) {
6558     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6559         << Arg->getSourceRange();
6560     return true;
6561   }
6562 
6563   if (Literal->containsNonAsciiOrNull()) {
6564     StringRef String = Literal->getString();
6565     unsigned NumBytes = String.size();
6566     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6567     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6568     llvm::UTF16 *ToPtr = &ToBuf[0];
6569 
6570     llvm::ConversionResult Result =
6571         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6572                                  ToPtr + NumBytes, llvm::strictConversion);
6573     // Check for conversion failure.
6574     if (Result != llvm::conversionOK)
6575       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6576           << Arg->getSourceRange();
6577   }
6578   return false;
6579 }
6580 
6581 /// CheckObjCString - Checks that the format string argument to the os_log()
6582 /// and os_trace() functions is correct, and converts it to const char *.
6583 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6584   Arg = Arg->IgnoreParenCasts();
6585   auto *Literal = dyn_cast<StringLiteral>(Arg);
6586   if (!Literal) {
6587     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6588       Literal = ObjcLiteral->getString();
6589     }
6590   }
6591 
6592   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6593     return ExprError(
6594         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6595         << Arg->getSourceRange());
6596   }
6597 
6598   ExprResult Result(Literal);
6599   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6600   InitializedEntity Entity =
6601       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6602   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6603   return Result;
6604 }
6605 
6606 /// Check that the user is calling the appropriate va_start builtin for the
6607 /// target and calling convention.
6608 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6609   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6610   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6611   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6612                     TT.getArch() == llvm::Triple::aarch64_32);
6613   bool IsWindows = TT.isOSWindows();
6614   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6615   if (IsX64 || IsAArch64) {
6616     CallingConv CC = CC_C;
6617     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6618       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6619     if (IsMSVAStart) {
6620       // Don't allow this in System V ABI functions.
6621       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6622         return S.Diag(Fn->getBeginLoc(),
6623                       diag::err_ms_va_start_used_in_sysv_function);
6624     } else {
6625       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6626       // On x64 Windows, don't allow this in System V ABI functions.
6627       // (Yes, that means there's no corresponding way to support variadic
6628       // System V ABI functions on Windows.)
6629       if ((IsWindows && CC == CC_X86_64SysV) ||
6630           (!IsWindows && CC == CC_Win64))
6631         return S.Diag(Fn->getBeginLoc(),
6632                       diag::err_va_start_used_in_wrong_abi_function)
6633                << !IsWindows;
6634     }
6635     return false;
6636   }
6637 
6638   if (IsMSVAStart)
6639     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6640   return false;
6641 }
6642 
6643 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6644                                              ParmVarDecl **LastParam = nullptr) {
6645   // Determine whether the current function, block, or obj-c method is variadic
6646   // and get its parameter list.
6647   bool IsVariadic = false;
6648   ArrayRef<ParmVarDecl *> Params;
6649   DeclContext *Caller = S.CurContext;
6650   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6651     IsVariadic = Block->isVariadic();
6652     Params = Block->parameters();
6653   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6654     IsVariadic = FD->isVariadic();
6655     Params = FD->parameters();
6656   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6657     IsVariadic = MD->isVariadic();
6658     // FIXME: This isn't correct for methods (results in bogus warning).
6659     Params = MD->parameters();
6660   } else if (isa<CapturedDecl>(Caller)) {
6661     // We don't support va_start in a CapturedDecl.
6662     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6663     return true;
6664   } else {
6665     // This must be some other declcontext that parses exprs.
6666     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6667     return true;
6668   }
6669 
6670   if (!IsVariadic) {
6671     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6672     return true;
6673   }
6674 
6675   if (LastParam)
6676     *LastParam = Params.empty() ? nullptr : Params.back();
6677 
6678   return false;
6679 }
6680 
6681 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6682 /// for validity.  Emit an error and return true on failure; return false
6683 /// on success.
6684 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6685   Expr *Fn = TheCall->getCallee();
6686 
6687   if (checkVAStartABI(*this, BuiltinID, Fn))
6688     return true;
6689 
6690   if (checkArgCount(*this, TheCall, 2))
6691     return true;
6692 
6693   // Type-check the first argument normally.
6694   if (checkBuiltinArgument(*this, TheCall, 0))
6695     return true;
6696 
6697   // Check that the current function is variadic, and get its last parameter.
6698   ParmVarDecl *LastParam;
6699   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6700     return true;
6701 
6702   // Verify that the second argument to the builtin is the last argument of the
6703   // current function or method.
6704   bool SecondArgIsLastNamedArgument = false;
6705   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6706 
6707   // These are valid if SecondArgIsLastNamedArgument is false after the next
6708   // block.
6709   QualType Type;
6710   SourceLocation ParamLoc;
6711   bool IsCRegister = false;
6712 
6713   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6714     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6715       SecondArgIsLastNamedArgument = PV == LastParam;
6716 
6717       Type = PV->getType();
6718       ParamLoc = PV->getLocation();
6719       IsCRegister =
6720           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6721     }
6722   }
6723 
6724   if (!SecondArgIsLastNamedArgument)
6725     Diag(TheCall->getArg(1)->getBeginLoc(),
6726          diag::warn_second_arg_of_va_start_not_last_named_param);
6727   else if (IsCRegister || Type->isReferenceType() ||
6728            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6729              // Promotable integers are UB, but enumerations need a bit of
6730              // extra checking to see what their promotable type actually is.
6731              if (!Type->isPromotableIntegerType())
6732                return false;
6733              if (!Type->isEnumeralType())
6734                return true;
6735              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6736              return !(ED &&
6737                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6738            }()) {
6739     unsigned Reason = 0;
6740     if (Type->isReferenceType())  Reason = 1;
6741     else if (IsCRegister)         Reason = 2;
6742     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6743     Diag(ParamLoc, diag::note_parameter_type) << Type;
6744   }
6745 
6746   TheCall->setType(Context.VoidTy);
6747   return false;
6748 }
6749 
6750 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6751   auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6752     const LangOptions &LO = getLangOpts();
6753 
6754     if (LO.CPlusPlus)
6755       return Arg->getType()
6756                  .getCanonicalType()
6757                  .getTypePtr()
6758                  ->getPointeeType()
6759                  .withoutLocalFastQualifiers() == Context.CharTy;
6760 
6761     // In C, allow aliasing through `char *`, this is required for AArch64 at
6762     // least.
6763     return true;
6764   };
6765 
6766   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6767   //                 const char *named_addr);
6768 
6769   Expr *Func = Call->getCallee();
6770 
6771   if (Call->getNumArgs() < 3)
6772     return Diag(Call->getEndLoc(),
6773                 diag::err_typecheck_call_too_few_args_at_least)
6774            << 0 /*function call*/ << 3 << Call->getNumArgs();
6775 
6776   // Type-check the first argument normally.
6777   if (checkBuiltinArgument(*this, Call, 0))
6778     return true;
6779 
6780   // Check that the current function is variadic.
6781   if (checkVAStartIsInVariadicFunction(*this, Func))
6782     return true;
6783 
6784   // __va_start on Windows does not validate the parameter qualifiers
6785 
6786   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6787   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6788 
6789   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6790   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6791 
6792   const QualType &ConstCharPtrTy =
6793       Context.getPointerType(Context.CharTy.withConst());
6794   if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6795     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6796         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6797         << 0                                      /* qualifier difference */
6798         << 3                                      /* parameter mismatch */
6799         << 2 << Arg1->getType() << ConstCharPtrTy;
6800 
6801   const QualType SizeTy = Context.getSizeType();
6802   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6803     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6804         << Arg2->getType() << SizeTy << 1 /* different class */
6805         << 0                              /* qualifier difference */
6806         << 3                              /* parameter mismatch */
6807         << 3 << Arg2->getType() << SizeTy;
6808 
6809   return false;
6810 }
6811 
6812 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6813 /// friends.  This is declared to take (...), so we have to check everything.
6814 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6815   if (checkArgCount(*this, TheCall, 2))
6816     return true;
6817 
6818   ExprResult OrigArg0 = TheCall->getArg(0);
6819   ExprResult OrigArg1 = TheCall->getArg(1);
6820 
6821   // Do standard promotions between the two arguments, returning their common
6822   // type.
6823   QualType Res = UsualArithmeticConversions(
6824       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6825   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6826     return true;
6827 
6828   // Make sure any conversions are pushed back into the call; this is
6829   // type safe since unordered compare builtins are declared as "_Bool
6830   // foo(...)".
6831   TheCall->setArg(0, OrigArg0.get());
6832   TheCall->setArg(1, OrigArg1.get());
6833 
6834   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6835     return false;
6836 
6837   // If the common type isn't a real floating type, then the arguments were
6838   // invalid for this operation.
6839   if (Res.isNull() || !Res->isRealFloatingType())
6840     return Diag(OrigArg0.get()->getBeginLoc(),
6841                 diag::err_typecheck_call_invalid_ordered_compare)
6842            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6843            << SourceRange(OrigArg0.get()->getBeginLoc(),
6844                           OrigArg1.get()->getEndLoc());
6845 
6846   return false;
6847 }
6848 
6849 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6850 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6851 /// to check everything. We expect the last argument to be a floating point
6852 /// value.
6853 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6854   if (checkArgCount(*this, TheCall, NumArgs))
6855     return true;
6856 
6857   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6858   // on all preceding parameters just being int.  Try all of those.
6859   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6860     Expr *Arg = TheCall->getArg(i);
6861 
6862     if (Arg->isTypeDependent())
6863       return false;
6864 
6865     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6866 
6867     if (Res.isInvalid())
6868       return true;
6869     TheCall->setArg(i, Res.get());
6870   }
6871 
6872   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6873 
6874   if (OrigArg->isTypeDependent())
6875     return false;
6876 
6877   // Usual Unary Conversions will convert half to float, which we want for
6878   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6879   // type how it is, but do normal L->Rvalue conversions.
6880   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6881     OrigArg = UsualUnaryConversions(OrigArg).get();
6882   else
6883     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6884   TheCall->setArg(NumArgs - 1, OrigArg);
6885 
6886   // This operation requires a non-_Complex floating-point number.
6887   if (!OrigArg->getType()->isRealFloatingType())
6888     return Diag(OrigArg->getBeginLoc(),
6889                 diag::err_typecheck_call_invalid_unary_fp)
6890            << OrigArg->getType() << OrigArg->getSourceRange();
6891 
6892   return false;
6893 }
6894 
6895 /// Perform semantic analysis for a call to __builtin_complex.
6896 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6897   if (checkArgCount(*this, TheCall, 2))
6898     return true;
6899 
6900   bool Dependent = false;
6901   for (unsigned I = 0; I != 2; ++I) {
6902     Expr *Arg = TheCall->getArg(I);
6903     QualType T = Arg->getType();
6904     if (T->isDependentType()) {
6905       Dependent = true;
6906       continue;
6907     }
6908 
6909     // Despite supporting _Complex int, GCC requires a real floating point type
6910     // for the operands of __builtin_complex.
6911     if (!T->isRealFloatingType()) {
6912       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6913              << Arg->getType() << Arg->getSourceRange();
6914     }
6915 
6916     ExprResult Converted = DefaultLvalueConversion(Arg);
6917     if (Converted.isInvalid())
6918       return true;
6919     TheCall->setArg(I, Converted.get());
6920   }
6921 
6922   if (Dependent) {
6923     TheCall->setType(Context.DependentTy);
6924     return false;
6925   }
6926 
6927   Expr *Real = TheCall->getArg(0);
6928   Expr *Imag = TheCall->getArg(1);
6929   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6930     return Diag(Real->getBeginLoc(),
6931                 diag::err_typecheck_call_different_arg_types)
6932            << Real->getType() << Imag->getType()
6933            << Real->getSourceRange() << Imag->getSourceRange();
6934   }
6935 
6936   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6937   // don't allow this builtin to form those types either.
6938   // FIXME: Should we allow these types?
6939   if (Real->getType()->isFloat16Type())
6940     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6941            << "_Float16";
6942   if (Real->getType()->isHalfType())
6943     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6944            << "half";
6945 
6946   TheCall->setType(Context.getComplexType(Real->getType()));
6947   return false;
6948 }
6949 
6950 // Customized Sema Checking for VSX builtins that have the following signature:
6951 // vector [...] builtinName(vector [...], vector [...], const int);
6952 // Which takes the same type of vectors (any legal vector type) for the first
6953 // two arguments and takes compile time constant for the third argument.
6954 // Example builtins are :
6955 // vector double vec_xxpermdi(vector double, vector double, int);
6956 // vector short vec_xxsldwi(vector short, vector short, int);
6957 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6958   unsigned ExpectedNumArgs = 3;
6959   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6960     return true;
6961 
6962   // Check the third argument is a compile time constant
6963   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6964     return Diag(TheCall->getBeginLoc(),
6965                 diag::err_vsx_builtin_nonconstant_argument)
6966            << 3 /* argument index */ << TheCall->getDirectCallee()
6967            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6968                           TheCall->getArg(2)->getEndLoc());
6969 
6970   QualType Arg1Ty = TheCall->getArg(0)->getType();
6971   QualType Arg2Ty = TheCall->getArg(1)->getType();
6972 
6973   // Check the type of argument 1 and argument 2 are vectors.
6974   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6975   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6976       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6977     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6978            << TheCall->getDirectCallee()
6979            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6980                           TheCall->getArg(1)->getEndLoc());
6981   }
6982 
6983   // Check the first two arguments are the same type.
6984   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6985     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6986            << TheCall->getDirectCallee()
6987            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6988                           TheCall->getArg(1)->getEndLoc());
6989   }
6990 
6991   // When default clang type checking is turned off and the customized type
6992   // checking is used, the returning type of the function must be explicitly
6993   // set. Otherwise it is _Bool by default.
6994   TheCall->setType(Arg1Ty);
6995 
6996   return false;
6997 }
6998 
6999 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
7000 // This is declared to take (...), so we have to check everything.
7001 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
7002   if (TheCall->getNumArgs() < 2)
7003     return ExprError(Diag(TheCall->getEndLoc(),
7004                           diag::err_typecheck_call_too_few_args_at_least)
7005                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
7006                      << TheCall->getSourceRange());
7007 
7008   // Determine which of the following types of shufflevector we're checking:
7009   // 1) unary, vector mask: (lhs, mask)
7010   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
7011   QualType resType = TheCall->getArg(0)->getType();
7012   unsigned numElements = 0;
7013 
7014   if (!TheCall->getArg(0)->isTypeDependent() &&
7015       !TheCall->getArg(1)->isTypeDependent()) {
7016     QualType LHSType = TheCall->getArg(0)->getType();
7017     QualType RHSType = TheCall->getArg(1)->getType();
7018 
7019     if (!LHSType->isVectorType() || !RHSType->isVectorType())
7020       return ExprError(
7021           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
7022           << TheCall->getDirectCallee()
7023           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7024                          TheCall->getArg(1)->getEndLoc()));
7025 
7026     numElements = LHSType->castAs<VectorType>()->getNumElements();
7027     unsigned numResElements = TheCall->getNumArgs() - 2;
7028 
7029     // Check to see if we have a call with 2 vector arguments, the unary shuffle
7030     // with mask.  If so, verify that RHS is an integer vector type with the
7031     // same number of elts as lhs.
7032     if (TheCall->getNumArgs() == 2) {
7033       if (!RHSType->hasIntegerRepresentation() ||
7034           RHSType->castAs<VectorType>()->getNumElements() != numElements)
7035         return ExprError(Diag(TheCall->getBeginLoc(),
7036                               diag::err_vec_builtin_incompatible_vector)
7037                          << TheCall->getDirectCallee()
7038                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
7039                                         TheCall->getArg(1)->getEndLoc()));
7040     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
7041       return ExprError(Diag(TheCall->getBeginLoc(),
7042                             diag::err_vec_builtin_incompatible_vector)
7043                        << TheCall->getDirectCallee()
7044                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7045                                       TheCall->getArg(1)->getEndLoc()));
7046     } else if (numElements != numResElements) {
7047       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
7048       resType = Context.getVectorType(eltType, numResElements,
7049                                       VectorType::GenericVector);
7050     }
7051   }
7052 
7053   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
7054     if (TheCall->getArg(i)->isTypeDependent() ||
7055         TheCall->getArg(i)->isValueDependent())
7056       continue;
7057 
7058     Optional<llvm::APSInt> Result;
7059     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
7060       return ExprError(Diag(TheCall->getBeginLoc(),
7061                             diag::err_shufflevector_nonconstant_argument)
7062                        << TheCall->getArg(i)->getSourceRange());
7063 
7064     // Allow -1 which will be translated to undef in the IR.
7065     if (Result->isSigned() && Result->isAllOnes())
7066       continue;
7067 
7068     if (Result->getActiveBits() > 64 ||
7069         Result->getZExtValue() >= numElements * 2)
7070       return ExprError(Diag(TheCall->getBeginLoc(),
7071                             diag::err_shufflevector_argument_too_large)
7072                        << TheCall->getArg(i)->getSourceRange());
7073   }
7074 
7075   SmallVector<Expr*, 32> exprs;
7076 
7077   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
7078     exprs.push_back(TheCall->getArg(i));
7079     TheCall->setArg(i, nullptr);
7080   }
7081 
7082   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
7083                                          TheCall->getCallee()->getBeginLoc(),
7084                                          TheCall->getRParenLoc());
7085 }
7086 
7087 /// SemaConvertVectorExpr - Handle __builtin_convertvector
7088 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
7089                                        SourceLocation BuiltinLoc,
7090                                        SourceLocation RParenLoc) {
7091   ExprValueKind VK = VK_PRValue;
7092   ExprObjectKind OK = OK_Ordinary;
7093   QualType DstTy = TInfo->getType();
7094   QualType SrcTy = E->getType();
7095 
7096   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
7097     return ExprError(Diag(BuiltinLoc,
7098                           diag::err_convertvector_non_vector)
7099                      << E->getSourceRange());
7100   if (!DstTy->isVectorType() && !DstTy->isDependentType())
7101     return ExprError(Diag(BuiltinLoc,
7102                           diag::err_convertvector_non_vector_type));
7103 
7104   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
7105     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
7106     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
7107     if (SrcElts != DstElts)
7108       return ExprError(Diag(BuiltinLoc,
7109                             diag::err_convertvector_incompatible_vector)
7110                        << E->getSourceRange());
7111   }
7112 
7113   return new (Context)
7114       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
7115 }
7116 
7117 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
7118 // This is declared to take (const void*, ...) and can take two
7119 // optional constant int args.
7120 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
7121   unsigned NumArgs = TheCall->getNumArgs();
7122 
7123   if (NumArgs > 3)
7124     return Diag(TheCall->getEndLoc(),
7125                 diag::err_typecheck_call_too_many_args_at_most)
7126            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7127 
7128   // Argument 0 is checked for us and the remaining arguments must be
7129   // constant integers.
7130   for (unsigned i = 1; i != NumArgs; ++i)
7131     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
7132       return true;
7133 
7134   return false;
7135 }
7136 
7137 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
7138 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
7139   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
7140     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
7141            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7142   if (checkArgCount(*this, TheCall, 1))
7143     return true;
7144   Expr *Arg = TheCall->getArg(0);
7145   if (Arg->isInstantiationDependent())
7146     return false;
7147 
7148   QualType ArgTy = Arg->getType();
7149   if (!ArgTy->hasFloatingRepresentation())
7150     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
7151            << ArgTy;
7152   if (Arg->isLValue()) {
7153     ExprResult FirstArg = DefaultLvalueConversion(Arg);
7154     TheCall->setArg(0, FirstArg.get());
7155   }
7156   TheCall->setType(TheCall->getArg(0)->getType());
7157   return false;
7158 }
7159 
7160 /// SemaBuiltinAssume - Handle __assume (MS Extension).
7161 // __assume does not evaluate its arguments, and should warn if its argument
7162 // has side effects.
7163 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
7164   Expr *Arg = TheCall->getArg(0);
7165   if (Arg->isInstantiationDependent()) return false;
7166 
7167   if (Arg->HasSideEffects(Context))
7168     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
7169         << Arg->getSourceRange()
7170         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
7171 
7172   return false;
7173 }
7174 
7175 /// Handle __builtin_alloca_with_align. This is declared
7176 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
7177 /// than 8.
7178 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
7179   // The alignment must be a constant integer.
7180   Expr *Arg = TheCall->getArg(1);
7181 
7182   // We can't check the value of a dependent argument.
7183   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7184     if (const auto *UE =
7185             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
7186       if (UE->getKind() == UETT_AlignOf ||
7187           UE->getKind() == UETT_PreferredAlignOf)
7188         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
7189             << Arg->getSourceRange();
7190 
7191     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
7192 
7193     if (!Result.isPowerOf2())
7194       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7195              << Arg->getSourceRange();
7196 
7197     if (Result < Context.getCharWidth())
7198       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
7199              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
7200 
7201     if (Result > std::numeric_limits<int32_t>::max())
7202       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
7203              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
7204   }
7205 
7206   return false;
7207 }
7208 
7209 /// Handle __builtin_assume_aligned. This is declared
7210 /// as (const void*, size_t, ...) and can take one optional constant int arg.
7211 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
7212   unsigned NumArgs = TheCall->getNumArgs();
7213 
7214   if (NumArgs > 3)
7215     return Diag(TheCall->getEndLoc(),
7216                 diag::err_typecheck_call_too_many_args_at_most)
7217            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7218 
7219   // The alignment must be a constant integer.
7220   Expr *Arg = TheCall->getArg(1);
7221 
7222   // We can't check the value of a dependent argument.
7223   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7224     llvm::APSInt Result;
7225     if (SemaBuiltinConstantArg(TheCall, 1, Result))
7226       return true;
7227 
7228     if (!Result.isPowerOf2())
7229       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7230              << Arg->getSourceRange();
7231 
7232     if (Result > Sema::MaximumAlignment)
7233       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
7234           << Arg->getSourceRange() << Sema::MaximumAlignment;
7235   }
7236 
7237   if (NumArgs > 2) {
7238     ExprResult Arg(TheCall->getArg(2));
7239     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
7240       Context.getSizeType(), false);
7241     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7242     if (Arg.isInvalid()) return true;
7243     TheCall->setArg(2, Arg.get());
7244   }
7245 
7246   return false;
7247 }
7248 
7249 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
7250   unsigned BuiltinID =
7251       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
7252   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
7253 
7254   unsigned NumArgs = TheCall->getNumArgs();
7255   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
7256   if (NumArgs < NumRequiredArgs) {
7257     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
7258            << 0 /* function call */ << NumRequiredArgs << NumArgs
7259            << TheCall->getSourceRange();
7260   }
7261   if (NumArgs >= NumRequiredArgs + 0x100) {
7262     return Diag(TheCall->getEndLoc(),
7263                 diag::err_typecheck_call_too_many_args_at_most)
7264            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
7265            << TheCall->getSourceRange();
7266   }
7267   unsigned i = 0;
7268 
7269   // For formatting call, check buffer arg.
7270   if (!IsSizeCall) {
7271     ExprResult Arg(TheCall->getArg(i));
7272     InitializedEntity Entity = InitializedEntity::InitializeParameter(
7273         Context, Context.VoidPtrTy, false);
7274     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7275     if (Arg.isInvalid())
7276       return true;
7277     TheCall->setArg(i, Arg.get());
7278     i++;
7279   }
7280 
7281   // Check string literal arg.
7282   unsigned FormatIdx = i;
7283   {
7284     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
7285     if (Arg.isInvalid())
7286       return true;
7287     TheCall->setArg(i, Arg.get());
7288     i++;
7289   }
7290 
7291   // Make sure variadic args are scalar.
7292   unsigned FirstDataArg = i;
7293   while (i < NumArgs) {
7294     ExprResult Arg = DefaultVariadicArgumentPromotion(
7295         TheCall->getArg(i), VariadicFunction, nullptr);
7296     if (Arg.isInvalid())
7297       return true;
7298     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
7299     if (ArgSize.getQuantity() >= 0x100) {
7300       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
7301              << i << (int)ArgSize.getQuantity() << 0xff
7302              << TheCall->getSourceRange();
7303     }
7304     TheCall->setArg(i, Arg.get());
7305     i++;
7306   }
7307 
7308   // Check formatting specifiers. NOTE: We're only doing this for the non-size
7309   // call to avoid duplicate diagnostics.
7310   if (!IsSizeCall) {
7311     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
7312     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
7313     bool Success = CheckFormatArguments(
7314         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
7315         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
7316         CheckedVarArgs);
7317     if (!Success)
7318       return true;
7319   }
7320 
7321   if (IsSizeCall) {
7322     TheCall->setType(Context.getSizeType());
7323   } else {
7324     TheCall->setType(Context.VoidPtrTy);
7325   }
7326   return false;
7327 }
7328 
7329 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
7330 /// TheCall is a constant expression.
7331 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7332                                   llvm::APSInt &Result) {
7333   Expr *Arg = TheCall->getArg(ArgNum);
7334   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
7335   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
7336 
7337   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
7338 
7339   Optional<llvm::APSInt> R;
7340   if (!(R = Arg->getIntegerConstantExpr(Context)))
7341     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
7342            << FDecl->getDeclName() << Arg->getSourceRange();
7343   Result = *R;
7344   return false;
7345 }
7346 
7347 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
7348 /// TheCall is a constant expression in the range [Low, High].
7349 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
7350                                        int Low, int High, bool RangeIsError) {
7351   if (isConstantEvaluated())
7352     return false;
7353   llvm::APSInt Result;
7354 
7355   // We can't check the value of a dependent argument.
7356   Expr *Arg = TheCall->getArg(ArgNum);
7357   if (Arg->isTypeDependent() || Arg->isValueDependent())
7358     return false;
7359 
7360   // Check constant-ness first.
7361   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7362     return true;
7363 
7364   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7365     if (RangeIsError)
7366       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
7367              << toString(Result, 10) << Low << High << Arg->getSourceRange();
7368     else
7369       // Defer the warning until we know if the code will be emitted so that
7370       // dead code can ignore this.
7371       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
7372                           PDiag(diag::warn_argument_invalid_range)
7373                               << toString(Result, 10) << Low << High
7374                               << Arg->getSourceRange());
7375   }
7376 
7377   return false;
7378 }
7379 
7380 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
7381 /// TheCall is a constant expression is a multiple of Num..
7382 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
7383                                           unsigned Num) {
7384   llvm::APSInt Result;
7385 
7386   // We can't check the value of a dependent argument.
7387   Expr *Arg = TheCall->getArg(ArgNum);
7388   if (Arg->isTypeDependent() || Arg->isValueDependent())
7389     return false;
7390 
7391   // Check constant-ness first.
7392   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7393     return true;
7394 
7395   if (Result.getSExtValue() % Num != 0)
7396     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7397            << Num << Arg->getSourceRange();
7398 
7399   return false;
7400 }
7401 
7402 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7403 /// constant expression representing a power of 2.
7404 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7405   llvm::APSInt Result;
7406 
7407   // We can't check the value of a dependent argument.
7408   Expr *Arg = TheCall->getArg(ArgNum);
7409   if (Arg->isTypeDependent() || Arg->isValueDependent())
7410     return false;
7411 
7412   // Check constant-ness first.
7413   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7414     return true;
7415 
7416   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7417   // and only if x is a power of 2.
7418   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7419     return false;
7420 
7421   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7422          << Arg->getSourceRange();
7423 }
7424 
7425 static bool IsShiftedByte(llvm::APSInt Value) {
7426   if (Value.isNegative())
7427     return false;
7428 
7429   // Check if it's a shifted byte, by shifting it down
7430   while (true) {
7431     // If the value fits in the bottom byte, the check passes.
7432     if (Value < 0x100)
7433       return true;
7434 
7435     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7436     // fails.
7437     if ((Value & 0xFF) != 0)
7438       return false;
7439 
7440     // If the bottom 8 bits are all 0, but something above that is nonzero,
7441     // then shifting the value right by 8 bits won't affect whether it's a
7442     // shifted byte or not. So do that, and go round again.
7443     Value >>= 8;
7444   }
7445 }
7446 
7447 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7448 /// a constant expression representing an arbitrary byte value shifted left by
7449 /// a multiple of 8 bits.
7450 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7451                                              unsigned ArgBits) {
7452   llvm::APSInt Result;
7453 
7454   // We can't check the value of a dependent argument.
7455   Expr *Arg = TheCall->getArg(ArgNum);
7456   if (Arg->isTypeDependent() || Arg->isValueDependent())
7457     return false;
7458 
7459   // Check constant-ness first.
7460   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7461     return true;
7462 
7463   // Truncate to the given size.
7464   Result = Result.getLoBits(ArgBits);
7465   Result.setIsUnsigned(true);
7466 
7467   if (IsShiftedByte(Result))
7468     return false;
7469 
7470   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7471          << Arg->getSourceRange();
7472 }
7473 
7474 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7475 /// TheCall is a constant expression representing either a shifted byte value,
7476 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7477 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7478 /// Arm MVE intrinsics.
7479 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7480                                                    int ArgNum,
7481                                                    unsigned ArgBits) {
7482   llvm::APSInt Result;
7483 
7484   // We can't check the value of a dependent argument.
7485   Expr *Arg = TheCall->getArg(ArgNum);
7486   if (Arg->isTypeDependent() || Arg->isValueDependent())
7487     return false;
7488 
7489   // Check constant-ness first.
7490   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7491     return true;
7492 
7493   // Truncate to the given size.
7494   Result = Result.getLoBits(ArgBits);
7495   Result.setIsUnsigned(true);
7496 
7497   // Check to see if it's in either of the required forms.
7498   if (IsShiftedByte(Result) ||
7499       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7500     return false;
7501 
7502   return Diag(TheCall->getBeginLoc(),
7503               diag::err_argument_not_shifted_byte_or_xxff)
7504          << Arg->getSourceRange();
7505 }
7506 
7507 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7508 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7509   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7510     if (checkArgCount(*this, TheCall, 2))
7511       return true;
7512     Expr *Arg0 = TheCall->getArg(0);
7513     Expr *Arg1 = TheCall->getArg(1);
7514 
7515     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7516     if (FirstArg.isInvalid())
7517       return true;
7518     QualType FirstArgType = FirstArg.get()->getType();
7519     if (!FirstArgType->isAnyPointerType())
7520       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7521                << "first" << FirstArgType << Arg0->getSourceRange();
7522     TheCall->setArg(0, FirstArg.get());
7523 
7524     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7525     if (SecArg.isInvalid())
7526       return true;
7527     QualType SecArgType = SecArg.get()->getType();
7528     if (!SecArgType->isIntegerType())
7529       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7530                << "second" << SecArgType << Arg1->getSourceRange();
7531 
7532     // Derive the return type from the pointer argument.
7533     TheCall->setType(FirstArgType);
7534     return false;
7535   }
7536 
7537   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7538     if (checkArgCount(*this, TheCall, 2))
7539       return true;
7540 
7541     Expr *Arg0 = TheCall->getArg(0);
7542     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7543     if (FirstArg.isInvalid())
7544       return true;
7545     QualType FirstArgType = FirstArg.get()->getType();
7546     if (!FirstArgType->isAnyPointerType())
7547       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7548                << "first" << FirstArgType << Arg0->getSourceRange();
7549     TheCall->setArg(0, FirstArg.get());
7550 
7551     // Derive the return type from the pointer argument.
7552     TheCall->setType(FirstArgType);
7553 
7554     // Second arg must be an constant in range [0,15]
7555     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7556   }
7557 
7558   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7559     if (checkArgCount(*this, TheCall, 2))
7560       return true;
7561     Expr *Arg0 = TheCall->getArg(0);
7562     Expr *Arg1 = TheCall->getArg(1);
7563 
7564     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7565     if (FirstArg.isInvalid())
7566       return true;
7567     QualType FirstArgType = FirstArg.get()->getType();
7568     if (!FirstArgType->isAnyPointerType())
7569       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7570                << "first" << FirstArgType << Arg0->getSourceRange();
7571 
7572     QualType SecArgType = Arg1->getType();
7573     if (!SecArgType->isIntegerType())
7574       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7575                << "second" << SecArgType << Arg1->getSourceRange();
7576     TheCall->setType(Context.IntTy);
7577     return false;
7578   }
7579 
7580   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7581       BuiltinID == AArch64::BI__builtin_arm_stg) {
7582     if (checkArgCount(*this, TheCall, 1))
7583       return true;
7584     Expr *Arg0 = TheCall->getArg(0);
7585     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7586     if (FirstArg.isInvalid())
7587       return true;
7588 
7589     QualType FirstArgType = FirstArg.get()->getType();
7590     if (!FirstArgType->isAnyPointerType())
7591       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7592                << "first" << FirstArgType << Arg0->getSourceRange();
7593     TheCall->setArg(0, FirstArg.get());
7594 
7595     // Derive the return type from the pointer argument.
7596     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7597       TheCall->setType(FirstArgType);
7598     return false;
7599   }
7600 
7601   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7602     Expr *ArgA = TheCall->getArg(0);
7603     Expr *ArgB = TheCall->getArg(1);
7604 
7605     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7606     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7607 
7608     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7609       return true;
7610 
7611     QualType ArgTypeA = ArgExprA.get()->getType();
7612     QualType ArgTypeB = ArgExprB.get()->getType();
7613 
7614     auto isNull = [&] (Expr *E) -> bool {
7615       return E->isNullPointerConstant(
7616                         Context, Expr::NPC_ValueDependentIsNotNull); };
7617 
7618     // argument should be either a pointer or null
7619     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7620       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7621         << "first" << ArgTypeA << ArgA->getSourceRange();
7622 
7623     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7624       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7625         << "second" << ArgTypeB << ArgB->getSourceRange();
7626 
7627     // Ensure Pointee types are compatible
7628     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7629         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7630       QualType pointeeA = ArgTypeA->getPointeeType();
7631       QualType pointeeB = ArgTypeB->getPointeeType();
7632       if (!Context.typesAreCompatible(
7633              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7634              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7635         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7636           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7637           << ArgB->getSourceRange();
7638       }
7639     }
7640 
7641     // at least one argument should be pointer type
7642     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7643       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7644         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7645 
7646     if (isNull(ArgA)) // adopt type of the other pointer
7647       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7648 
7649     if (isNull(ArgB))
7650       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7651 
7652     TheCall->setArg(0, ArgExprA.get());
7653     TheCall->setArg(1, ArgExprB.get());
7654     TheCall->setType(Context.LongLongTy);
7655     return false;
7656   }
7657   assert(false && "Unhandled ARM MTE intrinsic");
7658   return true;
7659 }
7660 
7661 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7662 /// TheCall is an ARM/AArch64 special register string literal.
7663 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7664                                     int ArgNum, unsigned ExpectedFieldNum,
7665                                     bool AllowName) {
7666   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7667                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7668                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7669                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7670                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7671                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7672   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7673                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7674                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7675                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7676                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7677                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7678   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7679 
7680   // We can't check the value of a dependent argument.
7681   Expr *Arg = TheCall->getArg(ArgNum);
7682   if (Arg->isTypeDependent() || Arg->isValueDependent())
7683     return false;
7684 
7685   // Check if the argument is a string literal.
7686   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7687     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7688            << Arg->getSourceRange();
7689 
7690   // Check the type of special register given.
7691   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7692   SmallVector<StringRef, 6> Fields;
7693   Reg.split(Fields, ":");
7694 
7695   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7696     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7697            << Arg->getSourceRange();
7698 
7699   // If the string is the name of a register then we cannot check that it is
7700   // valid here but if the string is of one the forms described in ACLE then we
7701   // can check that the supplied fields are integers and within the valid
7702   // ranges.
7703   if (Fields.size() > 1) {
7704     bool FiveFields = Fields.size() == 5;
7705 
7706     bool ValidString = true;
7707     if (IsARMBuiltin) {
7708       ValidString &= Fields[0].startswith_insensitive("cp") ||
7709                      Fields[0].startswith_insensitive("p");
7710       if (ValidString)
7711         Fields[0] = Fields[0].drop_front(
7712             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7713 
7714       ValidString &= Fields[2].startswith_insensitive("c");
7715       if (ValidString)
7716         Fields[2] = Fields[2].drop_front(1);
7717 
7718       if (FiveFields) {
7719         ValidString &= Fields[3].startswith_insensitive("c");
7720         if (ValidString)
7721           Fields[3] = Fields[3].drop_front(1);
7722       }
7723     }
7724 
7725     SmallVector<int, 5> Ranges;
7726     if (FiveFields)
7727       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7728     else
7729       Ranges.append({15, 7, 15});
7730 
7731     for (unsigned i=0; i<Fields.size(); ++i) {
7732       int IntField;
7733       ValidString &= !Fields[i].getAsInteger(10, IntField);
7734       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7735     }
7736 
7737     if (!ValidString)
7738       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7739              << Arg->getSourceRange();
7740   } else if (IsAArch64Builtin && Fields.size() == 1) {
7741     // If the register name is one of those that appear in the condition below
7742     // and the special register builtin being used is one of the write builtins,
7743     // then we require that the argument provided for writing to the register
7744     // is an integer constant expression. This is because it will be lowered to
7745     // an MSR (immediate) instruction, so we need to know the immediate at
7746     // compile time.
7747     if (TheCall->getNumArgs() != 2)
7748       return false;
7749 
7750     std::string RegLower = Reg.lower();
7751     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7752         RegLower != "pan" && RegLower != "uao")
7753       return false;
7754 
7755     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7756   }
7757 
7758   return false;
7759 }
7760 
7761 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7762 /// Emit an error and return true on failure; return false on success.
7763 /// TypeStr is a string containing the type descriptor of the value returned by
7764 /// the builtin and the descriptors of the expected type of the arguments.
7765 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
7766                                  const char *TypeStr) {
7767 
7768   assert((TypeStr[0] != '\0') &&
7769          "Invalid types in PPC MMA builtin declaration");
7770 
7771   switch (BuiltinID) {
7772   default:
7773     // This function is called in CheckPPCBuiltinFunctionCall where the
7774     // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here
7775     // we are isolating the pair vector memop builtins that can be used with mma
7776     // off so the default case is every builtin that requires mma and paired
7777     // vector memops.
7778     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7779                          diag::err_ppc_builtin_only_on_arch, "10") ||
7780         SemaFeatureCheck(*this, TheCall, "mma",
7781                          diag::err_ppc_builtin_only_on_arch, "10"))
7782       return true;
7783     break;
7784   case PPC::BI__builtin_vsx_lxvp:
7785   case PPC::BI__builtin_vsx_stxvp:
7786   case PPC::BI__builtin_vsx_assemble_pair:
7787   case PPC::BI__builtin_vsx_disassemble_pair:
7788     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7789                          diag::err_ppc_builtin_only_on_arch, "10"))
7790       return true;
7791     break;
7792   }
7793 
7794   unsigned Mask = 0;
7795   unsigned ArgNum = 0;
7796 
7797   // The first type in TypeStr is the type of the value returned by the
7798   // builtin. So we first read that type and change the type of TheCall.
7799   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7800   TheCall->setType(type);
7801 
7802   while (*TypeStr != '\0') {
7803     Mask = 0;
7804     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7805     if (ArgNum >= TheCall->getNumArgs()) {
7806       ArgNum++;
7807       break;
7808     }
7809 
7810     Expr *Arg = TheCall->getArg(ArgNum);
7811     QualType PassedType = Arg->getType();
7812     QualType StrippedRVType = PassedType.getCanonicalType();
7813 
7814     // Strip Restrict/Volatile qualifiers.
7815     if (StrippedRVType.isRestrictQualified() ||
7816         StrippedRVType.isVolatileQualified())
7817       StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
7818 
7819     // The only case where the argument type and expected type are allowed to
7820     // mismatch is if the argument type is a non-void pointer (or array) and
7821     // expected type is a void pointer.
7822     if (StrippedRVType != ExpectedType)
7823       if (!(ExpectedType->isVoidPointerType() &&
7824             (StrippedRVType->isPointerType() || StrippedRVType->isArrayType())))
7825         return Diag(Arg->getBeginLoc(),
7826                     diag::err_typecheck_convert_incompatible)
7827                << PassedType << ExpectedType << 1 << 0 << 0;
7828 
7829     // If the value of the Mask is not 0, we have a constraint in the size of
7830     // the integer argument so here we ensure the argument is a constant that
7831     // is in the valid range.
7832     if (Mask != 0 &&
7833         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7834       return true;
7835 
7836     ArgNum++;
7837   }
7838 
7839   // In case we exited early from the previous loop, there are other types to
7840   // read from TypeStr. So we need to read them all to ensure we have the right
7841   // number of arguments in TheCall and if it is not the case, to display a
7842   // better error message.
7843   while (*TypeStr != '\0') {
7844     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7845     ArgNum++;
7846   }
7847   if (checkArgCount(*this, TheCall, ArgNum))
7848     return true;
7849 
7850   return false;
7851 }
7852 
7853 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7854 /// This checks that the target supports __builtin_longjmp and
7855 /// that val is a constant 1.
7856 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7857   if (!Context.getTargetInfo().hasSjLjLowering())
7858     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7859            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7860 
7861   Expr *Arg = TheCall->getArg(1);
7862   llvm::APSInt Result;
7863 
7864   // TODO: This is less than ideal. Overload this to take a value.
7865   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7866     return true;
7867 
7868   if (Result != 1)
7869     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7870            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7871 
7872   return false;
7873 }
7874 
7875 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7876 /// This checks that the target supports __builtin_setjmp.
7877 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7878   if (!Context.getTargetInfo().hasSjLjLowering())
7879     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7880            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7881   return false;
7882 }
7883 
7884 namespace {
7885 
7886 class UncoveredArgHandler {
7887   enum { Unknown = -1, AllCovered = -2 };
7888 
7889   signed FirstUncoveredArg = Unknown;
7890   SmallVector<const Expr *, 4> DiagnosticExprs;
7891 
7892 public:
7893   UncoveredArgHandler() = default;
7894 
7895   bool hasUncoveredArg() const {
7896     return (FirstUncoveredArg >= 0);
7897   }
7898 
7899   unsigned getUncoveredArg() const {
7900     assert(hasUncoveredArg() && "no uncovered argument");
7901     return FirstUncoveredArg;
7902   }
7903 
7904   void setAllCovered() {
7905     // A string has been found with all arguments covered, so clear out
7906     // the diagnostics.
7907     DiagnosticExprs.clear();
7908     FirstUncoveredArg = AllCovered;
7909   }
7910 
7911   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7912     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7913 
7914     // Don't update if a previous string covers all arguments.
7915     if (FirstUncoveredArg == AllCovered)
7916       return;
7917 
7918     // UncoveredArgHandler tracks the highest uncovered argument index
7919     // and with it all the strings that match this index.
7920     if (NewFirstUncoveredArg == FirstUncoveredArg)
7921       DiagnosticExprs.push_back(StrExpr);
7922     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7923       DiagnosticExprs.clear();
7924       DiagnosticExprs.push_back(StrExpr);
7925       FirstUncoveredArg = NewFirstUncoveredArg;
7926     }
7927   }
7928 
7929   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7930 };
7931 
7932 enum StringLiteralCheckType {
7933   SLCT_NotALiteral,
7934   SLCT_UncheckedLiteral,
7935   SLCT_CheckedLiteral
7936 };
7937 
7938 } // namespace
7939 
7940 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7941                                      BinaryOperatorKind BinOpKind,
7942                                      bool AddendIsRight) {
7943   unsigned BitWidth = Offset.getBitWidth();
7944   unsigned AddendBitWidth = Addend.getBitWidth();
7945   // There might be negative interim results.
7946   if (Addend.isUnsigned()) {
7947     Addend = Addend.zext(++AddendBitWidth);
7948     Addend.setIsSigned(true);
7949   }
7950   // Adjust the bit width of the APSInts.
7951   if (AddendBitWidth > BitWidth) {
7952     Offset = Offset.sext(AddendBitWidth);
7953     BitWidth = AddendBitWidth;
7954   } else if (BitWidth > AddendBitWidth) {
7955     Addend = Addend.sext(BitWidth);
7956   }
7957 
7958   bool Ov = false;
7959   llvm::APSInt ResOffset = Offset;
7960   if (BinOpKind == BO_Add)
7961     ResOffset = Offset.sadd_ov(Addend, Ov);
7962   else {
7963     assert(AddendIsRight && BinOpKind == BO_Sub &&
7964            "operator must be add or sub with addend on the right");
7965     ResOffset = Offset.ssub_ov(Addend, Ov);
7966   }
7967 
7968   // We add an offset to a pointer here so we should support an offset as big as
7969   // possible.
7970   if (Ov) {
7971     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7972            "index (intermediate) result too big");
7973     Offset = Offset.sext(2 * BitWidth);
7974     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7975     return;
7976   }
7977 
7978   Offset = ResOffset;
7979 }
7980 
7981 namespace {
7982 
7983 // This is a wrapper class around StringLiteral to support offsetted string
7984 // literals as format strings. It takes the offset into account when returning
7985 // the string and its length or the source locations to display notes correctly.
7986 class FormatStringLiteral {
7987   const StringLiteral *FExpr;
7988   int64_t Offset;
7989 
7990  public:
7991   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7992       : FExpr(fexpr), Offset(Offset) {}
7993 
7994   StringRef getString() const {
7995     return FExpr->getString().drop_front(Offset);
7996   }
7997 
7998   unsigned getByteLength() const {
7999     return FExpr->getByteLength() - getCharByteWidth() * Offset;
8000   }
8001 
8002   unsigned getLength() const { return FExpr->getLength() - Offset; }
8003   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
8004 
8005   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
8006 
8007   QualType getType() const { return FExpr->getType(); }
8008 
8009   bool isAscii() const { return FExpr->isAscii(); }
8010   bool isWide() const { return FExpr->isWide(); }
8011   bool isUTF8() const { return FExpr->isUTF8(); }
8012   bool isUTF16() const { return FExpr->isUTF16(); }
8013   bool isUTF32() const { return FExpr->isUTF32(); }
8014   bool isPascal() const { return FExpr->isPascal(); }
8015 
8016   SourceLocation getLocationOfByte(
8017       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
8018       const TargetInfo &Target, unsigned *StartToken = nullptr,
8019       unsigned *StartTokenByteOffset = nullptr) const {
8020     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
8021                                     StartToken, StartTokenByteOffset);
8022   }
8023 
8024   SourceLocation getBeginLoc() const LLVM_READONLY {
8025     return FExpr->getBeginLoc().getLocWithOffset(Offset);
8026   }
8027 
8028   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
8029 };
8030 
8031 }  // namespace
8032 
8033 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8034                               const Expr *OrigFormatExpr,
8035                               ArrayRef<const Expr *> Args,
8036                               bool HasVAListArg, unsigned format_idx,
8037                               unsigned firstDataArg,
8038                               Sema::FormatStringType Type,
8039                               bool inFunctionCall,
8040                               Sema::VariadicCallType CallType,
8041                               llvm::SmallBitVector &CheckedVarArgs,
8042                               UncoveredArgHandler &UncoveredArg,
8043                               bool IgnoreStringsWithoutSpecifiers);
8044 
8045 // Determine if an expression is a string literal or constant string.
8046 // If this function returns false on the arguments to a function expecting a
8047 // format string, we will usually need to emit a warning.
8048 // True string literals are then checked by CheckFormatString.
8049 static StringLiteralCheckType
8050 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
8051                       bool HasVAListArg, unsigned format_idx,
8052                       unsigned firstDataArg, Sema::FormatStringType Type,
8053                       Sema::VariadicCallType CallType, bool InFunctionCall,
8054                       llvm::SmallBitVector &CheckedVarArgs,
8055                       UncoveredArgHandler &UncoveredArg,
8056                       llvm::APSInt Offset,
8057                       bool IgnoreStringsWithoutSpecifiers = false) {
8058   if (S.isConstantEvaluated())
8059     return SLCT_NotALiteral;
8060  tryAgain:
8061   assert(Offset.isSigned() && "invalid offset");
8062 
8063   if (E->isTypeDependent() || E->isValueDependent())
8064     return SLCT_NotALiteral;
8065 
8066   E = E->IgnoreParenCasts();
8067 
8068   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
8069     // Technically -Wformat-nonliteral does not warn about this case.
8070     // The behavior of printf and friends in this case is implementation
8071     // dependent.  Ideally if the format string cannot be null then
8072     // it should have a 'nonnull' attribute in the function prototype.
8073     return SLCT_UncheckedLiteral;
8074 
8075   switch (E->getStmtClass()) {
8076   case Stmt::BinaryConditionalOperatorClass:
8077   case Stmt::ConditionalOperatorClass: {
8078     // The expression is a literal if both sub-expressions were, and it was
8079     // completely checked only if both sub-expressions were checked.
8080     const AbstractConditionalOperator *C =
8081         cast<AbstractConditionalOperator>(E);
8082 
8083     // Determine whether it is necessary to check both sub-expressions, for
8084     // example, because the condition expression is a constant that can be
8085     // evaluated at compile time.
8086     bool CheckLeft = true, CheckRight = true;
8087 
8088     bool Cond;
8089     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
8090                                                  S.isConstantEvaluated())) {
8091       if (Cond)
8092         CheckRight = false;
8093       else
8094         CheckLeft = false;
8095     }
8096 
8097     // We need to maintain the offsets for the right and the left hand side
8098     // separately to check if every possible indexed expression is a valid
8099     // string literal. They might have different offsets for different string
8100     // literals in the end.
8101     StringLiteralCheckType Left;
8102     if (!CheckLeft)
8103       Left = SLCT_UncheckedLiteral;
8104     else {
8105       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
8106                                    HasVAListArg, format_idx, firstDataArg,
8107                                    Type, CallType, InFunctionCall,
8108                                    CheckedVarArgs, UncoveredArg, Offset,
8109                                    IgnoreStringsWithoutSpecifiers);
8110       if (Left == SLCT_NotALiteral || !CheckRight) {
8111         return Left;
8112       }
8113     }
8114 
8115     StringLiteralCheckType Right = checkFormatStringExpr(
8116         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
8117         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8118         IgnoreStringsWithoutSpecifiers);
8119 
8120     return (CheckLeft && Left < Right) ? Left : Right;
8121   }
8122 
8123   case Stmt::ImplicitCastExprClass:
8124     E = cast<ImplicitCastExpr>(E)->getSubExpr();
8125     goto tryAgain;
8126 
8127   case Stmt::OpaqueValueExprClass:
8128     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
8129       E = src;
8130       goto tryAgain;
8131     }
8132     return SLCT_NotALiteral;
8133 
8134   case Stmt::PredefinedExprClass:
8135     // While __func__, etc., are technically not string literals, they
8136     // cannot contain format specifiers and thus are not a security
8137     // liability.
8138     return SLCT_UncheckedLiteral;
8139 
8140   case Stmt::DeclRefExprClass: {
8141     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8142 
8143     // As an exception, do not flag errors for variables binding to
8144     // const string literals.
8145     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
8146       bool isConstant = false;
8147       QualType T = DR->getType();
8148 
8149       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
8150         isConstant = AT->getElementType().isConstant(S.Context);
8151       } else if (const PointerType *PT = T->getAs<PointerType>()) {
8152         isConstant = T.isConstant(S.Context) &&
8153                      PT->getPointeeType().isConstant(S.Context);
8154       } else if (T->isObjCObjectPointerType()) {
8155         // In ObjC, there is usually no "const ObjectPointer" type,
8156         // so don't check if the pointee type is constant.
8157         isConstant = T.isConstant(S.Context);
8158       }
8159 
8160       if (isConstant) {
8161         if (const Expr *Init = VD->getAnyInitializer()) {
8162           // Look through initializers like const char c[] = { "foo" }
8163           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
8164             if (InitList->isStringLiteralInit())
8165               Init = InitList->getInit(0)->IgnoreParenImpCasts();
8166           }
8167           return checkFormatStringExpr(S, Init, Args,
8168                                        HasVAListArg, format_idx,
8169                                        firstDataArg, Type, CallType,
8170                                        /*InFunctionCall*/ false, CheckedVarArgs,
8171                                        UncoveredArg, Offset);
8172         }
8173       }
8174 
8175       // For vprintf* functions (i.e., HasVAListArg==true), we add a
8176       // special check to see if the format string is a function parameter
8177       // of the function calling the printf function.  If the function
8178       // has an attribute indicating it is a printf-like function, then we
8179       // should suppress warnings concerning non-literals being used in a call
8180       // to a vprintf function.  For example:
8181       //
8182       // void
8183       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
8184       //      va_list ap;
8185       //      va_start(ap, fmt);
8186       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
8187       //      ...
8188       // }
8189       if (HasVAListArg) {
8190         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
8191           if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) {
8192             int PVIndex = PV->getFunctionScopeIndex() + 1;
8193             for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
8194               // adjust for implicit parameter
8195               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
8196                 if (MD->isInstance())
8197                   ++PVIndex;
8198               // We also check if the formats are compatible.
8199               // We can't pass a 'scanf' string to a 'printf' function.
8200               if (PVIndex == PVFormat->getFormatIdx() &&
8201                   Type == S.GetFormatStringType(PVFormat))
8202                 return SLCT_UncheckedLiteral;
8203             }
8204           }
8205         }
8206       }
8207     }
8208 
8209     return SLCT_NotALiteral;
8210   }
8211 
8212   case Stmt::CallExprClass:
8213   case Stmt::CXXMemberCallExprClass: {
8214     const CallExpr *CE = cast<CallExpr>(E);
8215     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
8216       bool IsFirst = true;
8217       StringLiteralCheckType CommonResult;
8218       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
8219         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
8220         StringLiteralCheckType Result = checkFormatStringExpr(
8221             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8222             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8223             IgnoreStringsWithoutSpecifiers);
8224         if (IsFirst) {
8225           CommonResult = Result;
8226           IsFirst = false;
8227         }
8228       }
8229       if (!IsFirst)
8230         return CommonResult;
8231 
8232       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
8233         unsigned BuiltinID = FD->getBuiltinID();
8234         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
8235             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
8236           const Expr *Arg = CE->getArg(0);
8237           return checkFormatStringExpr(S, Arg, Args,
8238                                        HasVAListArg, format_idx,
8239                                        firstDataArg, Type, CallType,
8240                                        InFunctionCall, CheckedVarArgs,
8241                                        UncoveredArg, Offset,
8242                                        IgnoreStringsWithoutSpecifiers);
8243         }
8244       }
8245     }
8246 
8247     return SLCT_NotALiteral;
8248   }
8249   case Stmt::ObjCMessageExprClass: {
8250     const auto *ME = cast<ObjCMessageExpr>(E);
8251     if (const auto *MD = ME->getMethodDecl()) {
8252       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
8253         // As a special case heuristic, if we're using the method -[NSBundle
8254         // localizedStringForKey:value:table:], ignore any key strings that lack
8255         // format specifiers. The idea is that if the key doesn't have any
8256         // format specifiers then its probably just a key to map to the
8257         // localized strings. If it does have format specifiers though, then its
8258         // likely that the text of the key is the format string in the
8259         // programmer's language, and should be checked.
8260         const ObjCInterfaceDecl *IFace;
8261         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
8262             IFace->getIdentifier()->isStr("NSBundle") &&
8263             MD->getSelector().isKeywordSelector(
8264                 {"localizedStringForKey", "value", "table"})) {
8265           IgnoreStringsWithoutSpecifiers = true;
8266         }
8267 
8268         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
8269         return checkFormatStringExpr(
8270             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8271             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8272             IgnoreStringsWithoutSpecifiers);
8273       }
8274     }
8275 
8276     return SLCT_NotALiteral;
8277   }
8278   case Stmt::ObjCStringLiteralClass:
8279   case Stmt::StringLiteralClass: {
8280     const StringLiteral *StrE = nullptr;
8281 
8282     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
8283       StrE = ObjCFExpr->getString();
8284     else
8285       StrE = cast<StringLiteral>(E);
8286 
8287     if (StrE) {
8288       if (Offset.isNegative() || Offset > StrE->getLength()) {
8289         // TODO: It would be better to have an explicit warning for out of
8290         // bounds literals.
8291         return SLCT_NotALiteral;
8292       }
8293       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
8294       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
8295                         firstDataArg, Type, InFunctionCall, CallType,
8296                         CheckedVarArgs, UncoveredArg,
8297                         IgnoreStringsWithoutSpecifiers);
8298       return SLCT_CheckedLiteral;
8299     }
8300 
8301     return SLCT_NotALiteral;
8302   }
8303   case Stmt::BinaryOperatorClass: {
8304     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
8305 
8306     // A string literal + an int offset is still a string literal.
8307     if (BinOp->isAdditiveOp()) {
8308       Expr::EvalResult LResult, RResult;
8309 
8310       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
8311           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8312       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
8313           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8314 
8315       if (LIsInt != RIsInt) {
8316         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
8317 
8318         if (LIsInt) {
8319           if (BinOpKind == BO_Add) {
8320             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
8321             E = BinOp->getRHS();
8322             goto tryAgain;
8323           }
8324         } else {
8325           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
8326           E = BinOp->getLHS();
8327           goto tryAgain;
8328         }
8329       }
8330     }
8331 
8332     return SLCT_NotALiteral;
8333   }
8334   case Stmt::UnaryOperatorClass: {
8335     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
8336     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
8337     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
8338       Expr::EvalResult IndexResult;
8339       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
8340                                        Expr::SE_NoSideEffects,
8341                                        S.isConstantEvaluated())) {
8342         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
8343                    /*RHS is int*/ true);
8344         E = ASE->getBase();
8345         goto tryAgain;
8346       }
8347     }
8348 
8349     return SLCT_NotALiteral;
8350   }
8351 
8352   default:
8353     return SLCT_NotALiteral;
8354   }
8355 }
8356 
8357 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
8358   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
8359       .Case("scanf", FST_Scanf)
8360       .Cases("printf", "printf0", FST_Printf)
8361       .Cases("NSString", "CFString", FST_NSString)
8362       .Case("strftime", FST_Strftime)
8363       .Case("strfmon", FST_Strfmon)
8364       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
8365       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
8366       .Case("os_trace", FST_OSLog)
8367       .Case("os_log", FST_OSLog)
8368       .Default(FST_Unknown);
8369 }
8370 
8371 /// CheckFormatArguments - Check calls to printf and scanf (and similar
8372 /// functions) for correct use of format strings.
8373 /// Returns true if a format string has been fully checked.
8374 bool Sema::CheckFormatArguments(const FormatAttr *Format,
8375                                 ArrayRef<const Expr *> Args,
8376                                 bool IsCXXMember,
8377                                 VariadicCallType CallType,
8378                                 SourceLocation Loc, SourceRange Range,
8379                                 llvm::SmallBitVector &CheckedVarArgs) {
8380   FormatStringInfo FSI;
8381   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
8382     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
8383                                 FSI.FirstDataArg, GetFormatStringType(Format),
8384                                 CallType, Loc, Range, CheckedVarArgs);
8385   return false;
8386 }
8387 
8388 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8389                                 bool HasVAListArg, unsigned format_idx,
8390                                 unsigned firstDataArg, FormatStringType Type,
8391                                 VariadicCallType CallType,
8392                                 SourceLocation Loc, SourceRange Range,
8393                                 llvm::SmallBitVector &CheckedVarArgs) {
8394   // CHECK: printf/scanf-like function is called with no format string.
8395   if (format_idx >= Args.size()) {
8396     Diag(Loc, diag::warn_missing_format_string) << Range;
8397     return false;
8398   }
8399 
8400   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8401 
8402   // CHECK: format string is not a string literal.
8403   //
8404   // Dynamically generated format strings are difficult to
8405   // automatically vet at compile time.  Requiring that format strings
8406   // are string literals: (1) permits the checking of format strings by
8407   // the compiler and thereby (2) can practically remove the source of
8408   // many format string exploits.
8409 
8410   // Format string can be either ObjC string (e.g. @"%d") or
8411   // C string (e.g. "%d")
8412   // ObjC string uses the same format specifiers as C string, so we can use
8413   // the same format string checking logic for both ObjC and C strings.
8414   UncoveredArgHandler UncoveredArg;
8415   StringLiteralCheckType CT =
8416       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8417                             format_idx, firstDataArg, Type, CallType,
8418                             /*IsFunctionCall*/ true, CheckedVarArgs,
8419                             UncoveredArg,
8420                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8421 
8422   // Generate a diagnostic where an uncovered argument is detected.
8423   if (UncoveredArg.hasUncoveredArg()) {
8424     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8425     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8426     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8427   }
8428 
8429   if (CT != SLCT_NotALiteral)
8430     // Literal format string found, check done!
8431     return CT == SLCT_CheckedLiteral;
8432 
8433   // Strftime is particular as it always uses a single 'time' argument,
8434   // so it is safe to pass a non-literal string.
8435   if (Type == FST_Strftime)
8436     return false;
8437 
8438   // Do not emit diag when the string param is a macro expansion and the
8439   // format is either NSString or CFString. This is a hack to prevent
8440   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8441   // which are usually used in place of NS and CF string literals.
8442   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8443   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8444     return false;
8445 
8446   // If there are no arguments specified, warn with -Wformat-security, otherwise
8447   // warn only with -Wformat-nonliteral.
8448   if (Args.size() == firstDataArg) {
8449     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8450       << OrigFormatExpr->getSourceRange();
8451     switch (Type) {
8452     default:
8453       break;
8454     case FST_Kprintf:
8455     case FST_FreeBSDKPrintf:
8456     case FST_Printf:
8457       Diag(FormatLoc, diag::note_format_security_fixit)
8458         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8459       break;
8460     case FST_NSString:
8461       Diag(FormatLoc, diag::note_format_security_fixit)
8462         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8463       break;
8464     }
8465   } else {
8466     Diag(FormatLoc, diag::warn_format_nonliteral)
8467       << OrigFormatExpr->getSourceRange();
8468   }
8469   return false;
8470 }
8471 
8472 namespace {
8473 
8474 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8475 protected:
8476   Sema &S;
8477   const FormatStringLiteral *FExpr;
8478   const Expr *OrigFormatExpr;
8479   const Sema::FormatStringType FSType;
8480   const unsigned FirstDataArg;
8481   const unsigned NumDataArgs;
8482   const char *Beg; // Start of format string.
8483   const bool HasVAListArg;
8484   ArrayRef<const Expr *> Args;
8485   unsigned FormatIdx;
8486   llvm::SmallBitVector CoveredArgs;
8487   bool usesPositionalArgs = false;
8488   bool atFirstArg = true;
8489   bool inFunctionCall;
8490   Sema::VariadicCallType CallType;
8491   llvm::SmallBitVector &CheckedVarArgs;
8492   UncoveredArgHandler &UncoveredArg;
8493 
8494 public:
8495   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8496                      const Expr *origFormatExpr,
8497                      const Sema::FormatStringType type, unsigned firstDataArg,
8498                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8499                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8500                      bool inFunctionCall, Sema::VariadicCallType callType,
8501                      llvm::SmallBitVector &CheckedVarArgs,
8502                      UncoveredArgHandler &UncoveredArg)
8503       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8504         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8505         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8506         inFunctionCall(inFunctionCall), CallType(callType),
8507         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8508     CoveredArgs.resize(numDataArgs);
8509     CoveredArgs.reset();
8510   }
8511 
8512   void DoneProcessing();
8513 
8514   void HandleIncompleteSpecifier(const char *startSpecifier,
8515                                  unsigned specifierLen) override;
8516 
8517   void HandleInvalidLengthModifier(
8518                            const analyze_format_string::FormatSpecifier &FS,
8519                            const analyze_format_string::ConversionSpecifier &CS,
8520                            const char *startSpecifier, unsigned specifierLen,
8521                            unsigned DiagID);
8522 
8523   void HandleNonStandardLengthModifier(
8524                     const analyze_format_string::FormatSpecifier &FS,
8525                     const char *startSpecifier, unsigned specifierLen);
8526 
8527   void HandleNonStandardConversionSpecifier(
8528                     const analyze_format_string::ConversionSpecifier &CS,
8529                     const char *startSpecifier, unsigned specifierLen);
8530 
8531   void HandlePosition(const char *startPos, unsigned posLen) override;
8532 
8533   void HandleInvalidPosition(const char *startSpecifier,
8534                              unsigned specifierLen,
8535                              analyze_format_string::PositionContext p) override;
8536 
8537   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8538 
8539   void HandleNullChar(const char *nullCharacter) override;
8540 
8541   template <typename Range>
8542   static void
8543   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8544                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8545                        bool IsStringLocation, Range StringRange,
8546                        ArrayRef<FixItHint> Fixit = None);
8547 
8548 protected:
8549   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8550                                         const char *startSpec,
8551                                         unsigned specifierLen,
8552                                         const char *csStart, unsigned csLen);
8553 
8554   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8555                                          const char *startSpec,
8556                                          unsigned specifierLen);
8557 
8558   SourceRange getFormatStringRange();
8559   CharSourceRange getSpecifierRange(const char *startSpecifier,
8560                                     unsigned specifierLen);
8561   SourceLocation getLocationOfByte(const char *x);
8562 
8563   const Expr *getDataArg(unsigned i) const;
8564 
8565   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8566                     const analyze_format_string::ConversionSpecifier &CS,
8567                     const char *startSpecifier, unsigned specifierLen,
8568                     unsigned argIndex);
8569 
8570   template <typename Range>
8571   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8572                             bool IsStringLocation, Range StringRange,
8573                             ArrayRef<FixItHint> Fixit = None);
8574 };
8575 
8576 } // namespace
8577 
8578 SourceRange CheckFormatHandler::getFormatStringRange() {
8579   return OrigFormatExpr->getSourceRange();
8580 }
8581 
8582 CharSourceRange CheckFormatHandler::
8583 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8584   SourceLocation Start = getLocationOfByte(startSpecifier);
8585   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8586 
8587   // Advance the end SourceLocation by one due to half-open ranges.
8588   End = End.getLocWithOffset(1);
8589 
8590   return CharSourceRange::getCharRange(Start, End);
8591 }
8592 
8593 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8594   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8595                                   S.getLangOpts(), S.Context.getTargetInfo());
8596 }
8597 
8598 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8599                                                    unsigned specifierLen){
8600   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8601                        getLocationOfByte(startSpecifier),
8602                        /*IsStringLocation*/true,
8603                        getSpecifierRange(startSpecifier, specifierLen));
8604 }
8605 
8606 void CheckFormatHandler::HandleInvalidLengthModifier(
8607     const analyze_format_string::FormatSpecifier &FS,
8608     const analyze_format_string::ConversionSpecifier &CS,
8609     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8610   using namespace analyze_format_string;
8611 
8612   const LengthModifier &LM = FS.getLengthModifier();
8613   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8614 
8615   // See if we know how to fix this length modifier.
8616   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8617   if (FixedLM) {
8618     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8619                          getLocationOfByte(LM.getStart()),
8620                          /*IsStringLocation*/true,
8621                          getSpecifierRange(startSpecifier, specifierLen));
8622 
8623     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8624       << FixedLM->toString()
8625       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8626 
8627   } else {
8628     FixItHint Hint;
8629     if (DiagID == diag::warn_format_nonsensical_length)
8630       Hint = FixItHint::CreateRemoval(LMRange);
8631 
8632     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8633                          getLocationOfByte(LM.getStart()),
8634                          /*IsStringLocation*/true,
8635                          getSpecifierRange(startSpecifier, specifierLen),
8636                          Hint);
8637   }
8638 }
8639 
8640 void CheckFormatHandler::HandleNonStandardLengthModifier(
8641     const analyze_format_string::FormatSpecifier &FS,
8642     const char *startSpecifier, unsigned specifierLen) {
8643   using namespace analyze_format_string;
8644 
8645   const LengthModifier &LM = FS.getLengthModifier();
8646   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8647 
8648   // See if we know how to fix this length modifier.
8649   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8650   if (FixedLM) {
8651     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8652                            << LM.toString() << 0,
8653                          getLocationOfByte(LM.getStart()),
8654                          /*IsStringLocation*/true,
8655                          getSpecifierRange(startSpecifier, specifierLen));
8656 
8657     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8658       << FixedLM->toString()
8659       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8660 
8661   } else {
8662     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8663                            << LM.toString() << 0,
8664                          getLocationOfByte(LM.getStart()),
8665                          /*IsStringLocation*/true,
8666                          getSpecifierRange(startSpecifier, specifierLen));
8667   }
8668 }
8669 
8670 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8671     const analyze_format_string::ConversionSpecifier &CS,
8672     const char *startSpecifier, unsigned specifierLen) {
8673   using namespace analyze_format_string;
8674 
8675   // See if we know how to fix this conversion specifier.
8676   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8677   if (FixedCS) {
8678     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8679                           << CS.toString() << /*conversion specifier*/1,
8680                          getLocationOfByte(CS.getStart()),
8681                          /*IsStringLocation*/true,
8682                          getSpecifierRange(startSpecifier, specifierLen));
8683 
8684     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8685     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8686       << FixedCS->toString()
8687       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8688   } else {
8689     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8690                           << CS.toString() << /*conversion specifier*/1,
8691                          getLocationOfByte(CS.getStart()),
8692                          /*IsStringLocation*/true,
8693                          getSpecifierRange(startSpecifier, specifierLen));
8694   }
8695 }
8696 
8697 void CheckFormatHandler::HandlePosition(const char *startPos,
8698                                         unsigned posLen) {
8699   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8700                                getLocationOfByte(startPos),
8701                                /*IsStringLocation*/true,
8702                                getSpecifierRange(startPos, posLen));
8703 }
8704 
8705 void
8706 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8707                                      analyze_format_string::PositionContext p) {
8708   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8709                          << (unsigned) p,
8710                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8711                        getSpecifierRange(startPos, posLen));
8712 }
8713 
8714 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8715                                             unsigned posLen) {
8716   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8717                                getLocationOfByte(startPos),
8718                                /*IsStringLocation*/true,
8719                                getSpecifierRange(startPos, posLen));
8720 }
8721 
8722 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8723   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8724     // The presence of a null character is likely an error.
8725     EmitFormatDiagnostic(
8726       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8727       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8728       getFormatStringRange());
8729   }
8730 }
8731 
8732 // Note that this may return NULL if there was an error parsing or building
8733 // one of the argument expressions.
8734 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8735   return Args[FirstDataArg + i];
8736 }
8737 
8738 void CheckFormatHandler::DoneProcessing() {
8739   // Does the number of data arguments exceed the number of
8740   // format conversions in the format string?
8741   if (!HasVAListArg) {
8742       // Find any arguments that weren't covered.
8743     CoveredArgs.flip();
8744     signed notCoveredArg = CoveredArgs.find_first();
8745     if (notCoveredArg >= 0) {
8746       assert((unsigned)notCoveredArg < NumDataArgs);
8747       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8748     } else {
8749       UncoveredArg.setAllCovered();
8750     }
8751   }
8752 }
8753 
8754 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8755                                    const Expr *ArgExpr) {
8756   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8757          "Invalid state");
8758 
8759   if (!ArgExpr)
8760     return;
8761 
8762   SourceLocation Loc = ArgExpr->getBeginLoc();
8763 
8764   if (S.getSourceManager().isInSystemMacro(Loc))
8765     return;
8766 
8767   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8768   for (auto E : DiagnosticExprs)
8769     PDiag << E->getSourceRange();
8770 
8771   CheckFormatHandler::EmitFormatDiagnostic(
8772                                   S, IsFunctionCall, DiagnosticExprs[0],
8773                                   PDiag, Loc, /*IsStringLocation*/false,
8774                                   DiagnosticExprs[0]->getSourceRange());
8775 }
8776 
8777 bool
8778 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8779                                                      SourceLocation Loc,
8780                                                      const char *startSpec,
8781                                                      unsigned specifierLen,
8782                                                      const char *csStart,
8783                                                      unsigned csLen) {
8784   bool keepGoing = true;
8785   if (argIndex < NumDataArgs) {
8786     // Consider the argument coverered, even though the specifier doesn't
8787     // make sense.
8788     CoveredArgs.set(argIndex);
8789   }
8790   else {
8791     // If argIndex exceeds the number of data arguments we
8792     // don't issue a warning because that is just a cascade of warnings (and
8793     // they may have intended '%%' anyway). We don't want to continue processing
8794     // the format string after this point, however, as we will like just get
8795     // gibberish when trying to match arguments.
8796     keepGoing = false;
8797   }
8798 
8799   StringRef Specifier(csStart, csLen);
8800 
8801   // If the specifier in non-printable, it could be the first byte of a UTF-8
8802   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8803   // hex value.
8804   std::string CodePointStr;
8805   if (!llvm::sys::locale::isPrint(*csStart)) {
8806     llvm::UTF32 CodePoint;
8807     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8808     const llvm::UTF8 *E =
8809         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8810     llvm::ConversionResult Result =
8811         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8812 
8813     if (Result != llvm::conversionOK) {
8814       unsigned char FirstChar = *csStart;
8815       CodePoint = (llvm::UTF32)FirstChar;
8816     }
8817 
8818     llvm::raw_string_ostream OS(CodePointStr);
8819     if (CodePoint < 256)
8820       OS << "\\x" << llvm::format("%02x", CodePoint);
8821     else if (CodePoint <= 0xFFFF)
8822       OS << "\\u" << llvm::format("%04x", CodePoint);
8823     else
8824       OS << "\\U" << llvm::format("%08x", CodePoint);
8825     OS.flush();
8826     Specifier = CodePointStr;
8827   }
8828 
8829   EmitFormatDiagnostic(
8830       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8831       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8832 
8833   return keepGoing;
8834 }
8835 
8836 void
8837 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8838                                                       const char *startSpec,
8839                                                       unsigned specifierLen) {
8840   EmitFormatDiagnostic(
8841     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8842     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8843 }
8844 
8845 bool
8846 CheckFormatHandler::CheckNumArgs(
8847   const analyze_format_string::FormatSpecifier &FS,
8848   const analyze_format_string::ConversionSpecifier &CS,
8849   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8850 
8851   if (argIndex >= NumDataArgs) {
8852     PartialDiagnostic PDiag = FS.usesPositionalArg()
8853       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8854            << (argIndex+1) << NumDataArgs)
8855       : S.PDiag(diag::warn_printf_insufficient_data_args);
8856     EmitFormatDiagnostic(
8857       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8858       getSpecifierRange(startSpecifier, specifierLen));
8859 
8860     // Since more arguments than conversion tokens are given, by extension
8861     // all arguments are covered, so mark this as so.
8862     UncoveredArg.setAllCovered();
8863     return false;
8864   }
8865   return true;
8866 }
8867 
8868 template<typename Range>
8869 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8870                                               SourceLocation Loc,
8871                                               bool IsStringLocation,
8872                                               Range StringRange,
8873                                               ArrayRef<FixItHint> FixIt) {
8874   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8875                        Loc, IsStringLocation, StringRange, FixIt);
8876 }
8877 
8878 /// If the format string is not within the function call, emit a note
8879 /// so that the function call and string are in diagnostic messages.
8880 ///
8881 /// \param InFunctionCall if true, the format string is within the function
8882 /// call and only one diagnostic message will be produced.  Otherwise, an
8883 /// extra note will be emitted pointing to location of the format string.
8884 ///
8885 /// \param ArgumentExpr the expression that is passed as the format string
8886 /// argument in the function call.  Used for getting locations when two
8887 /// diagnostics are emitted.
8888 ///
8889 /// \param PDiag the callee should already have provided any strings for the
8890 /// diagnostic message.  This function only adds locations and fixits
8891 /// to diagnostics.
8892 ///
8893 /// \param Loc primary location for diagnostic.  If two diagnostics are
8894 /// required, one will be at Loc and a new SourceLocation will be created for
8895 /// the other one.
8896 ///
8897 /// \param IsStringLocation if true, Loc points to the format string should be
8898 /// used for the note.  Otherwise, Loc points to the argument list and will
8899 /// be used with PDiag.
8900 ///
8901 /// \param StringRange some or all of the string to highlight.  This is
8902 /// templated so it can accept either a CharSourceRange or a SourceRange.
8903 ///
8904 /// \param FixIt optional fix it hint for the format string.
8905 template <typename Range>
8906 void CheckFormatHandler::EmitFormatDiagnostic(
8907     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8908     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8909     Range StringRange, ArrayRef<FixItHint> FixIt) {
8910   if (InFunctionCall) {
8911     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8912     D << StringRange;
8913     D << FixIt;
8914   } else {
8915     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8916       << ArgumentExpr->getSourceRange();
8917 
8918     const Sema::SemaDiagnosticBuilder &Note =
8919       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8920              diag::note_format_string_defined);
8921 
8922     Note << StringRange;
8923     Note << FixIt;
8924   }
8925 }
8926 
8927 //===--- CHECK: Printf format string checking ------------------------------===//
8928 
8929 namespace {
8930 
8931 class CheckPrintfHandler : public CheckFormatHandler {
8932 public:
8933   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8934                      const Expr *origFormatExpr,
8935                      const Sema::FormatStringType type, unsigned firstDataArg,
8936                      unsigned numDataArgs, bool isObjC, const char *beg,
8937                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8938                      unsigned formatIdx, bool inFunctionCall,
8939                      Sema::VariadicCallType CallType,
8940                      llvm::SmallBitVector &CheckedVarArgs,
8941                      UncoveredArgHandler &UncoveredArg)
8942       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8943                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8944                            inFunctionCall, CallType, CheckedVarArgs,
8945                            UncoveredArg) {}
8946 
8947   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8948 
8949   /// Returns true if '%@' specifiers are allowed in the format string.
8950   bool allowsObjCArg() const {
8951     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8952            FSType == Sema::FST_OSTrace;
8953   }
8954 
8955   bool HandleInvalidPrintfConversionSpecifier(
8956                                       const analyze_printf::PrintfSpecifier &FS,
8957                                       const char *startSpecifier,
8958                                       unsigned specifierLen) override;
8959 
8960   void handleInvalidMaskType(StringRef MaskType) override;
8961 
8962   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8963                              const char *startSpecifier, unsigned specifierLen,
8964                              const TargetInfo &Target) override;
8965   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8966                        const char *StartSpecifier,
8967                        unsigned SpecifierLen,
8968                        const Expr *E);
8969 
8970   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8971                     const char *startSpecifier, unsigned specifierLen);
8972   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8973                            const analyze_printf::OptionalAmount &Amt,
8974                            unsigned type,
8975                            const char *startSpecifier, unsigned specifierLen);
8976   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8977                   const analyze_printf::OptionalFlag &flag,
8978                   const char *startSpecifier, unsigned specifierLen);
8979   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8980                          const analyze_printf::OptionalFlag &ignoredFlag,
8981                          const analyze_printf::OptionalFlag &flag,
8982                          const char *startSpecifier, unsigned specifierLen);
8983   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8984                            const Expr *E);
8985 
8986   void HandleEmptyObjCModifierFlag(const char *startFlag,
8987                                    unsigned flagLen) override;
8988 
8989   void HandleInvalidObjCModifierFlag(const char *startFlag,
8990                                             unsigned flagLen) override;
8991 
8992   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8993                                            const char *flagsEnd,
8994                                            const char *conversionPosition)
8995                                              override;
8996 };
8997 
8998 } // namespace
8999 
9000 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
9001                                       const analyze_printf::PrintfSpecifier &FS,
9002                                       const char *startSpecifier,
9003                                       unsigned specifierLen) {
9004   const analyze_printf::PrintfConversionSpecifier &CS =
9005     FS.getConversionSpecifier();
9006 
9007   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9008                                           getLocationOfByte(CS.getStart()),
9009                                           startSpecifier, specifierLen,
9010                                           CS.getStart(), CS.getLength());
9011 }
9012 
9013 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
9014   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
9015 }
9016 
9017 bool CheckPrintfHandler::HandleAmount(
9018                                const analyze_format_string::OptionalAmount &Amt,
9019                                unsigned k, const char *startSpecifier,
9020                                unsigned specifierLen) {
9021   if (Amt.hasDataArgument()) {
9022     if (!HasVAListArg) {
9023       unsigned argIndex = Amt.getArgIndex();
9024       if (argIndex >= NumDataArgs) {
9025         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
9026                                << k,
9027                              getLocationOfByte(Amt.getStart()),
9028                              /*IsStringLocation*/true,
9029                              getSpecifierRange(startSpecifier, specifierLen));
9030         // Don't do any more checking.  We will just emit
9031         // spurious errors.
9032         return false;
9033       }
9034 
9035       // Type check the data argument.  It should be an 'int'.
9036       // Although not in conformance with C99, we also allow the argument to be
9037       // an 'unsigned int' as that is a reasonably safe case.  GCC also
9038       // doesn't emit a warning for that case.
9039       CoveredArgs.set(argIndex);
9040       const Expr *Arg = getDataArg(argIndex);
9041       if (!Arg)
9042         return false;
9043 
9044       QualType T = Arg->getType();
9045 
9046       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
9047       assert(AT.isValid());
9048 
9049       if (!AT.matchesType(S.Context, T)) {
9050         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
9051                                << k << AT.getRepresentativeTypeName(S.Context)
9052                                << T << Arg->getSourceRange(),
9053                              getLocationOfByte(Amt.getStart()),
9054                              /*IsStringLocation*/true,
9055                              getSpecifierRange(startSpecifier, specifierLen));
9056         // Don't do any more checking.  We will just emit
9057         // spurious errors.
9058         return false;
9059       }
9060     }
9061   }
9062   return true;
9063 }
9064 
9065 void CheckPrintfHandler::HandleInvalidAmount(
9066                                       const analyze_printf::PrintfSpecifier &FS,
9067                                       const analyze_printf::OptionalAmount &Amt,
9068                                       unsigned type,
9069                                       const char *startSpecifier,
9070                                       unsigned specifierLen) {
9071   const analyze_printf::PrintfConversionSpecifier &CS =
9072     FS.getConversionSpecifier();
9073 
9074   FixItHint fixit =
9075     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
9076       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
9077                                  Amt.getConstantLength()))
9078       : FixItHint();
9079 
9080   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
9081                          << type << CS.toString(),
9082                        getLocationOfByte(Amt.getStart()),
9083                        /*IsStringLocation*/true,
9084                        getSpecifierRange(startSpecifier, specifierLen),
9085                        fixit);
9086 }
9087 
9088 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
9089                                     const analyze_printf::OptionalFlag &flag,
9090                                     const char *startSpecifier,
9091                                     unsigned specifierLen) {
9092   // Warn about pointless flag with a fixit removal.
9093   const analyze_printf::PrintfConversionSpecifier &CS =
9094     FS.getConversionSpecifier();
9095   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
9096                          << flag.toString() << CS.toString(),
9097                        getLocationOfByte(flag.getPosition()),
9098                        /*IsStringLocation*/true,
9099                        getSpecifierRange(startSpecifier, specifierLen),
9100                        FixItHint::CreateRemoval(
9101                          getSpecifierRange(flag.getPosition(), 1)));
9102 }
9103 
9104 void CheckPrintfHandler::HandleIgnoredFlag(
9105                                 const analyze_printf::PrintfSpecifier &FS,
9106                                 const analyze_printf::OptionalFlag &ignoredFlag,
9107                                 const analyze_printf::OptionalFlag &flag,
9108                                 const char *startSpecifier,
9109                                 unsigned specifierLen) {
9110   // Warn about ignored flag with a fixit removal.
9111   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
9112                          << ignoredFlag.toString() << flag.toString(),
9113                        getLocationOfByte(ignoredFlag.getPosition()),
9114                        /*IsStringLocation*/true,
9115                        getSpecifierRange(startSpecifier, specifierLen),
9116                        FixItHint::CreateRemoval(
9117                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
9118 }
9119 
9120 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
9121                                                      unsigned flagLen) {
9122   // Warn about an empty flag.
9123   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
9124                        getLocationOfByte(startFlag),
9125                        /*IsStringLocation*/true,
9126                        getSpecifierRange(startFlag, flagLen));
9127 }
9128 
9129 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
9130                                                        unsigned flagLen) {
9131   // Warn about an invalid flag.
9132   auto Range = getSpecifierRange(startFlag, flagLen);
9133   StringRef flag(startFlag, flagLen);
9134   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
9135                       getLocationOfByte(startFlag),
9136                       /*IsStringLocation*/true,
9137                       Range, FixItHint::CreateRemoval(Range));
9138 }
9139 
9140 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
9141     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
9142     // Warn about using '[...]' without a '@' conversion.
9143     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
9144     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
9145     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
9146                          getLocationOfByte(conversionPosition),
9147                          /*IsStringLocation*/true,
9148                          Range, FixItHint::CreateRemoval(Range));
9149 }
9150 
9151 // Determines if the specified is a C++ class or struct containing
9152 // a member with the specified name and kind (e.g. a CXXMethodDecl named
9153 // "c_str()").
9154 template<typename MemberKind>
9155 static llvm::SmallPtrSet<MemberKind*, 1>
9156 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9157   const RecordType *RT = Ty->getAs<RecordType>();
9158   llvm::SmallPtrSet<MemberKind*, 1> Results;
9159 
9160   if (!RT)
9161     return Results;
9162   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
9163   if (!RD || !RD->getDefinition())
9164     return Results;
9165 
9166   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9167                  Sema::LookupMemberName);
9168   R.suppressDiagnostics();
9169 
9170   // We just need to include all members of the right kind turned up by the
9171   // filter, at this point.
9172   if (S.LookupQualifiedName(R, RT->getDecl()))
9173     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9174       NamedDecl *decl = (*I)->getUnderlyingDecl();
9175       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9176         Results.insert(FK);
9177     }
9178   return Results;
9179 }
9180 
9181 /// Check if we could call '.c_str()' on an object.
9182 ///
9183 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9184 /// allow the call, or if it would be ambiguous).
9185 bool Sema::hasCStrMethod(const Expr *E) {
9186   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9187 
9188   MethodSet Results =
9189       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
9190   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9191        MI != ME; ++MI)
9192     if ((*MI)->getMinRequiredArguments() == 0)
9193       return true;
9194   return false;
9195 }
9196 
9197 // Check if a (w)string was passed when a (w)char* was needed, and offer a
9198 // better diagnostic if so. AT is assumed to be valid.
9199 // Returns true when a c_str() conversion method is found.
9200 bool CheckPrintfHandler::checkForCStrMembers(
9201     const analyze_printf::ArgType &AT, const Expr *E) {
9202   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9203 
9204   MethodSet Results =
9205       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
9206 
9207   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9208        MI != ME; ++MI) {
9209     const CXXMethodDecl *Method = *MI;
9210     if (Method->getMinRequiredArguments() == 0 &&
9211         AT.matchesType(S.Context, Method->getReturnType())) {
9212       // FIXME: Suggest parens if the expression needs them.
9213       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
9214       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
9215           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
9216       return true;
9217     }
9218   }
9219 
9220   return false;
9221 }
9222 
9223 bool CheckPrintfHandler::HandlePrintfSpecifier(
9224     const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9225     unsigned specifierLen, const TargetInfo &Target) {
9226   using namespace analyze_format_string;
9227   using namespace analyze_printf;
9228 
9229   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9230 
9231   if (FS.consumesDataArgument()) {
9232     if (atFirstArg) {
9233         atFirstArg = false;
9234         usesPositionalArgs = FS.usesPositionalArg();
9235     }
9236     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9237       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9238                                         startSpecifier, specifierLen);
9239       return false;
9240     }
9241   }
9242 
9243   // First check if the field width, precision, and conversion specifier
9244   // have matching data arguments.
9245   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
9246                     startSpecifier, specifierLen)) {
9247     return false;
9248   }
9249 
9250   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
9251                     startSpecifier, specifierLen)) {
9252     return false;
9253   }
9254 
9255   if (!CS.consumesDataArgument()) {
9256     // FIXME: Technically specifying a precision or field width here
9257     // makes no sense.  Worth issuing a warning at some point.
9258     return true;
9259   }
9260 
9261   // Consume the argument.
9262   unsigned argIndex = FS.getArgIndex();
9263   if (argIndex < NumDataArgs) {
9264     // The check to see if the argIndex is valid will come later.
9265     // We set the bit here because we may exit early from this
9266     // function if we encounter some other error.
9267     CoveredArgs.set(argIndex);
9268   }
9269 
9270   // FreeBSD kernel extensions.
9271   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9272       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9273     // We need at least two arguments.
9274     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9275       return false;
9276 
9277     // Claim the second argument.
9278     CoveredArgs.set(argIndex + 1);
9279 
9280     // Type check the first argument (int for %b, pointer for %D)
9281     const Expr *Ex = getDataArg(argIndex);
9282     const analyze_printf::ArgType &AT =
9283       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
9284         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
9285     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9286       EmitFormatDiagnostic(
9287           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9288               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9289               << false << Ex->getSourceRange(),
9290           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9291           getSpecifierRange(startSpecifier, specifierLen));
9292 
9293     // Type check the second argument (char * for both %b and %D)
9294     Ex = getDataArg(argIndex + 1);
9295     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
9296     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9297       EmitFormatDiagnostic(
9298           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9299               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9300               << false << Ex->getSourceRange(),
9301           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9302           getSpecifierRange(startSpecifier, specifierLen));
9303 
9304      return true;
9305   }
9306 
9307   // Check for using an Objective-C specific conversion specifier
9308   // in a non-ObjC literal.
9309   if (!allowsObjCArg() && CS.isObjCArg()) {
9310     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9311                                                   specifierLen);
9312   }
9313 
9314   // %P can only be used with os_log.
9315   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
9316     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9317                                                   specifierLen);
9318   }
9319 
9320   // %n is not allowed with os_log.
9321   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
9322     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9323                          getLocationOfByte(CS.getStart()),
9324                          /*IsStringLocation*/ false,
9325                          getSpecifierRange(startSpecifier, specifierLen));
9326 
9327     return true;
9328   }
9329 
9330   // Only scalars are allowed for os_trace.
9331   if (FSType == Sema::FST_OSTrace &&
9332       (CS.getKind() == ConversionSpecifier::PArg ||
9333        CS.getKind() == ConversionSpecifier::sArg ||
9334        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9335     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9336                                                   specifierLen);
9337   }
9338 
9339   // Check for use of public/private annotation outside of os_log().
9340   if (FSType != Sema::FST_OSLog) {
9341     if (FS.isPublic().isSet()) {
9342       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9343                                << "public",
9344                            getLocationOfByte(FS.isPublic().getPosition()),
9345                            /*IsStringLocation*/ false,
9346                            getSpecifierRange(startSpecifier, specifierLen));
9347     }
9348     if (FS.isPrivate().isSet()) {
9349       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9350                                << "private",
9351                            getLocationOfByte(FS.isPrivate().getPosition()),
9352                            /*IsStringLocation*/ false,
9353                            getSpecifierRange(startSpecifier, specifierLen));
9354     }
9355   }
9356 
9357   const llvm::Triple &Triple = Target.getTriple();
9358   if (CS.getKind() == ConversionSpecifier::nArg &&
9359       (Triple.isAndroid() || Triple.isOSFuchsia())) {
9360     EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
9361                          getLocationOfByte(CS.getStart()),
9362                          /*IsStringLocation*/ false,
9363                          getSpecifierRange(startSpecifier, specifierLen));
9364   }
9365 
9366   // Check for invalid use of field width
9367   if (!FS.hasValidFieldWidth()) {
9368     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9369         startSpecifier, specifierLen);
9370   }
9371 
9372   // Check for invalid use of precision
9373   if (!FS.hasValidPrecision()) {
9374     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9375         startSpecifier, specifierLen);
9376   }
9377 
9378   // Precision is mandatory for %P specifier.
9379   if (CS.getKind() == ConversionSpecifier::PArg &&
9380       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9381     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9382                          getLocationOfByte(startSpecifier),
9383                          /*IsStringLocation*/ false,
9384                          getSpecifierRange(startSpecifier, specifierLen));
9385   }
9386 
9387   // Check each flag does not conflict with any other component.
9388   if (!FS.hasValidThousandsGroupingPrefix())
9389     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9390   if (!FS.hasValidLeadingZeros())
9391     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9392   if (!FS.hasValidPlusPrefix())
9393     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9394   if (!FS.hasValidSpacePrefix())
9395     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9396   if (!FS.hasValidAlternativeForm())
9397     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9398   if (!FS.hasValidLeftJustified())
9399     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9400 
9401   // Check that flags are not ignored by another flag
9402   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9403     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9404         startSpecifier, specifierLen);
9405   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9406     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9407             startSpecifier, specifierLen);
9408 
9409   // Check the length modifier is valid with the given conversion specifier.
9410   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9411                                  S.getLangOpts()))
9412     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9413                                 diag::warn_format_nonsensical_length);
9414   else if (!FS.hasStandardLengthModifier())
9415     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9416   else if (!FS.hasStandardLengthConversionCombination())
9417     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9418                                 diag::warn_format_non_standard_conversion_spec);
9419 
9420   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9421     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9422 
9423   // The remaining checks depend on the data arguments.
9424   if (HasVAListArg)
9425     return true;
9426 
9427   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9428     return false;
9429 
9430   const Expr *Arg = getDataArg(argIndex);
9431   if (!Arg)
9432     return true;
9433 
9434   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9435 }
9436 
9437 static bool requiresParensToAddCast(const Expr *E) {
9438   // FIXME: We should have a general way to reason about operator
9439   // precedence and whether parens are actually needed here.
9440   // Take care of a few common cases where they aren't.
9441   const Expr *Inside = E->IgnoreImpCasts();
9442   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9443     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9444 
9445   switch (Inside->getStmtClass()) {
9446   case Stmt::ArraySubscriptExprClass:
9447   case Stmt::CallExprClass:
9448   case Stmt::CharacterLiteralClass:
9449   case Stmt::CXXBoolLiteralExprClass:
9450   case Stmt::DeclRefExprClass:
9451   case Stmt::FloatingLiteralClass:
9452   case Stmt::IntegerLiteralClass:
9453   case Stmt::MemberExprClass:
9454   case Stmt::ObjCArrayLiteralClass:
9455   case Stmt::ObjCBoolLiteralExprClass:
9456   case Stmt::ObjCBoxedExprClass:
9457   case Stmt::ObjCDictionaryLiteralClass:
9458   case Stmt::ObjCEncodeExprClass:
9459   case Stmt::ObjCIvarRefExprClass:
9460   case Stmt::ObjCMessageExprClass:
9461   case Stmt::ObjCPropertyRefExprClass:
9462   case Stmt::ObjCStringLiteralClass:
9463   case Stmt::ObjCSubscriptRefExprClass:
9464   case Stmt::ParenExprClass:
9465   case Stmt::StringLiteralClass:
9466   case Stmt::UnaryOperatorClass:
9467     return false;
9468   default:
9469     return true;
9470   }
9471 }
9472 
9473 static std::pair<QualType, StringRef>
9474 shouldNotPrintDirectly(const ASTContext &Context,
9475                        QualType IntendedTy,
9476                        const Expr *E) {
9477   // Use a 'while' to peel off layers of typedefs.
9478   QualType TyTy = IntendedTy;
9479   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9480     StringRef Name = UserTy->getDecl()->getName();
9481     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9482       .Case("CFIndex", Context.getNSIntegerType())
9483       .Case("NSInteger", Context.getNSIntegerType())
9484       .Case("NSUInteger", Context.getNSUIntegerType())
9485       .Case("SInt32", Context.IntTy)
9486       .Case("UInt32", Context.UnsignedIntTy)
9487       .Default(QualType());
9488 
9489     if (!CastTy.isNull())
9490       return std::make_pair(CastTy, Name);
9491 
9492     TyTy = UserTy->desugar();
9493   }
9494 
9495   // Strip parens if necessary.
9496   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9497     return shouldNotPrintDirectly(Context,
9498                                   PE->getSubExpr()->getType(),
9499                                   PE->getSubExpr());
9500 
9501   // If this is a conditional expression, then its result type is constructed
9502   // via usual arithmetic conversions and thus there might be no necessary
9503   // typedef sugar there.  Recurse to operands to check for NSInteger &
9504   // Co. usage condition.
9505   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9506     QualType TrueTy, FalseTy;
9507     StringRef TrueName, FalseName;
9508 
9509     std::tie(TrueTy, TrueName) =
9510       shouldNotPrintDirectly(Context,
9511                              CO->getTrueExpr()->getType(),
9512                              CO->getTrueExpr());
9513     std::tie(FalseTy, FalseName) =
9514       shouldNotPrintDirectly(Context,
9515                              CO->getFalseExpr()->getType(),
9516                              CO->getFalseExpr());
9517 
9518     if (TrueTy == FalseTy)
9519       return std::make_pair(TrueTy, TrueName);
9520     else if (TrueTy.isNull())
9521       return std::make_pair(FalseTy, FalseName);
9522     else if (FalseTy.isNull())
9523       return std::make_pair(TrueTy, TrueName);
9524   }
9525 
9526   return std::make_pair(QualType(), StringRef());
9527 }
9528 
9529 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9530 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9531 /// type do not count.
9532 static bool
9533 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9534   QualType From = ICE->getSubExpr()->getType();
9535   QualType To = ICE->getType();
9536   // It's an integer promotion if the destination type is the promoted
9537   // source type.
9538   if (ICE->getCastKind() == CK_IntegralCast &&
9539       From->isPromotableIntegerType() &&
9540       S.Context.getPromotedIntegerType(From) == To)
9541     return true;
9542   // Look through vector types, since we do default argument promotion for
9543   // those in OpenCL.
9544   if (const auto *VecTy = From->getAs<ExtVectorType>())
9545     From = VecTy->getElementType();
9546   if (const auto *VecTy = To->getAs<ExtVectorType>())
9547     To = VecTy->getElementType();
9548   // It's a floating promotion if the source type is a lower rank.
9549   return ICE->getCastKind() == CK_FloatingCast &&
9550          S.Context.getFloatingTypeOrder(From, To) < 0;
9551 }
9552 
9553 bool
9554 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9555                                     const char *StartSpecifier,
9556                                     unsigned SpecifierLen,
9557                                     const Expr *E) {
9558   using namespace analyze_format_string;
9559   using namespace analyze_printf;
9560 
9561   // Now type check the data expression that matches the
9562   // format specifier.
9563   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9564   if (!AT.isValid())
9565     return true;
9566 
9567   QualType ExprTy = E->getType();
9568   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9569     ExprTy = TET->getUnderlyingExpr()->getType();
9570   }
9571 
9572   // Diagnose attempts to print a boolean value as a character. Unlike other
9573   // -Wformat diagnostics, this is fine from a type perspective, but it still
9574   // doesn't make sense.
9575   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9576       E->isKnownToHaveBooleanValue()) {
9577     const CharSourceRange &CSR =
9578         getSpecifierRange(StartSpecifier, SpecifierLen);
9579     SmallString<4> FSString;
9580     llvm::raw_svector_ostream os(FSString);
9581     FS.toString(os);
9582     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9583                              << FSString,
9584                          E->getExprLoc(), false, CSR);
9585     return true;
9586   }
9587 
9588   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9589   if (Match == analyze_printf::ArgType::Match)
9590     return true;
9591 
9592   // Look through argument promotions for our error message's reported type.
9593   // This includes the integral and floating promotions, but excludes array
9594   // and function pointer decay (seeing that an argument intended to be a
9595   // string has type 'char [6]' is probably more confusing than 'char *') and
9596   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9597   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9598     if (isArithmeticArgumentPromotion(S, ICE)) {
9599       E = ICE->getSubExpr();
9600       ExprTy = E->getType();
9601 
9602       // Check if we didn't match because of an implicit cast from a 'char'
9603       // or 'short' to an 'int'.  This is done because printf is a varargs
9604       // function.
9605       if (ICE->getType() == S.Context.IntTy ||
9606           ICE->getType() == S.Context.UnsignedIntTy) {
9607         // All further checking is done on the subexpression
9608         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9609             AT.matchesType(S.Context, ExprTy);
9610         if (ImplicitMatch == analyze_printf::ArgType::Match)
9611           return true;
9612         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9613             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9614           Match = ImplicitMatch;
9615       }
9616     }
9617   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9618     // Special case for 'a', which has type 'int' in C.
9619     // Note, however, that we do /not/ want to treat multibyte constants like
9620     // 'MooV' as characters! This form is deprecated but still exists. In
9621     // addition, don't treat expressions as of type 'char' if one byte length
9622     // modifier is provided.
9623     if (ExprTy == S.Context.IntTy &&
9624         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9625       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9626         ExprTy = S.Context.CharTy;
9627   }
9628 
9629   // Look through enums to their underlying type.
9630   bool IsEnum = false;
9631   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9632     ExprTy = EnumTy->getDecl()->getIntegerType();
9633     IsEnum = true;
9634   }
9635 
9636   // %C in an Objective-C context prints a unichar, not a wchar_t.
9637   // If the argument is an integer of some kind, believe the %C and suggest
9638   // a cast instead of changing the conversion specifier.
9639   QualType IntendedTy = ExprTy;
9640   if (isObjCContext() &&
9641       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9642     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9643         !ExprTy->isCharType()) {
9644       // 'unichar' is defined as a typedef of unsigned short, but we should
9645       // prefer using the typedef if it is visible.
9646       IntendedTy = S.Context.UnsignedShortTy;
9647 
9648       // While we are here, check if the value is an IntegerLiteral that happens
9649       // to be within the valid range.
9650       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9651         const llvm::APInt &V = IL->getValue();
9652         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9653           return true;
9654       }
9655 
9656       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9657                           Sema::LookupOrdinaryName);
9658       if (S.LookupName(Result, S.getCurScope())) {
9659         NamedDecl *ND = Result.getFoundDecl();
9660         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9661           if (TD->getUnderlyingType() == IntendedTy)
9662             IntendedTy = S.Context.getTypedefType(TD);
9663       }
9664     }
9665   }
9666 
9667   // Special-case some of Darwin's platform-independence types by suggesting
9668   // casts to primitive types that are known to be large enough.
9669   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9670   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9671     QualType CastTy;
9672     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9673     if (!CastTy.isNull()) {
9674       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9675       // (long in ASTContext). Only complain to pedants.
9676       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9677           (AT.isSizeT() || AT.isPtrdiffT()) &&
9678           AT.matchesType(S.Context, CastTy))
9679         Match = ArgType::NoMatchPedantic;
9680       IntendedTy = CastTy;
9681       ShouldNotPrintDirectly = true;
9682     }
9683   }
9684 
9685   // We may be able to offer a FixItHint if it is a supported type.
9686   PrintfSpecifier fixedFS = FS;
9687   bool Success =
9688       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9689 
9690   if (Success) {
9691     // Get the fix string from the fixed format specifier
9692     SmallString<16> buf;
9693     llvm::raw_svector_ostream os(buf);
9694     fixedFS.toString(os);
9695 
9696     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9697 
9698     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9699       unsigned Diag;
9700       switch (Match) {
9701       case ArgType::Match: llvm_unreachable("expected non-matching");
9702       case ArgType::NoMatchPedantic:
9703         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9704         break;
9705       case ArgType::NoMatchTypeConfusion:
9706         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9707         break;
9708       case ArgType::NoMatch:
9709         Diag = diag::warn_format_conversion_argument_type_mismatch;
9710         break;
9711       }
9712 
9713       // In this case, the specifier is wrong and should be changed to match
9714       // the argument.
9715       EmitFormatDiagnostic(S.PDiag(Diag)
9716                                << AT.getRepresentativeTypeName(S.Context)
9717                                << IntendedTy << IsEnum << E->getSourceRange(),
9718                            E->getBeginLoc(),
9719                            /*IsStringLocation*/ false, SpecRange,
9720                            FixItHint::CreateReplacement(SpecRange, os.str()));
9721     } else {
9722       // The canonical type for formatting this value is different from the
9723       // actual type of the expression. (This occurs, for example, with Darwin's
9724       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9725       // should be printed as 'long' for 64-bit compatibility.)
9726       // Rather than emitting a normal format/argument mismatch, we want to
9727       // add a cast to the recommended type (and correct the format string
9728       // if necessary).
9729       SmallString<16> CastBuf;
9730       llvm::raw_svector_ostream CastFix(CastBuf);
9731       CastFix << "(";
9732       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9733       CastFix << ")";
9734 
9735       SmallVector<FixItHint,4> Hints;
9736       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9737         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9738 
9739       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9740         // If there's already a cast present, just replace it.
9741         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9742         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9743 
9744       } else if (!requiresParensToAddCast(E)) {
9745         // If the expression has high enough precedence,
9746         // just write the C-style cast.
9747         Hints.push_back(
9748             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9749       } else {
9750         // Otherwise, add parens around the expression as well as the cast.
9751         CastFix << "(";
9752         Hints.push_back(
9753             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9754 
9755         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9756         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9757       }
9758 
9759       if (ShouldNotPrintDirectly) {
9760         // The expression has a type that should not be printed directly.
9761         // We extract the name from the typedef because we don't want to show
9762         // the underlying type in the diagnostic.
9763         StringRef Name;
9764         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9765           Name = TypedefTy->getDecl()->getName();
9766         else
9767           Name = CastTyName;
9768         unsigned Diag = Match == ArgType::NoMatchPedantic
9769                             ? diag::warn_format_argument_needs_cast_pedantic
9770                             : diag::warn_format_argument_needs_cast;
9771         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9772                                            << E->getSourceRange(),
9773                              E->getBeginLoc(), /*IsStringLocation=*/false,
9774                              SpecRange, Hints);
9775       } else {
9776         // In this case, the expression could be printed using a different
9777         // specifier, but we've decided that the specifier is probably correct
9778         // and we should cast instead. Just use the normal warning message.
9779         EmitFormatDiagnostic(
9780             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9781                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9782                 << E->getSourceRange(),
9783             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9784       }
9785     }
9786   } else {
9787     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9788                                                    SpecifierLen);
9789     // Since the warning for passing non-POD types to variadic functions
9790     // was deferred until now, we emit a warning for non-POD
9791     // arguments here.
9792     switch (S.isValidVarArgType(ExprTy)) {
9793     case Sema::VAK_Valid:
9794     case Sema::VAK_ValidInCXX11: {
9795       unsigned Diag;
9796       switch (Match) {
9797       case ArgType::Match: llvm_unreachable("expected non-matching");
9798       case ArgType::NoMatchPedantic:
9799         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9800         break;
9801       case ArgType::NoMatchTypeConfusion:
9802         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9803         break;
9804       case ArgType::NoMatch:
9805         Diag = diag::warn_format_conversion_argument_type_mismatch;
9806         break;
9807       }
9808 
9809       EmitFormatDiagnostic(
9810           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9811                         << IsEnum << CSR << E->getSourceRange(),
9812           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9813       break;
9814     }
9815     case Sema::VAK_Undefined:
9816     case Sema::VAK_MSVCUndefined:
9817       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9818                                << S.getLangOpts().CPlusPlus11 << ExprTy
9819                                << CallType
9820                                << AT.getRepresentativeTypeName(S.Context) << CSR
9821                                << E->getSourceRange(),
9822                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9823       checkForCStrMembers(AT, E);
9824       break;
9825 
9826     case Sema::VAK_Invalid:
9827       if (ExprTy->isObjCObjectType())
9828         EmitFormatDiagnostic(
9829             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9830                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9831                 << AT.getRepresentativeTypeName(S.Context) << CSR
9832                 << E->getSourceRange(),
9833             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9834       else
9835         // FIXME: If this is an initializer list, suggest removing the braces
9836         // or inserting a cast to the target type.
9837         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9838             << isa<InitListExpr>(E) << ExprTy << CallType
9839             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9840       break;
9841     }
9842 
9843     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9844            "format string specifier index out of range");
9845     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9846   }
9847 
9848   return true;
9849 }
9850 
9851 //===--- CHECK: Scanf format string checking ------------------------------===//
9852 
9853 namespace {
9854 
9855 class CheckScanfHandler : public CheckFormatHandler {
9856 public:
9857   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9858                     const Expr *origFormatExpr, Sema::FormatStringType type,
9859                     unsigned firstDataArg, unsigned numDataArgs,
9860                     const char *beg, bool hasVAListArg,
9861                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9862                     bool inFunctionCall, Sema::VariadicCallType CallType,
9863                     llvm::SmallBitVector &CheckedVarArgs,
9864                     UncoveredArgHandler &UncoveredArg)
9865       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9866                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9867                            inFunctionCall, CallType, CheckedVarArgs,
9868                            UncoveredArg) {}
9869 
9870   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9871                             const char *startSpecifier,
9872                             unsigned specifierLen) override;
9873 
9874   bool HandleInvalidScanfConversionSpecifier(
9875           const analyze_scanf::ScanfSpecifier &FS,
9876           const char *startSpecifier,
9877           unsigned specifierLen) override;
9878 
9879   void HandleIncompleteScanList(const char *start, const char *end) override;
9880 };
9881 
9882 } // namespace
9883 
9884 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9885                                                  const char *end) {
9886   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9887                        getLocationOfByte(end), /*IsStringLocation*/true,
9888                        getSpecifierRange(start, end - start));
9889 }
9890 
9891 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9892                                         const analyze_scanf::ScanfSpecifier &FS,
9893                                         const char *startSpecifier,
9894                                         unsigned specifierLen) {
9895   const analyze_scanf::ScanfConversionSpecifier &CS =
9896     FS.getConversionSpecifier();
9897 
9898   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9899                                           getLocationOfByte(CS.getStart()),
9900                                           startSpecifier, specifierLen,
9901                                           CS.getStart(), CS.getLength());
9902 }
9903 
9904 bool CheckScanfHandler::HandleScanfSpecifier(
9905                                        const analyze_scanf::ScanfSpecifier &FS,
9906                                        const char *startSpecifier,
9907                                        unsigned specifierLen) {
9908   using namespace analyze_scanf;
9909   using namespace analyze_format_string;
9910 
9911   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9912 
9913   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9914   // be used to decide if we are using positional arguments consistently.
9915   if (FS.consumesDataArgument()) {
9916     if (atFirstArg) {
9917       atFirstArg = false;
9918       usesPositionalArgs = FS.usesPositionalArg();
9919     }
9920     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9921       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9922                                         startSpecifier, specifierLen);
9923       return false;
9924     }
9925   }
9926 
9927   // Check if the field with is non-zero.
9928   const OptionalAmount &Amt = FS.getFieldWidth();
9929   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9930     if (Amt.getConstantAmount() == 0) {
9931       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9932                                                    Amt.getConstantLength());
9933       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9934                            getLocationOfByte(Amt.getStart()),
9935                            /*IsStringLocation*/true, R,
9936                            FixItHint::CreateRemoval(R));
9937     }
9938   }
9939 
9940   if (!FS.consumesDataArgument()) {
9941     // FIXME: Technically specifying a precision or field width here
9942     // makes no sense.  Worth issuing a warning at some point.
9943     return true;
9944   }
9945 
9946   // Consume the argument.
9947   unsigned argIndex = FS.getArgIndex();
9948   if (argIndex < NumDataArgs) {
9949       // The check to see if the argIndex is valid will come later.
9950       // We set the bit here because we may exit early from this
9951       // function if we encounter some other error.
9952     CoveredArgs.set(argIndex);
9953   }
9954 
9955   // Check the length modifier is valid with the given conversion specifier.
9956   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9957                                  S.getLangOpts()))
9958     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9959                                 diag::warn_format_nonsensical_length);
9960   else if (!FS.hasStandardLengthModifier())
9961     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9962   else if (!FS.hasStandardLengthConversionCombination())
9963     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9964                                 diag::warn_format_non_standard_conversion_spec);
9965 
9966   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9967     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9968 
9969   // The remaining checks depend on the data arguments.
9970   if (HasVAListArg)
9971     return true;
9972 
9973   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9974     return false;
9975 
9976   // Check that the argument type matches the format specifier.
9977   const Expr *Ex = getDataArg(argIndex);
9978   if (!Ex)
9979     return true;
9980 
9981   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9982 
9983   if (!AT.isValid()) {
9984     return true;
9985   }
9986 
9987   analyze_format_string::ArgType::MatchKind Match =
9988       AT.matchesType(S.Context, Ex->getType());
9989   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9990   if (Match == analyze_format_string::ArgType::Match)
9991     return true;
9992 
9993   ScanfSpecifier fixedFS = FS;
9994   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9995                                  S.getLangOpts(), S.Context);
9996 
9997   unsigned Diag =
9998       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9999                : diag::warn_format_conversion_argument_type_mismatch;
10000 
10001   if (Success) {
10002     // Get the fix string from the fixed format specifier.
10003     SmallString<128> buf;
10004     llvm::raw_svector_ostream os(buf);
10005     fixedFS.toString(os);
10006 
10007     EmitFormatDiagnostic(
10008         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
10009                       << Ex->getType() << false << Ex->getSourceRange(),
10010         Ex->getBeginLoc(),
10011         /*IsStringLocation*/ false,
10012         getSpecifierRange(startSpecifier, specifierLen),
10013         FixItHint::CreateReplacement(
10014             getSpecifierRange(startSpecifier, specifierLen), os.str()));
10015   } else {
10016     EmitFormatDiagnostic(S.PDiag(Diag)
10017                              << AT.getRepresentativeTypeName(S.Context)
10018                              << Ex->getType() << false << Ex->getSourceRange(),
10019                          Ex->getBeginLoc(),
10020                          /*IsStringLocation*/ false,
10021                          getSpecifierRange(startSpecifier, specifierLen));
10022   }
10023 
10024   return true;
10025 }
10026 
10027 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
10028                               const Expr *OrigFormatExpr,
10029                               ArrayRef<const Expr *> Args,
10030                               bool HasVAListArg, unsigned format_idx,
10031                               unsigned firstDataArg,
10032                               Sema::FormatStringType Type,
10033                               bool inFunctionCall,
10034                               Sema::VariadicCallType CallType,
10035                               llvm::SmallBitVector &CheckedVarArgs,
10036                               UncoveredArgHandler &UncoveredArg,
10037                               bool IgnoreStringsWithoutSpecifiers) {
10038   // CHECK: is the format string a wide literal?
10039   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
10040     CheckFormatHandler::EmitFormatDiagnostic(
10041         S, inFunctionCall, Args[format_idx],
10042         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
10043         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10044     return;
10045   }
10046 
10047   // Str - The format string.  NOTE: this is NOT null-terminated!
10048   StringRef StrRef = FExpr->getString();
10049   const char *Str = StrRef.data();
10050   // Account for cases where the string literal is truncated in a declaration.
10051   const ConstantArrayType *T =
10052     S.Context.getAsConstantArrayType(FExpr->getType());
10053   assert(T && "String literal not of constant array type!");
10054   size_t TypeSize = T->getSize().getZExtValue();
10055   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10056   const unsigned numDataArgs = Args.size() - firstDataArg;
10057 
10058   if (IgnoreStringsWithoutSpecifiers &&
10059       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
10060           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10061     return;
10062 
10063   // Emit a warning if the string literal is truncated and does not contain an
10064   // embedded null character.
10065   if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
10066     CheckFormatHandler::EmitFormatDiagnostic(
10067         S, inFunctionCall, Args[format_idx],
10068         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
10069         FExpr->getBeginLoc(),
10070         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
10071     return;
10072   }
10073 
10074   // CHECK: empty format string?
10075   if (StrLen == 0 && numDataArgs > 0) {
10076     CheckFormatHandler::EmitFormatDiagnostic(
10077         S, inFunctionCall, Args[format_idx],
10078         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
10079         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10080     return;
10081   }
10082 
10083   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
10084       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
10085       Type == Sema::FST_OSTrace) {
10086     CheckPrintfHandler H(
10087         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
10088         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
10089         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
10090         CheckedVarArgs, UncoveredArg);
10091 
10092     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
10093                                                   S.getLangOpts(),
10094                                                   S.Context.getTargetInfo(),
10095                                             Type == Sema::FST_FreeBSDKPrintf))
10096       H.DoneProcessing();
10097   } else if (Type == Sema::FST_Scanf) {
10098     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10099                         numDataArgs, Str, HasVAListArg, Args, format_idx,
10100                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
10101 
10102     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
10103                                                  S.getLangOpts(),
10104                                                  S.Context.getTargetInfo()))
10105       H.DoneProcessing();
10106   } // TODO: handle other formats
10107 }
10108 
10109 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
10110   // Str - The format string.  NOTE: this is NOT null-terminated!
10111   StringRef StrRef = FExpr->getString();
10112   const char *Str = StrRef.data();
10113   // Account for cases where the string literal is truncated in a declaration.
10114   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
10115   assert(T && "String literal not of constant array type!");
10116   size_t TypeSize = T->getSize().getZExtValue();
10117   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10118   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
10119                                                          getLangOpts(),
10120                                                          Context.getTargetInfo());
10121 }
10122 
10123 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10124 
10125 // Returns the related absolute value function that is larger, of 0 if one
10126 // does not exist.
10127 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10128   switch (AbsFunction) {
10129   default:
10130     return 0;
10131 
10132   case Builtin::BI__builtin_abs:
10133     return Builtin::BI__builtin_labs;
10134   case Builtin::BI__builtin_labs:
10135     return Builtin::BI__builtin_llabs;
10136   case Builtin::BI__builtin_llabs:
10137     return 0;
10138 
10139   case Builtin::BI__builtin_fabsf:
10140     return Builtin::BI__builtin_fabs;
10141   case Builtin::BI__builtin_fabs:
10142     return Builtin::BI__builtin_fabsl;
10143   case Builtin::BI__builtin_fabsl:
10144     return 0;
10145 
10146   case Builtin::BI__builtin_cabsf:
10147     return Builtin::BI__builtin_cabs;
10148   case Builtin::BI__builtin_cabs:
10149     return Builtin::BI__builtin_cabsl;
10150   case Builtin::BI__builtin_cabsl:
10151     return 0;
10152 
10153   case Builtin::BIabs:
10154     return Builtin::BIlabs;
10155   case Builtin::BIlabs:
10156     return Builtin::BIllabs;
10157   case Builtin::BIllabs:
10158     return 0;
10159 
10160   case Builtin::BIfabsf:
10161     return Builtin::BIfabs;
10162   case Builtin::BIfabs:
10163     return Builtin::BIfabsl;
10164   case Builtin::BIfabsl:
10165     return 0;
10166 
10167   case Builtin::BIcabsf:
10168    return Builtin::BIcabs;
10169   case Builtin::BIcabs:
10170     return Builtin::BIcabsl;
10171   case Builtin::BIcabsl:
10172     return 0;
10173   }
10174 }
10175 
10176 // Returns the argument type of the absolute value function.
10177 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
10178                                              unsigned AbsType) {
10179   if (AbsType == 0)
10180     return QualType();
10181 
10182   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
10183   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10184   if (Error != ASTContext::GE_None)
10185     return QualType();
10186 
10187   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
10188   if (!FT)
10189     return QualType();
10190 
10191   if (FT->getNumParams() != 1)
10192     return QualType();
10193 
10194   return FT->getParamType(0);
10195 }
10196 
10197 // Returns the best absolute value function, or zero, based on type and
10198 // current absolute value function.
10199 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10200                                    unsigned AbsFunctionKind) {
10201   unsigned BestKind = 0;
10202   uint64_t ArgSize = Context.getTypeSize(ArgType);
10203   for (unsigned Kind = AbsFunctionKind; Kind != 0;
10204        Kind = getLargerAbsoluteValueFunction(Kind)) {
10205     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10206     if (Context.getTypeSize(ParamType) >= ArgSize) {
10207       if (BestKind == 0)
10208         BestKind = Kind;
10209       else if (Context.hasSameType(ParamType, ArgType)) {
10210         BestKind = Kind;
10211         break;
10212       }
10213     }
10214   }
10215   return BestKind;
10216 }
10217 
10218 enum AbsoluteValueKind {
10219   AVK_Integer,
10220   AVK_Floating,
10221   AVK_Complex
10222 };
10223 
10224 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
10225   if (T->isIntegralOrEnumerationType())
10226     return AVK_Integer;
10227   if (T->isRealFloatingType())
10228     return AVK_Floating;
10229   if (T->isAnyComplexType())
10230     return AVK_Complex;
10231 
10232   llvm_unreachable("Type not integer, floating, or complex");
10233 }
10234 
10235 // Changes the absolute value function to a different type.  Preserves whether
10236 // the function is a builtin.
10237 static unsigned changeAbsFunction(unsigned AbsKind,
10238                                   AbsoluteValueKind ValueKind) {
10239   switch (ValueKind) {
10240   case AVK_Integer:
10241     switch (AbsKind) {
10242     default:
10243       return 0;
10244     case Builtin::BI__builtin_fabsf:
10245     case Builtin::BI__builtin_fabs:
10246     case Builtin::BI__builtin_fabsl:
10247     case Builtin::BI__builtin_cabsf:
10248     case Builtin::BI__builtin_cabs:
10249     case Builtin::BI__builtin_cabsl:
10250       return Builtin::BI__builtin_abs;
10251     case Builtin::BIfabsf:
10252     case Builtin::BIfabs:
10253     case Builtin::BIfabsl:
10254     case Builtin::BIcabsf:
10255     case Builtin::BIcabs:
10256     case Builtin::BIcabsl:
10257       return Builtin::BIabs;
10258     }
10259   case AVK_Floating:
10260     switch (AbsKind) {
10261     default:
10262       return 0;
10263     case Builtin::BI__builtin_abs:
10264     case Builtin::BI__builtin_labs:
10265     case Builtin::BI__builtin_llabs:
10266     case Builtin::BI__builtin_cabsf:
10267     case Builtin::BI__builtin_cabs:
10268     case Builtin::BI__builtin_cabsl:
10269       return Builtin::BI__builtin_fabsf;
10270     case Builtin::BIabs:
10271     case Builtin::BIlabs:
10272     case Builtin::BIllabs:
10273     case Builtin::BIcabsf:
10274     case Builtin::BIcabs:
10275     case Builtin::BIcabsl:
10276       return Builtin::BIfabsf;
10277     }
10278   case AVK_Complex:
10279     switch (AbsKind) {
10280     default:
10281       return 0;
10282     case Builtin::BI__builtin_abs:
10283     case Builtin::BI__builtin_labs:
10284     case Builtin::BI__builtin_llabs:
10285     case Builtin::BI__builtin_fabsf:
10286     case Builtin::BI__builtin_fabs:
10287     case Builtin::BI__builtin_fabsl:
10288       return Builtin::BI__builtin_cabsf;
10289     case Builtin::BIabs:
10290     case Builtin::BIlabs:
10291     case Builtin::BIllabs:
10292     case Builtin::BIfabsf:
10293     case Builtin::BIfabs:
10294     case Builtin::BIfabsl:
10295       return Builtin::BIcabsf;
10296     }
10297   }
10298   llvm_unreachable("Unable to convert function");
10299 }
10300 
10301 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10302   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10303   if (!FnInfo)
10304     return 0;
10305 
10306   switch (FDecl->getBuiltinID()) {
10307   default:
10308     return 0;
10309   case Builtin::BI__builtin_abs:
10310   case Builtin::BI__builtin_fabs:
10311   case Builtin::BI__builtin_fabsf:
10312   case Builtin::BI__builtin_fabsl:
10313   case Builtin::BI__builtin_labs:
10314   case Builtin::BI__builtin_llabs:
10315   case Builtin::BI__builtin_cabs:
10316   case Builtin::BI__builtin_cabsf:
10317   case Builtin::BI__builtin_cabsl:
10318   case Builtin::BIabs:
10319   case Builtin::BIlabs:
10320   case Builtin::BIllabs:
10321   case Builtin::BIfabs:
10322   case Builtin::BIfabsf:
10323   case Builtin::BIfabsl:
10324   case Builtin::BIcabs:
10325   case Builtin::BIcabsf:
10326   case Builtin::BIcabsl:
10327     return FDecl->getBuiltinID();
10328   }
10329   llvm_unreachable("Unknown Builtin type");
10330 }
10331 
10332 // If the replacement is valid, emit a note with replacement function.
10333 // Additionally, suggest including the proper header if not already included.
10334 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10335                             unsigned AbsKind, QualType ArgType) {
10336   bool EmitHeaderHint = true;
10337   const char *HeaderName = nullptr;
10338   const char *FunctionName = nullptr;
10339   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10340     FunctionName = "std::abs";
10341     if (ArgType->isIntegralOrEnumerationType()) {
10342       HeaderName = "cstdlib";
10343     } else if (ArgType->isRealFloatingType()) {
10344       HeaderName = "cmath";
10345     } else {
10346       llvm_unreachable("Invalid Type");
10347     }
10348 
10349     // Lookup all std::abs
10350     if (NamespaceDecl *Std = S.getStdNamespace()) {
10351       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10352       R.suppressDiagnostics();
10353       S.LookupQualifiedName(R, Std);
10354 
10355       for (const auto *I : R) {
10356         const FunctionDecl *FDecl = nullptr;
10357         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10358           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10359         } else {
10360           FDecl = dyn_cast<FunctionDecl>(I);
10361         }
10362         if (!FDecl)
10363           continue;
10364 
10365         // Found std::abs(), check that they are the right ones.
10366         if (FDecl->getNumParams() != 1)
10367           continue;
10368 
10369         // Check that the parameter type can handle the argument.
10370         QualType ParamType = FDecl->getParamDecl(0)->getType();
10371         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10372             S.Context.getTypeSize(ArgType) <=
10373                 S.Context.getTypeSize(ParamType)) {
10374           // Found a function, don't need the header hint.
10375           EmitHeaderHint = false;
10376           break;
10377         }
10378       }
10379     }
10380   } else {
10381     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10382     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10383 
10384     if (HeaderName) {
10385       DeclarationName DN(&S.Context.Idents.get(FunctionName));
10386       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10387       R.suppressDiagnostics();
10388       S.LookupName(R, S.getCurScope());
10389 
10390       if (R.isSingleResult()) {
10391         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10392         if (FD && FD->getBuiltinID() == AbsKind) {
10393           EmitHeaderHint = false;
10394         } else {
10395           return;
10396         }
10397       } else if (!R.empty()) {
10398         return;
10399       }
10400     }
10401   }
10402 
10403   S.Diag(Loc, diag::note_replace_abs_function)
10404       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10405 
10406   if (!HeaderName)
10407     return;
10408 
10409   if (!EmitHeaderHint)
10410     return;
10411 
10412   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10413                                                     << FunctionName;
10414 }
10415 
10416 template <std::size_t StrLen>
10417 static bool IsStdFunction(const FunctionDecl *FDecl,
10418                           const char (&Str)[StrLen]) {
10419   if (!FDecl)
10420     return false;
10421   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10422     return false;
10423   if (!FDecl->isInStdNamespace())
10424     return false;
10425 
10426   return true;
10427 }
10428 
10429 // Warn when using the wrong abs() function.
10430 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10431                                       const FunctionDecl *FDecl) {
10432   if (Call->getNumArgs() != 1)
10433     return;
10434 
10435   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10436   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10437   if (AbsKind == 0 && !IsStdAbs)
10438     return;
10439 
10440   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10441   QualType ParamType = Call->getArg(0)->getType();
10442 
10443   // Unsigned types cannot be negative.  Suggest removing the absolute value
10444   // function call.
10445   if (ArgType->isUnsignedIntegerType()) {
10446     const char *FunctionName =
10447         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10448     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10449     Diag(Call->getExprLoc(), diag::note_remove_abs)
10450         << FunctionName
10451         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10452     return;
10453   }
10454 
10455   // Taking the absolute value of a pointer is very suspicious, they probably
10456   // wanted to index into an array, dereference a pointer, call a function, etc.
10457   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10458     unsigned DiagType = 0;
10459     if (ArgType->isFunctionType())
10460       DiagType = 1;
10461     else if (ArgType->isArrayType())
10462       DiagType = 2;
10463 
10464     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10465     return;
10466   }
10467 
10468   // std::abs has overloads which prevent most of the absolute value problems
10469   // from occurring.
10470   if (IsStdAbs)
10471     return;
10472 
10473   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10474   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10475 
10476   // The argument and parameter are the same kind.  Check if they are the right
10477   // size.
10478   if (ArgValueKind == ParamValueKind) {
10479     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10480       return;
10481 
10482     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10483     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10484         << FDecl << ArgType << ParamType;
10485 
10486     if (NewAbsKind == 0)
10487       return;
10488 
10489     emitReplacement(*this, Call->getExprLoc(),
10490                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10491     return;
10492   }
10493 
10494   // ArgValueKind != ParamValueKind
10495   // The wrong type of absolute value function was used.  Attempt to find the
10496   // proper one.
10497   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10498   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10499   if (NewAbsKind == 0)
10500     return;
10501 
10502   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10503       << FDecl << ParamValueKind << ArgValueKind;
10504 
10505   emitReplacement(*this, Call->getExprLoc(),
10506                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10507 }
10508 
10509 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10510 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10511                                 const FunctionDecl *FDecl) {
10512   if (!Call || !FDecl) return;
10513 
10514   // Ignore template specializations and macros.
10515   if (inTemplateInstantiation()) return;
10516   if (Call->getExprLoc().isMacroID()) return;
10517 
10518   // Only care about the one template argument, two function parameter std::max
10519   if (Call->getNumArgs() != 2) return;
10520   if (!IsStdFunction(FDecl, "max")) return;
10521   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10522   if (!ArgList) return;
10523   if (ArgList->size() != 1) return;
10524 
10525   // Check that template type argument is unsigned integer.
10526   const auto& TA = ArgList->get(0);
10527   if (TA.getKind() != TemplateArgument::Type) return;
10528   QualType ArgType = TA.getAsType();
10529   if (!ArgType->isUnsignedIntegerType()) return;
10530 
10531   // See if either argument is a literal zero.
10532   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10533     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10534     if (!MTE) return false;
10535     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10536     if (!Num) return false;
10537     if (Num->getValue() != 0) return false;
10538     return true;
10539   };
10540 
10541   const Expr *FirstArg = Call->getArg(0);
10542   const Expr *SecondArg = Call->getArg(1);
10543   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10544   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10545 
10546   // Only warn when exactly one argument is zero.
10547   if (IsFirstArgZero == IsSecondArgZero) return;
10548 
10549   SourceRange FirstRange = FirstArg->getSourceRange();
10550   SourceRange SecondRange = SecondArg->getSourceRange();
10551 
10552   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10553 
10554   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10555       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10556 
10557   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10558   SourceRange RemovalRange;
10559   if (IsFirstArgZero) {
10560     RemovalRange = SourceRange(FirstRange.getBegin(),
10561                                SecondRange.getBegin().getLocWithOffset(-1));
10562   } else {
10563     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10564                                SecondRange.getEnd());
10565   }
10566 
10567   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10568         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10569         << FixItHint::CreateRemoval(RemovalRange);
10570 }
10571 
10572 //===--- CHECK: Standard memory functions ---------------------------------===//
10573 
10574 /// Takes the expression passed to the size_t parameter of functions
10575 /// such as memcmp, strncat, etc and warns if it's a comparison.
10576 ///
10577 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10578 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10579                                            IdentifierInfo *FnName,
10580                                            SourceLocation FnLoc,
10581                                            SourceLocation RParenLoc) {
10582   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10583   if (!Size)
10584     return false;
10585 
10586   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10587   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10588     return false;
10589 
10590   SourceRange SizeRange = Size->getSourceRange();
10591   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10592       << SizeRange << FnName;
10593   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10594       << FnName
10595       << FixItHint::CreateInsertion(
10596              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10597       << FixItHint::CreateRemoval(RParenLoc);
10598   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10599       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10600       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10601                                     ")");
10602 
10603   return true;
10604 }
10605 
10606 /// Determine whether the given type is or contains a dynamic class type
10607 /// (e.g., whether it has a vtable).
10608 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10609                                                      bool &IsContained) {
10610   // Look through array types while ignoring qualifiers.
10611   const Type *Ty = T->getBaseElementTypeUnsafe();
10612   IsContained = false;
10613 
10614   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10615   RD = RD ? RD->getDefinition() : nullptr;
10616   if (!RD || RD->isInvalidDecl())
10617     return nullptr;
10618 
10619   if (RD->isDynamicClass())
10620     return RD;
10621 
10622   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10623   // It's impossible for a class to transitively contain itself by value, so
10624   // infinite recursion is impossible.
10625   for (auto *FD : RD->fields()) {
10626     bool SubContained;
10627     if (const CXXRecordDecl *ContainedRD =
10628             getContainedDynamicClass(FD->getType(), SubContained)) {
10629       IsContained = true;
10630       return ContainedRD;
10631     }
10632   }
10633 
10634   return nullptr;
10635 }
10636 
10637 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10638   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10639     if (Unary->getKind() == UETT_SizeOf)
10640       return Unary;
10641   return nullptr;
10642 }
10643 
10644 /// If E is a sizeof expression, returns its argument expression,
10645 /// otherwise returns NULL.
10646 static const Expr *getSizeOfExprArg(const Expr *E) {
10647   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10648     if (!SizeOf->isArgumentType())
10649       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10650   return nullptr;
10651 }
10652 
10653 /// If E is a sizeof expression, returns its argument type.
10654 static QualType getSizeOfArgType(const Expr *E) {
10655   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10656     return SizeOf->getTypeOfArgument();
10657   return QualType();
10658 }
10659 
10660 namespace {
10661 
10662 struct SearchNonTrivialToInitializeField
10663     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10664   using Super =
10665       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10666 
10667   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10668 
10669   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10670                      SourceLocation SL) {
10671     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10672       asDerived().visitArray(PDIK, AT, SL);
10673       return;
10674     }
10675 
10676     Super::visitWithKind(PDIK, FT, SL);
10677   }
10678 
10679   void visitARCStrong(QualType FT, SourceLocation SL) {
10680     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10681   }
10682   void visitARCWeak(QualType FT, SourceLocation SL) {
10683     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10684   }
10685   void visitStruct(QualType FT, SourceLocation SL) {
10686     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10687       visit(FD->getType(), FD->getLocation());
10688   }
10689   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10690                   const ArrayType *AT, SourceLocation SL) {
10691     visit(getContext().getBaseElementType(AT), SL);
10692   }
10693   void visitTrivial(QualType FT, SourceLocation SL) {}
10694 
10695   static void diag(QualType RT, const Expr *E, Sema &S) {
10696     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10697   }
10698 
10699   ASTContext &getContext() { return S.getASTContext(); }
10700 
10701   const Expr *E;
10702   Sema &S;
10703 };
10704 
10705 struct SearchNonTrivialToCopyField
10706     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10707   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10708 
10709   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10710 
10711   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10712                      SourceLocation SL) {
10713     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10714       asDerived().visitArray(PCK, AT, SL);
10715       return;
10716     }
10717 
10718     Super::visitWithKind(PCK, FT, SL);
10719   }
10720 
10721   void visitARCStrong(QualType FT, SourceLocation SL) {
10722     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10723   }
10724   void visitARCWeak(QualType FT, SourceLocation SL) {
10725     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10726   }
10727   void visitStruct(QualType FT, SourceLocation SL) {
10728     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10729       visit(FD->getType(), FD->getLocation());
10730   }
10731   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10732                   SourceLocation SL) {
10733     visit(getContext().getBaseElementType(AT), SL);
10734   }
10735   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10736                 SourceLocation SL) {}
10737   void visitTrivial(QualType FT, SourceLocation SL) {}
10738   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10739 
10740   static void diag(QualType RT, const Expr *E, Sema &S) {
10741     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10742   }
10743 
10744   ASTContext &getContext() { return S.getASTContext(); }
10745 
10746   const Expr *E;
10747   Sema &S;
10748 };
10749 
10750 }
10751 
10752 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10753 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10754   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10755 
10756   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10757     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10758       return false;
10759 
10760     return doesExprLikelyComputeSize(BO->getLHS()) ||
10761            doesExprLikelyComputeSize(BO->getRHS());
10762   }
10763 
10764   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10765 }
10766 
10767 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10768 ///
10769 /// \code
10770 ///   #define MACRO 0
10771 ///   foo(MACRO);
10772 ///   foo(0);
10773 /// \endcode
10774 ///
10775 /// This should return true for the first call to foo, but not for the second
10776 /// (regardless of whether foo is a macro or function).
10777 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10778                                         SourceLocation CallLoc,
10779                                         SourceLocation ArgLoc) {
10780   if (!CallLoc.isMacroID())
10781     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10782 
10783   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10784          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10785 }
10786 
10787 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10788 /// last two arguments transposed.
10789 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10790   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10791     return;
10792 
10793   const Expr *SizeArg =
10794     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10795 
10796   auto isLiteralZero = [](const Expr *E) {
10797     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10798   };
10799 
10800   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10801   SourceLocation CallLoc = Call->getRParenLoc();
10802   SourceManager &SM = S.getSourceManager();
10803   if (isLiteralZero(SizeArg) &&
10804       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10805 
10806     SourceLocation DiagLoc = SizeArg->getExprLoc();
10807 
10808     // Some platforms #define bzero to __builtin_memset. See if this is the
10809     // case, and if so, emit a better diagnostic.
10810     if (BId == Builtin::BIbzero ||
10811         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10812                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10813       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10814       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10815     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10816       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10817       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10818     }
10819     return;
10820   }
10821 
10822   // If the second argument to a memset is a sizeof expression and the third
10823   // isn't, this is also likely an error. This should catch
10824   // 'memset(buf, sizeof(buf), 0xff)'.
10825   if (BId == Builtin::BImemset &&
10826       doesExprLikelyComputeSize(Call->getArg(1)) &&
10827       !doesExprLikelyComputeSize(Call->getArg(2))) {
10828     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10829     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10830     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10831     return;
10832   }
10833 }
10834 
10835 /// Check for dangerous or invalid arguments to memset().
10836 ///
10837 /// This issues warnings on known problematic, dangerous or unspecified
10838 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10839 /// function calls.
10840 ///
10841 /// \param Call The call expression to diagnose.
10842 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10843                                    unsigned BId,
10844                                    IdentifierInfo *FnName) {
10845   assert(BId != 0);
10846 
10847   // It is possible to have a non-standard definition of memset.  Validate
10848   // we have enough arguments, and if not, abort further checking.
10849   unsigned ExpectedNumArgs =
10850       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10851   if (Call->getNumArgs() < ExpectedNumArgs)
10852     return;
10853 
10854   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10855                       BId == Builtin::BIstrndup ? 1 : 2);
10856   unsigned LenArg =
10857       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10858   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10859 
10860   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10861                                      Call->getBeginLoc(), Call->getRParenLoc()))
10862     return;
10863 
10864   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10865   CheckMemaccessSize(*this, BId, Call);
10866 
10867   // We have special checking when the length is a sizeof expression.
10868   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10869   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10870   llvm::FoldingSetNodeID SizeOfArgID;
10871 
10872   // Although widely used, 'bzero' is not a standard function. Be more strict
10873   // with the argument types before allowing diagnostics and only allow the
10874   // form bzero(ptr, sizeof(...)).
10875   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10876   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10877     return;
10878 
10879   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10880     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10881     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10882 
10883     QualType DestTy = Dest->getType();
10884     QualType PointeeTy;
10885     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10886       PointeeTy = DestPtrTy->getPointeeType();
10887 
10888       // Never warn about void type pointers. This can be used to suppress
10889       // false positives.
10890       if (PointeeTy->isVoidType())
10891         continue;
10892 
10893       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10894       // actually comparing the expressions for equality. Because computing the
10895       // expression IDs can be expensive, we only do this if the diagnostic is
10896       // enabled.
10897       if (SizeOfArg &&
10898           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10899                            SizeOfArg->getExprLoc())) {
10900         // We only compute IDs for expressions if the warning is enabled, and
10901         // cache the sizeof arg's ID.
10902         if (SizeOfArgID == llvm::FoldingSetNodeID())
10903           SizeOfArg->Profile(SizeOfArgID, Context, true);
10904         llvm::FoldingSetNodeID DestID;
10905         Dest->Profile(DestID, Context, true);
10906         if (DestID == SizeOfArgID) {
10907           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10908           //       over sizeof(src) as well.
10909           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10910           StringRef ReadableName = FnName->getName();
10911 
10912           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10913             if (UnaryOp->getOpcode() == UO_AddrOf)
10914               ActionIdx = 1; // If its an address-of operator, just remove it.
10915           if (!PointeeTy->isIncompleteType() &&
10916               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10917             ActionIdx = 2; // If the pointee's size is sizeof(char),
10918                            // suggest an explicit length.
10919 
10920           // If the function is defined as a builtin macro, do not show macro
10921           // expansion.
10922           SourceLocation SL = SizeOfArg->getExprLoc();
10923           SourceRange DSR = Dest->getSourceRange();
10924           SourceRange SSR = SizeOfArg->getSourceRange();
10925           SourceManager &SM = getSourceManager();
10926 
10927           if (SM.isMacroArgExpansion(SL)) {
10928             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10929             SL = SM.getSpellingLoc(SL);
10930             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10931                              SM.getSpellingLoc(DSR.getEnd()));
10932             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10933                              SM.getSpellingLoc(SSR.getEnd()));
10934           }
10935 
10936           DiagRuntimeBehavior(SL, SizeOfArg,
10937                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10938                                 << ReadableName
10939                                 << PointeeTy
10940                                 << DestTy
10941                                 << DSR
10942                                 << SSR);
10943           DiagRuntimeBehavior(SL, SizeOfArg,
10944                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10945                                 << ActionIdx
10946                                 << SSR);
10947 
10948           break;
10949         }
10950       }
10951 
10952       // Also check for cases where the sizeof argument is the exact same
10953       // type as the memory argument, and where it points to a user-defined
10954       // record type.
10955       if (SizeOfArgTy != QualType()) {
10956         if (PointeeTy->isRecordType() &&
10957             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10958           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10959                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10960                                 << FnName << SizeOfArgTy << ArgIdx
10961                                 << PointeeTy << Dest->getSourceRange()
10962                                 << LenExpr->getSourceRange());
10963           break;
10964         }
10965       }
10966     } else if (DestTy->isArrayType()) {
10967       PointeeTy = DestTy;
10968     }
10969 
10970     if (PointeeTy == QualType())
10971       continue;
10972 
10973     // Always complain about dynamic classes.
10974     bool IsContained;
10975     if (const CXXRecordDecl *ContainedRD =
10976             getContainedDynamicClass(PointeeTy, IsContained)) {
10977 
10978       unsigned OperationType = 0;
10979       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10980       // "overwritten" if we're warning about the destination for any call
10981       // but memcmp; otherwise a verb appropriate to the call.
10982       if (ArgIdx != 0 || IsCmp) {
10983         if (BId == Builtin::BImemcpy)
10984           OperationType = 1;
10985         else if(BId == Builtin::BImemmove)
10986           OperationType = 2;
10987         else if (IsCmp)
10988           OperationType = 3;
10989       }
10990 
10991       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10992                           PDiag(diag::warn_dyn_class_memaccess)
10993                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10994                               << IsContained << ContainedRD << OperationType
10995                               << Call->getCallee()->getSourceRange());
10996     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10997              BId != Builtin::BImemset)
10998       DiagRuntimeBehavior(
10999         Dest->getExprLoc(), Dest,
11000         PDiag(diag::warn_arc_object_memaccess)
11001           << ArgIdx << FnName << PointeeTy
11002           << Call->getCallee()->getSourceRange());
11003     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
11004       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11005           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
11006         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11007                             PDiag(diag::warn_cstruct_memaccess)
11008                                 << ArgIdx << FnName << PointeeTy << 0);
11009         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
11010       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11011                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
11012         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11013                             PDiag(diag::warn_cstruct_memaccess)
11014                                 << ArgIdx << FnName << PointeeTy << 1);
11015         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
11016       } else {
11017         continue;
11018       }
11019     } else
11020       continue;
11021 
11022     DiagRuntimeBehavior(
11023       Dest->getExprLoc(), Dest,
11024       PDiag(diag::note_bad_memaccess_silence)
11025         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
11026     break;
11027   }
11028 }
11029 
11030 // A little helper routine: ignore addition and subtraction of integer literals.
11031 // This intentionally does not ignore all integer constant expressions because
11032 // we don't want to remove sizeof().
11033 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11034   Ex = Ex->IgnoreParenCasts();
11035 
11036   while (true) {
11037     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
11038     if (!BO || !BO->isAdditiveOp())
11039       break;
11040 
11041     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11042     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11043 
11044     if (isa<IntegerLiteral>(RHS))
11045       Ex = LHS;
11046     else if (isa<IntegerLiteral>(LHS))
11047       Ex = RHS;
11048     else
11049       break;
11050   }
11051 
11052   return Ex;
11053 }
11054 
11055 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
11056                                                       ASTContext &Context) {
11057   // Only handle constant-sized or VLAs, but not flexible members.
11058   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
11059     // Only issue the FIXIT for arrays of size > 1.
11060     if (CAT->getSize().getSExtValue() <= 1)
11061       return false;
11062   } else if (!Ty->isVariableArrayType()) {
11063     return false;
11064   }
11065   return true;
11066 }
11067 
11068 // Warn if the user has made the 'size' argument to strlcpy or strlcat
11069 // be the size of the source, instead of the destination.
11070 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11071                                     IdentifierInfo *FnName) {
11072 
11073   // Don't crash if the user has the wrong number of arguments
11074   unsigned NumArgs = Call->getNumArgs();
11075   if ((NumArgs != 3) && (NumArgs != 4))
11076     return;
11077 
11078   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
11079   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
11080   const Expr *CompareWithSrc = nullptr;
11081 
11082   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
11083                                      Call->getBeginLoc(), Call->getRParenLoc()))
11084     return;
11085 
11086   // Look for 'strlcpy(dst, x, sizeof(x))'
11087   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
11088     CompareWithSrc = Ex;
11089   else {
11090     // Look for 'strlcpy(dst, x, strlen(x))'
11091     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11092       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11093           SizeCall->getNumArgs() == 1)
11094         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
11095     }
11096   }
11097 
11098   if (!CompareWithSrc)
11099     return;
11100 
11101   // Determine if the argument to sizeof/strlen is equal to the source
11102   // argument.  In principle there's all kinds of things you could do
11103   // here, for instance creating an == expression and evaluating it with
11104   // EvaluateAsBooleanCondition, but this uses a more direct technique:
11105   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11106   if (!SrcArgDRE)
11107     return;
11108 
11109   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11110   if (!CompareWithSrcDRE ||
11111       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11112     return;
11113 
11114   const Expr *OriginalSizeArg = Call->getArg(2);
11115   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11116       << OriginalSizeArg->getSourceRange() << FnName;
11117 
11118   // Output a FIXIT hint if the destination is an array (rather than a
11119   // pointer to an array).  This could be enhanced to handle some
11120   // pointers if we know the actual size, like if DstArg is 'array+2'
11121   // we could say 'sizeof(array)-2'.
11122   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
11123   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
11124     return;
11125 
11126   SmallString<128> sizeString;
11127   llvm::raw_svector_ostream OS(sizeString);
11128   OS << "sizeof(";
11129   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11130   OS << ")";
11131 
11132   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
11133       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
11134                                       OS.str());
11135 }
11136 
11137 /// Check if two expressions refer to the same declaration.
11138 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11139   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11140     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11141       return D1->getDecl() == D2->getDecl();
11142   return false;
11143 }
11144 
11145 static const Expr *getStrlenExprArg(const Expr *E) {
11146   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11147     const FunctionDecl *FD = CE->getDirectCallee();
11148     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11149       return nullptr;
11150     return CE->getArg(0)->IgnoreParenCasts();
11151   }
11152   return nullptr;
11153 }
11154 
11155 // Warn on anti-patterns as the 'size' argument to strncat.
11156 // The correct size argument should look like following:
11157 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
11158 void Sema::CheckStrncatArguments(const CallExpr *CE,
11159                                  IdentifierInfo *FnName) {
11160   // Don't crash if the user has the wrong number of arguments.
11161   if (CE->getNumArgs() < 3)
11162     return;
11163   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11164   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11165   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11166 
11167   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11168                                      CE->getRParenLoc()))
11169     return;
11170 
11171   // Identify common expressions, which are wrongly used as the size argument
11172   // to strncat and may lead to buffer overflows.
11173   unsigned PatternType = 0;
11174   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11175     // - sizeof(dst)
11176     if (referToTheSameDecl(SizeOfArg, DstArg))
11177       PatternType = 1;
11178     // - sizeof(src)
11179     else if (referToTheSameDecl(SizeOfArg, SrcArg))
11180       PatternType = 2;
11181   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11182     if (BE->getOpcode() == BO_Sub) {
11183       const Expr *L = BE->getLHS()->IgnoreParenCasts();
11184       const Expr *R = BE->getRHS()->IgnoreParenCasts();
11185       // - sizeof(dst) - strlen(dst)
11186       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11187           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
11188         PatternType = 1;
11189       // - sizeof(src) - (anything)
11190       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11191         PatternType = 2;
11192     }
11193   }
11194 
11195   if (PatternType == 0)
11196     return;
11197 
11198   // Generate the diagnostic.
11199   SourceLocation SL = LenArg->getBeginLoc();
11200   SourceRange SR = LenArg->getSourceRange();
11201   SourceManager &SM = getSourceManager();
11202 
11203   // If the function is defined as a builtin macro, do not show macro expansion.
11204   if (SM.isMacroArgExpansion(SL)) {
11205     SL = SM.getSpellingLoc(SL);
11206     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11207                      SM.getSpellingLoc(SR.getEnd()));
11208   }
11209 
11210   // Check if the destination is an array (rather than a pointer to an array).
11211   QualType DstTy = DstArg->getType();
11212   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11213                                                                     Context);
11214   if (!isKnownSizeArray) {
11215     if (PatternType == 1)
11216       Diag(SL, diag::warn_strncat_wrong_size) << SR;
11217     else
11218       Diag(SL, diag::warn_strncat_src_size) << SR;
11219     return;
11220   }
11221 
11222   if (PatternType == 1)
11223     Diag(SL, diag::warn_strncat_large_size) << SR;
11224   else
11225     Diag(SL, diag::warn_strncat_src_size) << SR;
11226 
11227   SmallString<128> sizeString;
11228   llvm::raw_svector_ostream OS(sizeString);
11229   OS << "sizeof(";
11230   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11231   OS << ") - ";
11232   OS << "strlen(";
11233   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11234   OS << ") - 1";
11235 
11236   Diag(SL, diag::note_strncat_wrong_size)
11237     << FixItHint::CreateReplacement(SR, OS.str());
11238 }
11239 
11240 namespace {
11241 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11242                                 const UnaryOperator *UnaryExpr, const Decl *D) {
11243   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
11244     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11245         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11246     return;
11247   }
11248 }
11249 
11250 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11251                                  const UnaryOperator *UnaryExpr) {
11252   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11253     const Decl *D = Lvalue->getDecl();
11254     if (isa<DeclaratorDecl>(D))
11255       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
11256         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11257   }
11258 
11259   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11260     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11261                                       Lvalue->getMemberDecl());
11262 }
11263 
11264 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11265                             const UnaryOperator *UnaryExpr) {
11266   const auto *Lambda = dyn_cast<LambdaExpr>(
11267       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11268   if (!Lambda)
11269     return;
11270 
11271   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11272       << CalleeName << 2 /*object: lambda expression*/;
11273 }
11274 
11275 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11276                                   const DeclRefExpr *Lvalue) {
11277   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11278   if (Var == nullptr)
11279     return;
11280 
11281   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11282       << CalleeName << 0 /*object: */ << Var;
11283 }
11284 
11285 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11286                             const CastExpr *Cast) {
11287   SmallString<128> SizeString;
11288   llvm::raw_svector_ostream OS(SizeString);
11289 
11290   clang::CastKind Kind = Cast->getCastKind();
11291   if (Kind == clang::CK_BitCast &&
11292       !Cast->getSubExpr()->getType()->isFunctionPointerType())
11293     return;
11294   if (Kind == clang::CK_IntegralToPointer &&
11295       !isa<IntegerLiteral>(
11296           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11297     return;
11298 
11299   switch (Cast->getCastKind()) {
11300   case clang::CK_BitCast:
11301   case clang::CK_IntegralToPointer:
11302   case clang::CK_FunctionToPointerDecay:
11303     OS << '\'';
11304     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11305     OS << '\'';
11306     break;
11307   default:
11308     return;
11309   }
11310 
11311   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11312       << CalleeName << 0 /*object: */ << OS.str();
11313 }
11314 } // namespace
11315 
11316 /// Alerts the user that they are attempting to free a non-malloc'd object.
11317 void Sema::CheckFreeArguments(const CallExpr *E) {
11318   const std::string CalleeName =
11319       cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11320 
11321   { // Prefer something that doesn't involve a cast to make things simpler.
11322     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11323     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11324       switch (UnaryExpr->getOpcode()) {
11325       case UnaryOperator::Opcode::UO_AddrOf:
11326         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11327       case UnaryOperator::Opcode::UO_Plus:
11328         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11329       default:
11330         break;
11331       }
11332 
11333     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11334       if (Lvalue->getType()->isArrayType())
11335         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11336 
11337     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11338       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11339           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11340       return;
11341     }
11342 
11343     if (isa<BlockExpr>(Arg)) {
11344       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11345           << CalleeName << 1 /*object: block*/;
11346       return;
11347     }
11348   }
11349   // Maybe the cast was important, check after the other cases.
11350   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11351     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11352 }
11353 
11354 void
11355 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11356                          SourceLocation ReturnLoc,
11357                          bool isObjCMethod,
11358                          const AttrVec *Attrs,
11359                          const FunctionDecl *FD) {
11360   // Check if the return value is null but should not be.
11361   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11362        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
11363       CheckNonNullExpr(*this, RetValExp))
11364     Diag(ReturnLoc, diag::warn_null_ret)
11365       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11366 
11367   // C++11 [basic.stc.dynamic.allocation]p4:
11368   //   If an allocation function declared with a non-throwing
11369   //   exception-specification fails to allocate storage, it shall return
11370   //   a null pointer. Any other allocation function that fails to allocate
11371   //   storage shall indicate failure only by throwing an exception [...]
11372   if (FD) {
11373     OverloadedOperatorKind Op = FD->getOverloadedOperator();
11374     if (Op == OO_New || Op == OO_Array_New) {
11375       const FunctionProtoType *Proto
11376         = FD->getType()->castAs<FunctionProtoType>();
11377       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11378           CheckNonNullExpr(*this, RetValExp))
11379         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11380           << FD << getLangOpts().CPlusPlus11;
11381     }
11382   }
11383 
11384   // PPC MMA non-pointer types are not allowed as return type. Checking the type
11385   // here prevent the user from using a PPC MMA type as trailing return type.
11386   if (Context.getTargetInfo().getTriple().isPPC64())
11387     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11388 }
11389 
11390 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
11391 
11392 /// Check for comparisons of floating point operands using != and ==.
11393 /// Issue a warning if these are no self-comparisons, as they are not likely
11394 /// to do what the programmer intended.
11395 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
11396   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
11397   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
11398 
11399   // Special case: check for x == x (which is OK).
11400   // Do not emit warnings for such cases.
11401   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11402     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11403       if (DRL->getDecl() == DRR->getDecl())
11404         return;
11405 
11406   // Special case: check for comparisons against literals that can be exactly
11407   //  represented by APFloat.  In such cases, do not emit a warning.  This
11408   //  is a heuristic: often comparison against such literals are used to
11409   //  detect if a value in a variable has not changed.  This clearly can
11410   //  lead to false negatives.
11411   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11412     if (FLL->isExact())
11413       return;
11414   } else
11415     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11416       if (FLR->isExact())
11417         return;
11418 
11419   // Check for comparisons with builtin types.
11420   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11421     if (CL->getBuiltinCallee())
11422       return;
11423 
11424   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11425     if (CR->getBuiltinCallee())
11426       return;
11427 
11428   // Emit the diagnostic.
11429   Diag(Loc, diag::warn_floatingpoint_eq)
11430     << LHS->getSourceRange() << RHS->getSourceRange();
11431 }
11432 
11433 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11434 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11435 
11436 namespace {
11437 
11438 /// Structure recording the 'active' range of an integer-valued
11439 /// expression.
11440 struct IntRange {
11441   /// The number of bits active in the int. Note that this includes exactly one
11442   /// sign bit if !NonNegative.
11443   unsigned Width;
11444 
11445   /// True if the int is known not to have negative values. If so, all leading
11446   /// bits before Width are known zero, otherwise they are known to be the
11447   /// same as the MSB within Width.
11448   bool NonNegative;
11449 
11450   IntRange(unsigned Width, bool NonNegative)
11451       : Width(Width), NonNegative(NonNegative) {}
11452 
11453   /// Number of bits excluding the sign bit.
11454   unsigned valueBits() const {
11455     return NonNegative ? Width : Width - 1;
11456   }
11457 
11458   /// Returns the range of the bool type.
11459   static IntRange forBoolType() {
11460     return IntRange(1, true);
11461   }
11462 
11463   /// Returns the range of an opaque value of the given integral type.
11464   static IntRange forValueOfType(ASTContext &C, QualType T) {
11465     return forValueOfCanonicalType(C,
11466                           T->getCanonicalTypeInternal().getTypePtr());
11467   }
11468 
11469   /// Returns the range of an opaque value of a canonical integral type.
11470   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11471     assert(T->isCanonicalUnqualified());
11472 
11473     if (const VectorType *VT = dyn_cast<VectorType>(T))
11474       T = VT->getElementType().getTypePtr();
11475     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11476       T = CT->getElementType().getTypePtr();
11477     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11478       T = AT->getValueType().getTypePtr();
11479 
11480     if (!C.getLangOpts().CPlusPlus) {
11481       // For enum types in C code, use the underlying datatype.
11482       if (const EnumType *ET = dyn_cast<EnumType>(T))
11483         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11484     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11485       // For enum types in C++, use the known bit width of the enumerators.
11486       EnumDecl *Enum = ET->getDecl();
11487       // In C++11, enums can have a fixed underlying type. Use this type to
11488       // compute the range.
11489       if (Enum->isFixed()) {
11490         return IntRange(C.getIntWidth(QualType(T, 0)),
11491                         !ET->isSignedIntegerOrEnumerationType());
11492       }
11493 
11494       unsigned NumPositive = Enum->getNumPositiveBits();
11495       unsigned NumNegative = Enum->getNumNegativeBits();
11496 
11497       if (NumNegative == 0)
11498         return IntRange(NumPositive, true/*NonNegative*/);
11499       else
11500         return IntRange(std::max(NumPositive + 1, NumNegative),
11501                         false/*NonNegative*/);
11502     }
11503 
11504     if (const auto *EIT = dyn_cast<BitIntType>(T))
11505       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11506 
11507     const BuiltinType *BT = cast<BuiltinType>(T);
11508     assert(BT->isInteger());
11509 
11510     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11511   }
11512 
11513   /// Returns the "target" range of a canonical integral type, i.e.
11514   /// the range of values expressible in the type.
11515   ///
11516   /// This matches forValueOfCanonicalType except that enums have the
11517   /// full range of their type, not the range of their enumerators.
11518   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11519     assert(T->isCanonicalUnqualified());
11520 
11521     if (const VectorType *VT = dyn_cast<VectorType>(T))
11522       T = VT->getElementType().getTypePtr();
11523     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11524       T = CT->getElementType().getTypePtr();
11525     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11526       T = AT->getValueType().getTypePtr();
11527     if (const EnumType *ET = dyn_cast<EnumType>(T))
11528       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11529 
11530     if (const auto *EIT = dyn_cast<BitIntType>(T))
11531       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11532 
11533     const BuiltinType *BT = cast<BuiltinType>(T);
11534     assert(BT->isInteger());
11535 
11536     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11537   }
11538 
11539   /// Returns the supremum of two ranges: i.e. their conservative merge.
11540   static IntRange join(IntRange L, IntRange R) {
11541     bool Unsigned = L.NonNegative && R.NonNegative;
11542     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11543                     L.NonNegative && R.NonNegative);
11544   }
11545 
11546   /// Return the range of a bitwise-AND of the two ranges.
11547   static IntRange bit_and(IntRange L, IntRange R) {
11548     unsigned Bits = std::max(L.Width, R.Width);
11549     bool NonNegative = false;
11550     if (L.NonNegative) {
11551       Bits = std::min(Bits, L.Width);
11552       NonNegative = true;
11553     }
11554     if (R.NonNegative) {
11555       Bits = std::min(Bits, R.Width);
11556       NonNegative = true;
11557     }
11558     return IntRange(Bits, NonNegative);
11559   }
11560 
11561   /// Return the range of a sum of the two ranges.
11562   static IntRange sum(IntRange L, IntRange R) {
11563     bool Unsigned = L.NonNegative && R.NonNegative;
11564     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11565                     Unsigned);
11566   }
11567 
11568   /// Return the range of a difference of the two ranges.
11569   static IntRange difference(IntRange L, IntRange R) {
11570     // We need a 1-bit-wider range if:
11571     //   1) LHS can be negative: least value can be reduced.
11572     //   2) RHS can be negative: greatest value can be increased.
11573     bool CanWiden = !L.NonNegative || !R.NonNegative;
11574     bool Unsigned = L.NonNegative && R.Width == 0;
11575     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11576                         !Unsigned,
11577                     Unsigned);
11578   }
11579 
11580   /// Return the range of a product of the two ranges.
11581   static IntRange product(IntRange L, IntRange R) {
11582     // If both LHS and RHS can be negative, we can form
11583     //   -2^L * -2^R = 2^(L + R)
11584     // which requires L + R + 1 value bits to represent.
11585     bool CanWiden = !L.NonNegative && !R.NonNegative;
11586     bool Unsigned = L.NonNegative && R.NonNegative;
11587     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11588                     Unsigned);
11589   }
11590 
11591   /// Return the range of a remainder operation between the two ranges.
11592   static IntRange rem(IntRange L, IntRange R) {
11593     // The result of a remainder can't be larger than the result of
11594     // either side. The sign of the result is the sign of the LHS.
11595     bool Unsigned = L.NonNegative;
11596     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11597                     Unsigned);
11598   }
11599 };
11600 
11601 } // namespace
11602 
11603 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11604                               unsigned MaxWidth) {
11605   if (value.isSigned() && value.isNegative())
11606     return IntRange(value.getMinSignedBits(), false);
11607 
11608   if (value.getBitWidth() > MaxWidth)
11609     value = value.trunc(MaxWidth);
11610 
11611   // isNonNegative() just checks the sign bit without considering
11612   // signedness.
11613   return IntRange(value.getActiveBits(), true);
11614 }
11615 
11616 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11617                               unsigned MaxWidth) {
11618   if (result.isInt())
11619     return GetValueRange(C, result.getInt(), MaxWidth);
11620 
11621   if (result.isVector()) {
11622     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11623     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11624       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11625       R = IntRange::join(R, El);
11626     }
11627     return R;
11628   }
11629 
11630   if (result.isComplexInt()) {
11631     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11632     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11633     return IntRange::join(R, I);
11634   }
11635 
11636   // This can happen with lossless casts to intptr_t of "based" lvalues.
11637   // Assume it might use arbitrary bits.
11638   // FIXME: The only reason we need to pass the type in here is to get
11639   // the sign right on this one case.  It would be nice if APValue
11640   // preserved this.
11641   assert(result.isLValue() || result.isAddrLabelDiff());
11642   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11643 }
11644 
11645 static QualType GetExprType(const Expr *E) {
11646   QualType Ty = E->getType();
11647   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11648     Ty = AtomicRHS->getValueType();
11649   return Ty;
11650 }
11651 
11652 /// Pseudo-evaluate the given integer expression, estimating the
11653 /// range of values it might take.
11654 ///
11655 /// \param MaxWidth The width to which the value will be truncated.
11656 /// \param Approximate If \c true, return a likely range for the result: in
11657 ///        particular, assume that arithmetic on narrower types doesn't leave
11658 ///        those types. If \c false, return a range including all possible
11659 ///        result values.
11660 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11661                              bool InConstantContext, bool Approximate) {
11662   E = E->IgnoreParens();
11663 
11664   // Try a full evaluation first.
11665   Expr::EvalResult result;
11666   if (E->EvaluateAsRValue(result, C, InConstantContext))
11667     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11668 
11669   // I think we only want to look through implicit casts here; if the
11670   // user has an explicit widening cast, we should treat the value as
11671   // being of the new, wider type.
11672   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11673     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11674       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11675                           Approximate);
11676 
11677     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11678 
11679     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11680                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11681 
11682     // Assume that non-integer casts can span the full range of the type.
11683     if (!isIntegerCast)
11684       return OutputTypeRange;
11685 
11686     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11687                                      std::min(MaxWidth, OutputTypeRange.Width),
11688                                      InConstantContext, Approximate);
11689 
11690     // Bail out if the subexpr's range is as wide as the cast type.
11691     if (SubRange.Width >= OutputTypeRange.Width)
11692       return OutputTypeRange;
11693 
11694     // Otherwise, we take the smaller width, and we're non-negative if
11695     // either the output type or the subexpr is.
11696     return IntRange(SubRange.Width,
11697                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11698   }
11699 
11700   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11701     // If we can fold the condition, just take that operand.
11702     bool CondResult;
11703     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11704       return GetExprRange(C,
11705                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11706                           MaxWidth, InConstantContext, Approximate);
11707 
11708     // Otherwise, conservatively merge.
11709     // GetExprRange requires an integer expression, but a throw expression
11710     // results in a void type.
11711     Expr *E = CO->getTrueExpr();
11712     IntRange L = E->getType()->isVoidType()
11713                      ? IntRange{0, true}
11714                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11715     E = CO->getFalseExpr();
11716     IntRange R = E->getType()->isVoidType()
11717                      ? IntRange{0, true}
11718                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11719     return IntRange::join(L, R);
11720   }
11721 
11722   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11723     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11724 
11725     switch (BO->getOpcode()) {
11726     case BO_Cmp:
11727       llvm_unreachable("builtin <=> should have class type");
11728 
11729     // Boolean-valued operations are single-bit and positive.
11730     case BO_LAnd:
11731     case BO_LOr:
11732     case BO_LT:
11733     case BO_GT:
11734     case BO_LE:
11735     case BO_GE:
11736     case BO_EQ:
11737     case BO_NE:
11738       return IntRange::forBoolType();
11739 
11740     // The type of the assignments is the type of the LHS, so the RHS
11741     // is not necessarily the same type.
11742     case BO_MulAssign:
11743     case BO_DivAssign:
11744     case BO_RemAssign:
11745     case BO_AddAssign:
11746     case BO_SubAssign:
11747     case BO_XorAssign:
11748     case BO_OrAssign:
11749       // TODO: bitfields?
11750       return IntRange::forValueOfType(C, GetExprType(E));
11751 
11752     // Simple assignments just pass through the RHS, which will have
11753     // been coerced to the LHS type.
11754     case BO_Assign:
11755       // TODO: bitfields?
11756       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11757                           Approximate);
11758 
11759     // Operations with opaque sources are black-listed.
11760     case BO_PtrMemD:
11761     case BO_PtrMemI:
11762       return IntRange::forValueOfType(C, GetExprType(E));
11763 
11764     // Bitwise-and uses the *infinum* of the two source ranges.
11765     case BO_And:
11766     case BO_AndAssign:
11767       Combine = IntRange::bit_and;
11768       break;
11769 
11770     // Left shift gets black-listed based on a judgement call.
11771     case BO_Shl:
11772       // ...except that we want to treat '1 << (blah)' as logically
11773       // positive.  It's an important idiom.
11774       if (IntegerLiteral *I
11775             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11776         if (I->getValue() == 1) {
11777           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11778           return IntRange(R.Width, /*NonNegative*/ true);
11779         }
11780       }
11781       LLVM_FALLTHROUGH;
11782 
11783     case BO_ShlAssign:
11784       return IntRange::forValueOfType(C, GetExprType(E));
11785 
11786     // Right shift by a constant can narrow its left argument.
11787     case BO_Shr:
11788     case BO_ShrAssign: {
11789       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11790                                 Approximate);
11791 
11792       // If the shift amount is a positive constant, drop the width by
11793       // that much.
11794       if (Optional<llvm::APSInt> shift =
11795               BO->getRHS()->getIntegerConstantExpr(C)) {
11796         if (shift->isNonNegative()) {
11797           unsigned zext = shift->getZExtValue();
11798           if (zext >= L.Width)
11799             L.Width = (L.NonNegative ? 0 : 1);
11800           else
11801             L.Width -= zext;
11802         }
11803       }
11804 
11805       return L;
11806     }
11807 
11808     // Comma acts as its right operand.
11809     case BO_Comma:
11810       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11811                           Approximate);
11812 
11813     case BO_Add:
11814       if (!Approximate)
11815         Combine = IntRange::sum;
11816       break;
11817 
11818     case BO_Sub:
11819       if (BO->getLHS()->getType()->isPointerType())
11820         return IntRange::forValueOfType(C, GetExprType(E));
11821       if (!Approximate)
11822         Combine = IntRange::difference;
11823       break;
11824 
11825     case BO_Mul:
11826       if (!Approximate)
11827         Combine = IntRange::product;
11828       break;
11829 
11830     // The width of a division result is mostly determined by the size
11831     // of the LHS.
11832     case BO_Div: {
11833       // Don't 'pre-truncate' the operands.
11834       unsigned opWidth = C.getIntWidth(GetExprType(E));
11835       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11836                                 Approximate);
11837 
11838       // If the divisor is constant, use that.
11839       if (Optional<llvm::APSInt> divisor =
11840               BO->getRHS()->getIntegerConstantExpr(C)) {
11841         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11842         if (log2 >= L.Width)
11843           L.Width = (L.NonNegative ? 0 : 1);
11844         else
11845           L.Width = std::min(L.Width - log2, MaxWidth);
11846         return L;
11847       }
11848 
11849       // Otherwise, just use the LHS's width.
11850       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11851       // could be -1.
11852       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11853                                 Approximate);
11854       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11855     }
11856 
11857     case BO_Rem:
11858       Combine = IntRange::rem;
11859       break;
11860 
11861     // The default behavior is okay for these.
11862     case BO_Xor:
11863     case BO_Or:
11864       break;
11865     }
11866 
11867     // Combine the two ranges, but limit the result to the type in which we
11868     // performed the computation.
11869     QualType T = GetExprType(E);
11870     unsigned opWidth = C.getIntWidth(T);
11871     IntRange L =
11872         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11873     IntRange R =
11874         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11875     IntRange C = Combine(L, R);
11876     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11877     C.Width = std::min(C.Width, MaxWidth);
11878     return C;
11879   }
11880 
11881   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11882     switch (UO->getOpcode()) {
11883     // Boolean-valued operations are white-listed.
11884     case UO_LNot:
11885       return IntRange::forBoolType();
11886 
11887     // Operations with opaque sources are black-listed.
11888     case UO_Deref:
11889     case UO_AddrOf: // should be impossible
11890       return IntRange::forValueOfType(C, GetExprType(E));
11891 
11892     default:
11893       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11894                           Approximate);
11895     }
11896   }
11897 
11898   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11899     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11900                         Approximate);
11901 
11902   if (const auto *BitField = E->getSourceBitField())
11903     return IntRange(BitField->getBitWidthValue(C),
11904                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11905 
11906   return IntRange::forValueOfType(C, GetExprType(E));
11907 }
11908 
11909 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11910                              bool InConstantContext, bool Approximate) {
11911   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11912                       Approximate);
11913 }
11914 
11915 /// Checks whether the given value, which currently has the given
11916 /// source semantics, has the same value when coerced through the
11917 /// target semantics.
11918 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11919                                  const llvm::fltSemantics &Src,
11920                                  const llvm::fltSemantics &Tgt) {
11921   llvm::APFloat truncated = value;
11922 
11923   bool ignored;
11924   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11925   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11926 
11927   return truncated.bitwiseIsEqual(value);
11928 }
11929 
11930 /// Checks whether the given value, which currently has the given
11931 /// source semantics, has the same value when coerced through the
11932 /// target semantics.
11933 ///
11934 /// The value might be a vector of floats (or a complex number).
11935 static bool IsSameFloatAfterCast(const APValue &value,
11936                                  const llvm::fltSemantics &Src,
11937                                  const llvm::fltSemantics &Tgt) {
11938   if (value.isFloat())
11939     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11940 
11941   if (value.isVector()) {
11942     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11943       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11944         return false;
11945     return true;
11946   }
11947 
11948   assert(value.isComplexFloat());
11949   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11950           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11951 }
11952 
11953 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11954                                        bool IsListInit = false);
11955 
11956 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11957   // Suppress cases where we are comparing against an enum constant.
11958   if (const DeclRefExpr *DR =
11959       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11960     if (isa<EnumConstantDecl>(DR->getDecl()))
11961       return true;
11962 
11963   // Suppress cases where the value is expanded from a macro, unless that macro
11964   // is how a language represents a boolean literal. This is the case in both C
11965   // and Objective-C.
11966   SourceLocation BeginLoc = E->getBeginLoc();
11967   if (BeginLoc.isMacroID()) {
11968     StringRef MacroName = Lexer::getImmediateMacroName(
11969         BeginLoc, S.getSourceManager(), S.getLangOpts());
11970     return MacroName != "YES" && MacroName != "NO" &&
11971            MacroName != "true" && MacroName != "false";
11972   }
11973 
11974   return false;
11975 }
11976 
11977 static bool isKnownToHaveUnsignedValue(Expr *E) {
11978   return E->getType()->isIntegerType() &&
11979          (!E->getType()->isSignedIntegerType() ||
11980           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11981 }
11982 
11983 namespace {
11984 /// The promoted range of values of a type. In general this has the
11985 /// following structure:
11986 ///
11987 ///     |-----------| . . . |-----------|
11988 ///     ^           ^       ^           ^
11989 ///    Min       HoleMin  HoleMax      Max
11990 ///
11991 /// ... where there is only a hole if a signed type is promoted to unsigned
11992 /// (in which case Min and Max are the smallest and largest representable
11993 /// values).
11994 struct PromotedRange {
11995   // Min, or HoleMax if there is a hole.
11996   llvm::APSInt PromotedMin;
11997   // Max, or HoleMin if there is a hole.
11998   llvm::APSInt PromotedMax;
11999 
12000   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12001     if (R.Width == 0)
12002       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12003     else if (R.Width >= BitWidth && !Unsigned) {
12004       // Promotion made the type *narrower*. This happens when promoting
12005       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12006       // Treat all values of 'signed int' as being in range for now.
12007       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
12008       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
12009     } else {
12010       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
12011                         .extOrTrunc(BitWidth);
12012       PromotedMin.setIsUnsigned(Unsigned);
12013 
12014       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
12015                         .extOrTrunc(BitWidth);
12016       PromotedMax.setIsUnsigned(Unsigned);
12017     }
12018   }
12019 
12020   // Determine whether this range is contiguous (has no hole).
12021   bool isContiguous() const { return PromotedMin <= PromotedMax; }
12022 
12023   // Where a constant value is within the range.
12024   enum ComparisonResult {
12025     LT = 0x1,
12026     LE = 0x2,
12027     GT = 0x4,
12028     GE = 0x8,
12029     EQ = 0x10,
12030     NE = 0x20,
12031     InRangeFlag = 0x40,
12032 
12033     Less = LE | LT | NE,
12034     Min = LE | InRangeFlag,
12035     InRange = InRangeFlag,
12036     Max = GE | InRangeFlag,
12037     Greater = GE | GT | NE,
12038 
12039     OnlyValue = LE | GE | EQ | InRangeFlag,
12040     InHole = NE
12041   };
12042 
12043   ComparisonResult compare(const llvm::APSInt &Value) const {
12044     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12045            Value.isUnsigned() == PromotedMin.isUnsigned());
12046     if (!isContiguous()) {
12047       assert(Value.isUnsigned() && "discontiguous range for signed compare");
12048       if (Value.isMinValue()) return Min;
12049       if (Value.isMaxValue()) return Max;
12050       if (Value >= PromotedMin) return InRange;
12051       if (Value <= PromotedMax) return InRange;
12052       return InHole;
12053     }
12054 
12055     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
12056     case -1: return Less;
12057     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12058     case 1:
12059       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
12060       case -1: return InRange;
12061       case 0: return Max;
12062       case 1: return Greater;
12063       }
12064     }
12065 
12066     llvm_unreachable("impossible compare result");
12067   }
12068 
12069   static llvm::Optional<StringRef>
12070   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12071     if (Op == BO_Cmp) {
12072       ComparisonResult LTFlag = LT, GTFlag = GT;
12073       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
12074 
12075       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12076       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12077       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12078       return llvm::None;
12079     }
12080 
12081     ComparisonResult TrueFlag, FalseFlag;
12082     if (Op == BO_EQ) {
12083       TrueFlag = EQ;
12084       FalseFlag = NE;
12085     } else if (Op == BO_NE) {
12086       TrueFlag = NE;
12087       FalseFlag = EQ;
12088     } else {
12089       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12090         TrueFlag = LT;
12091         FalseFlag = GE;
12092       } else {
12093         TrueFlag = GT;
12094         FalseFlag = LE;
12095       }
12096       if (Op == BO_GE || Op == BO_LE)
12097         std::swap(TrueFlag, FalseFlag);
12098     }
12099     if (R & TrueFlag)
12100       return StringRef("true");
12101     if (R & FalseFlag)
12102       return StringRef("false");
12103     return llvm::None;
12104   }
12105 };
12106 }
12107 
12108 static bool HasEnumType(Expr *E) {
12109   // Strip off implicit integral promotions.
12110   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12111     if (ICE->getCastKind() != CK_IntegralCast &&
12112         ICE->getCastKind() != CK_NoOp)
12113       break;
12114     E = ICE->getSubExpr();
12115   }
12116 
12117   return E->getType()->isEnumeralType();
12118 }
12119 
12120 static int classifyConstantValue(Expr *Constant) {
12121   // The values of this enumeration are used in the diagnostics
12122   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12123   enum ConstantValueKind {
12124     Miscellaneous = 0,
12125     LiteralTrue,
12126     LiteralFalse
12127   };
12128   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12129     return BL->getValue() ? ConstantValueKind::LiteralTrue
12130                           : ConstantValueKind::LiteralFalse;
12131   return ConstantValueKind::Miscellaneous;
12132 }
12133 
12134 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
12135                                         Expr *Constant, Expr *Other,
12136                                         const llvm::APSInt &Value,
12137                                         bool RhsConstant) {
12138   if (S.inTemplateInstantiation())
12139     return false;
12140 
12141   Expr *OriginalOther = Other;
12142 
12143   Constant = Constant->IgnoreParenImpCasts();
12144   Other = Other->IgnoreParenImpCasts();
12145 
12146   // Suppress warnings on tautological comparisons between values of the same
12147   // enumeration type. There are only two ways we could warn on this:
12148   //  - If the constant is outside the range of representable values of
12149   //    the enumeration. In such a case, we should warn about the cast
12150   //    to enumeration type, not about the comparison.
12151   //  - If the constant is the maximum / minimum in-range value. For an
12152   //    enumeratin type, such comparisons can be meaningful and useful.
12153   if (Constant->getType()->isEnumeralType() &&
12154       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12155     return false;
12156 
12157   IntRange OtherValueRange = GetExprRange(
12158       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
12159 
12160   QualType OtherT = Other->getType();
12161   if (const auto *AT = OtherT->getAs<AtomicType>())
12162     OtherT = AT->getValueType();
12163   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12164 
12165   // Special case for ObjC BOOL on targets where its a typedef for a signed char
12166   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12167   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12168                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
12169                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12170 
12171   // Whether we're treating Other as being a bool because of the form of
12172   // expression despite it having another type (typically 'int' in C).
12173   bool OtherIsBooleanDespiteType =
12174       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12175   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12176     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
12177 
12178   // Check if all values in the range of possible values of this expression
12179   // lead to the same comparison outcome.
12180   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
12181                                         Value.isUnsigned());
12182   auto Cmp = OtherPromotedValueRange.compare(Value);
12183   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12184   if (!Result)
12185     return false;
12186 
12187   // Also consider the range determined by the type alone. This allows us to
12188   // classify the warning under the proper diagnostic group.
12189   bool TautologicalTypeCompare = false;
12190   {
12191     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12192                                          Value.isUnsigned());
12193     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12194     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12195                                                        RhsConstant)) {
12196       TautologicalTypeCompare = true;
12197       Cmp = TypeCmp;
12198       Result = TypeResult;
12199     }
12200   }
12201 
12202   // Don't warn if the non-constant operand actually always evaluates to the
12203   // same value.
12204   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
12205     return false;
12206 
12207   // Suppress the diagnostic for an in-range comparison if the constant comes
12208   // from a macro or enumerator. We don't want to diagnose
12209   //
12210   //   some_long_value <= INT_MAX
12211   //
12212   // when sizeof(int) == sizeof(long).
12213   bool InRange = Cmp & PromotedRange::InRangeFlag;
12214   if (InRange && IsEnumConstOrFromMacro(S, Constant))
12215     return false;
12216 
12217   // A comparison of an unsigned bit-field against 0 is really a type problem,
12218   // even though at the type level the bit-field might promote to 'signed int'.
12219   if (Other->refersToBitField() && InRange && Value == 0 &&
12220       Other->getType()->isUnsignedIntegerOrEnumerationType())
12221     TautologicalTypeCompare = true;
12222 
12223   // If this is a comparison to an enum constant, include that
12224   // constant in the diagnostic.
12225   const EnumConstantDecl *ED = nullptr;
12226   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
12227     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12228 
12229   // Should be enough for uint128 (39 decimal digits)
12230   SmallString<64> PrettySourceValue;
12231   llvm::raw_svector_ostream OS(PrettySourceValue);
12232   if (ED) {
12233     OS << '\'' << *ED << "' (" << Value << ")";
12234   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12235                Constant->IgnoreParenImpCasts())) {
12236     OS << (BL->getValue() ? "YES" : "NO");
12237   } else {
12238     OS << Value;
12239   }
12240 
12241   if (!TautologicalTypeCompare) {
12242     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12243         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
12244         << E->getOpcodeStr() << OS.str() << *Result
12245         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12246     return true;
12247   }
12248 
12249   if (IsObjCSignedCharBool) {
12250     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12251                           S.PDiag(diag::warn_tautological_compare_objc_bool)
12252                               << OS.str() << *Result);
12253     return true;
12254   }
12255 
12256   // FIXME: We use a somewhat different formatting for the in-range cases and
12257   // cases involving boolean values for historical reasons. We should pick a
12258   // consistent way of presenting these diagnostics.
12259   if (!InRange || Other->isKnownToHaveBooleanValue()) {
12260 
12261     S.DiagRuntimeBehavior(
12262         E->getOperatorLoc(), E,
12263         S.PDiag(!InRange ? diag::warn_out_of_range_compare
12264                          : diag::warn_tautological_bool_compare)
12265             << OS.str() << classifyConstantValue(Constant) << OtherT
12266             << OtherIsBooleanDespiteType << *Result
12267             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12268   } else {
12269     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12270     unsigned Diag =
12271         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12272             ? (HasEnumType(OriginalOther)
12273                    ? diag::warn_unsigned_enum_always_true_comparison
12274                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12275                               : diag::warn_unsigned_always_true_comparison)
12276             : diag::warn_tautological_constant_compare;
12277 
12278     S.Diag(E->getOperatorLoc(), Diag)
12279         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12280         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12281   }
12282 
12283   return true;
12284 }
12285 
12286 /// Analyze the operands of the given comparison.  Implements the
12287 /// fallback case from AnalyzeComparison.
12288 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12289   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12290   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12291 }
12292 
12293 /// Implements -Wsign-compare.
12294 ///
12295 /// \param E the binary operator to check for warnings
12296 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12297   // The type the comparison is being performed in.
12298   QualType T = E->getLHS()->getType();
12299 
12300   // Only analyze comparison operators where both sides have been converted to
12301   // the same type.
12302   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12303     return AnalyzeImpConvsInComparison(S, E);
12304 
12305   // Don't analyze value-dependent comparisons directly.
12306   if (E->isValueDependent())
12307     return AnalyzeImpConvsInComparison(S, E);
12308 
12309   Expr *LHS = E->getLHS();
12310   Expr *RHS = E->getRHS();
12311 
12312   if (T->isIntegralType(S.Context)) {
12313     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
12314     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
12315 
12316     // We don't care about expressions whose result is a constant.
12317     if (RHSValue && LHSValue)
12318       return AnalyzeImpConvsInComparison(S, E);
12319 
12320     // We only care about expressions where just one side is literal
12321     if ((bool)RHSValue ^ (bool)LHSValue) {
12322       // Is the constant on the RHS or LHS?
12323       const bool RhsConstant = (bool)RHSValue;
12324       Expr *Const = RhsConstant ? RHS : LHS;
12325       Expr *Other = RhsConstant ? LHS : RHS;
12326       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12327 
12328       // Check whether an integer constant comparison results in a value
12329       // of 'true' or 'false'.
12330       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12331         return AnalyzeImpConvsInComparison(S, E);
12332     }
12333   }
12334 
12335   if (!T->hasUnsignedIntegerRepresentation()) {
12336     // We don't do anything special if this isn't an unsigned integral
12337     // comparison:  we're only interested in integral comparisons, and
12338     // signed comparisons only happen in cases we don't care to warn about.
12339     return AnalyzeImpConvsInComparison(S, E);
12340   }
12341 
12342   LHS = LHS->IgnoreParenImpCasts();
12343   RHS = RHS->IgnoreParenImpCasts();
12344 
12345   if (!S.getLangOpts().CPlusPlus) {
12346     // Avoid warning about comparison of integers with different signs when
12347     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12348     // the type of `E`.
12349     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12350       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12351     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12352       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12353   }
12354 
12355   // Check to see if one of the (unmodified) operands is of different
12356   // signedness.
12357   Expr *signedOperand, *unsignedOperand;
12358   if (LHS->getType()->hasSignedIntegerRepresentation()) {
12359     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12360            "unsigned comparison between two signed integer expressions?");
12361     signedOperand = LHS;
12362     unsignedOperand = RHS;
12363   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12364     signedOperand = RHS;
12365     unsignedOperand = LHS;
12366   } else {
12367     return AnalyzeImpConvsInComparison(S, E);
12368   }
12369 
12370   // Otherwise, calculate the effective range of the signed operand.
12371   IntRange signedRange = GetExprRange(
12372       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
12373 
12374   // Go ahead and analyze implicit conversions in the operands.  Note
12375   // that we skip the implicit conversions on both sides.
12376   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
12377   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
12378 
12379   // If the signed range is non-negative, -Wsign-compare won't fire.
12380   if (signedRange.NonNegative)
12381     return;
12382 
12383   // For (in)equality comparisons, if the unsigned operand is a
12384   // constant which cannot collide with a overflowed signed operand,
12385   // then reinterpreting the signed operand as unsigned will not
12386   // change the result of the comparison.
12387   if (E->isEqualityOp()) {
12388     unsigned comparisonWidth = S.Context.getIntWidth(T);
12389     IntRange unsignedRange =
12390         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
12391                      /*Approximate*/ true);
12392 
12393     // We should never be unable to prove that the unsigned operand is
12394     // non-negative.
12395     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
12396 
12397     if (unsignedRange.Width < comparisonWidth)
12398       return;
12399   }
12400 
12401   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12402                         S.PDiag(diag::warn_mixed_sign_comparison)
12403                             << LHS->getType() << RHS->getType()
12404                             << LHS->getSourceRange() << RHS->getSourceRange());
12405 }
12406 
12407 /// Analyzes an attempt to assign the given value to a bitfield.
12408 ///
12409 /// Returns true if there was something fishy about the attempt.
12410 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12411                                       SourceLocation InitLoc) {
12412   assert(Bitfield->isBitField());
12413   if (Bitfield->isInvalidDecl())
12414     return false;
12415 
12416   // White-list bool bitfields.
12417   QualType BitfieldType = Bitfield->getType();
12418   if (BitfieldType->isBooleanType())
12419      return false;
12420 
12421   if (BitfieldType->isEnumeralType()) {
12422     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12423     // If the underlying enum type was not explicitly specified as an unsigned
12424     // type and the enum contain only positive values, MSVC++ will cause an
12425     // inconsistency by storing this as a signed type.
12426     if (S.getLangOpts().CPlusPlus11 &&
12427         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12428         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12429         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12430       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12431           << BitfieldEnumDecl;
12432     }
12433   }
12434 
12435   if (Bitfield->getType()->isBooleanType())
12436     return false;
12437 
12438   // Ignore value- or type-dependent expressions.
12439   if (Bitfield->getBitWidth()->isValueDependent() ||
12440       Bitfield->getBitWidth()->isTypeDependent() ||
12441       Init->isValueDependent() ||
12442       Init->isTypeDependent())
12443     return false;
12444 
12445   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12446   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12447 
12448   Expr::EvalResult Result;
12449   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12450                                    Expr::SE_AllowSideEffects)) {
12451     // The RHS is not constant.  If the RHS has an enum type, make sure the
12452     // bitfield is wide enough to hold all the values of the enum without
12453     // truncation.
12454     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12455       EnumDecl *ED = EnumTy->getDecl();
12456       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12457 
12458       // Enum types are implicitly signed on Windows, so check if there are any
12459       // negative enumerators to see if the enum was intended to be signed or
12460       // not.
12461       bool SignedEnum = ED->getNumNegativeBits() > 0;
12462 
12463       // Check for surprising sign changes when assigning enum values to a
12464       // bitfield of different signedness.  If the bitfield is signed and we
12465       // have exactly the right number of bits to store this unsigned enum,
12466       // suggest changing the enum to an unsigned type. This typically happens
12467       // on Windows where unfixed enums always use an underlying type of 'int'.
12468       unsigned DiagID = 0;
12469       if (SignedEnum && !SignedBitfield) {
12470         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12471       } else if (SignedBitfield && !SignedEnum &&
12472                  ED->getNumPositiveBits() == FieldWidth) {
12473         DiagID = diag::warn_signed_bitfield_enum_conversion;
12474       }
12475 
12476       if (DiagID) {
12477         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12478         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12479         SourceRange TypeRange =
12480             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12481         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12482             << SignedEnum << TypeRange;
12483       }
12484 
12485       // Compute the required bitwidth. If the enum has negative values, we need
12486       // one more bit than the normal number of positive bits to represent the
12487       // sign bit.
12488       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12489                                                   ED->getNumNegativeBits())
12490                                        : ED->getNumPositiveBits();
12491 
12492       // Check the bitwidth.
12493       if (BitsNeeded > FieldWidth) {
12494         Expr *WidthExpr = Bitfield->getBitWidth();
12495         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12496             << Bitfield << ED;
12497         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12498             << BitsNeeded << ED << WidthExpr->getSourceRange();
12499       }
12500     }
12501 
12502     return false;
12503   }
12504 
12505   llvm::APSInt Value = Result.Val.getInt();
12506 
12507   unsigned OriginalWidth = Value.getBitWidth();
12508 
12509   if (!Value.isSigned() || Value.isNegative())
12510     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12511       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12512         OriginalWidth = Value.getMinSignedBits();
12513 
12514   if (OriginalWidth <= FieldWidth)
12515     return false;
12516 
12517   // Compute the value which the bitfield will contain.
12518   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12519   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12520 
12521   // Check whether the stored value is equal to the original value.
12522   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12523   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12524     return false;
12525 
12526   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12527   // therefore don't strictly fit into a signed bitfield of width 1.
12528   if (FieldWidth == 1 && Value == 1)
12529     return false;
12530 
12531   std::string PrettyValue = toString(Value, 10);
12532   std::string PrettyTrunc = toString(TruncatedValue, 10);
12533 
12534   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12535     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12536     << Init->getSourceRange();
12537 
12538   return true;
12539 }
12540 
12541 /// Analyze the given simple or compound assignment for warning-worthy
12542 /// operations.
12543 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12544   // Just recurse on the LHS.
12545   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12546 
12547   // We want to recurse on the RHS as normal unless we're assigning to
12548   // a bitfield.
12549   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12550     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12551                                   E->getOperatorLoc())) {
12552       // Recurse, ignoring any implicit conversions on the RHS.
12553       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12554                                         E->getOperatorLoc());
12555     }
12556   }
12557 
12558   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12559 
12560   // Diagnose implicitly sequentially-consistent atomic assignment.
12561   if (E->getLHS()->getType()->isAtomicType())
12562     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12563 }
12564 
12565 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12566 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12567                             SourceLocation CContext, unsigned diag,
12568                             bool pruneControlFlow = false) {
12569   if (pruneControlFlow) {
12570     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12571                           S.PDiag(diag)
12572                               << SourceType << T << E->getSourceRange()
12573                               << SourceRange(CContext));
12574     return;
12575   }
12576   S.Diag(E->getExprLoc(), diag)
12577     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12578 }
12579 
12580 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12581 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12582                             SourceLocation CContext,
12583                             unsigned diag, bool pruneControlFlow = false) {
12584   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12585 }
12586 
12587 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12588   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12589       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12590 }
12591 
12592 static void adornObjCBoolConversionDiagWithTernaryFixit(
12593     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12594   Expr *Ignored = SourceExpr->IgnoreImplicit();
12595   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12596     Ignored = OVE->getSourceExpr();
12597   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12598                      isa<BinaryOperator>(Ignored) ||
12599                      isa<CXXOperatorCallExpr>(Ignored);
12600   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12601   if (NeedsParens)
12602     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12603             << FixItHint::CreateInsertion(EndLoc, ")");
12604   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12605 }
12606 
12607 /// Diagnose an implicit cast from a floating point value to an integer value.
12608 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12609                                     SourceLocation CContext) {
12610   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12611   const bool PruneWarnings = S.inTemplateInstantiation();
12612 
12613   Expr *InnerE = E->IgnoreParenImpCasts();
12614   // We also want to warn on, e.g., "int i = -1.234"
12615   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12616     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12617       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12618 
12619   const bool IsLiteral =
12620       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12621 
12622   llvm::APFloat Value(0.0);
12623   bool IsConstant =
12624     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12625   if (!IsConstant) {
12626     if (isObjCSignedCharBool(S, T)) {
12627       return adornObjCBoolConversionDiagWithTernaryFixit(
12628           S, E,
12629           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12630               << E->getType());
12631     }
12632 
12633     return DiagnoseImpCast(S, E, T, CContext,
12634                            diag::warn_impcast_float_integer, PruneWarnings);
12635   }
12636 
12637   bool isExact = false;
12638 
12639   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12640                             T->hasUnsignedIntegerRepresentation());
12641   llvm::APFloat::opStatus Result = Value.convertToInteger(
12642       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12643 
12644   // FIXME: Force the precision of the source value down so we don't print
12645   // digits which are usually useless (we don't really care here if we
12646   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12647   // would automatically print the shortest representation, but it's a bit
12648   // tricky to implement.
12649   SmallString<16> PrettySourceValue;
12650   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12651   precision = (precision * 59 + 195) / 196;
12652   Value.toString(PrettySourceValue, precision);
12653 
12654   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12655     return adornObjCBoolConversionDiagWithTernaryFixit(
12656         S, E,
12657         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12658             << PrettySourceValue);
12659   }
12660 
12661   if (Result == llvm::APFloat::opOK && isExact) {
12662     if (IsLiteral) return;
12663     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12664                            PruneWarnings);
12665   }
12666 
12667   // Conversion of a floating-point value to a non-bool integer where the
12668   // integral part cannot be represented by the integer type is undefined.
12669   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12670     return DiagnoseImpCast(
12671         S, E, T, CContext,
12672         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12673                   : diag::warn_impcast_float_to_integer_out_of_range,
12674         PruneWarnings);
12675 
12676   unsigned DiagID = 0;
12677   if (IsLiteral) {
12678     // Warn on floating point literal to integer.
12679     DiagID = diag::warn_impcast_literal_float_to_integer;
12680   } else if (IntegerValue == 0) {
12681     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12682       return DiagnoseImpCast(S, E, T, CContext,
12683                              diag::warn_impcast_float_integer, PruneWarnings);
12684     }
12685     // Warn on non-zero to zero conversion.
12686     DiagID = diag::warn_impcast_float_to_integer_zero;
12687   } else {
12688     if (IntegerValue.isUnsigned()) {
12689       if (!IntegerValue.isMaxValue()) {
12690         return DiagnoseImpCast(S, E, T, CContext,
12691                                diag::warn_impcast_float_integer, PruneWarnings);
12692       }
12693     } else {  // IntegerValue.isSigned()
12694       if (!IntegerValue.isMaxSignedValue() &&
12695           !IntegerValue.isMinSignedValue()) {
12696         return DiagnoseImpCast(S, E, T, CContext,
12697                                diag::warn_impcast_float_integer, PruneWarnings);
12698       }
12699     }
12700     // Warn on evaluatable floating point expression to integer conversion.
12701     DiagID = diag::warn_impcast_float_to_integer;
12702   }
12703 
12704   SmallString<16> PrettyTargetValue;
12705   if (IsBool)
12706     PrettyTargetValue = Value.isZero() ? "false" : "true";
12707   else
12708     IntegerValue.toString(PrettyTargetValue);
12709 
12710   if (PruneWarnings) {
12711     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12712                           S.PDiag(DiagID)
12713                               << E->getType() << T.getUnqualifiedType()
12714                               << PrettySourceValue << PrettyTargetValue
12715                               << E->getSourceRange() << SourceRange(CContext));
12716   } else {
12717     S.Diag(E->getExprLoc(), DiagID)
12718         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12719         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12720   }
12721 }
12722 
12723 /// Analyze the given compound assignment for the possible losing of
12724 /// floating-point precision.
12725 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12726   assert(isa<CompoundAssignOperator>(E) &&
12727          "Must be compound assignment operation");
12728   // Recurse on the LHS and RHS in here
12729   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12730   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12731 
12732   if (E->getLHS()->getType()->isAtomicType())
12733     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12734 
12735   // Now check the outermost expression
12736   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12737   const auto *RBT = cast<CompoundAssignOperator>(E)
12738                         ->getComputationResultType()
12739                         ->getAs<BuiltinType>();
12740 
12741   // The below checks assume source is floating point.
12742   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12743 
12744   // If source is floating point but target is an integer.
12745   if (ResultBT->isInteger())
12746     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12747                            E->getExprLoc(), diag::warn_impcast_float_integer);
12748 
12749   if (!ResultBT->isFloatingPoint())
12750     return;
12751 
12752   // If both source and target are floating points, warn about losing precision.
12753   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12754       QualType(ResultBT, 0), QualType(RBT, 0));
12755   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12756     // warn about dropping FP rank.
12757     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12758                     diag::warn_impcast_float_result_precision);
12759 }
12760 
12761 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12762                                       IntRange Range) {
12763   if (!Range.Width) return "0";
12764 
12765   llvm::APSInt ValueInRange = Value;
12766   ValueInRange.setIsSigned(!Range.NonNegative);
12767   ValueInRange = ValueInRange.trunc(Range.Width);
12768   return toString(ValueInRange, 10);
12769 }
12770 
12771 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12772   if (!isa<ImplicitCastExpr>(Ex))
12773     return false;
12774 
12775   Expr *InnerE = Ex->IgnoreParenImpCasts();
12776   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12777   const Type *Source =
12778     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12779   if (Target->isDependentType())
12780     return false;
12781 
12782   const BuiltinType *FloatCandidateBT =
12783     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12784   const Type *BoolCandidateType = ToBool ? Target : Source;
12785 
12786   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12787           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12788 }
12789 
12790 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12791                                              SourceLocation CC) {
12792   unsigned NumArgs = TheCall->getNumArgs();
12793   for (unsigned i = 0; i < NumArgs; ++i) {
12794     Expr *CurrA = TheCall->getArg(i);
12795     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12796       continue;
12797 
12798     bool IsSwapped = ((i > 0) &&
12799         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12800     IsSwapped |= ((i < (NumArgs - 1)) &&
12801         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12802     if (IsSwapped) {
12803       // Warn on this floating-point to bool conversion.
12804       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12805                       CurrA->getType(), CC,
12806                       diag::warn_impcast_floating_point_to_bool);
12807     }
12808   }
12809 }
12810 
12811 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12812                                    SourceLocation CC) {
12813   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12814                         E->getExprLoc()))
12815     return;
12816 
12817   // Don't warn on functions which have return type nullptr_t.
12818   if (isa<CallExpr>(E))
12819     return;
12820 
12821   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12822   const Expr::NullPointerConstantKind NullKind =
12823       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12824   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12825     return;
12826 
12827   // Return if target type is a safe conversion.
12828   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12829       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12830     return;
12831 
12832   SourceLocation Loc = E->getSourceRange().getBegin();
12833 
12834   // Venture through the macro stacks to get to the source of macro arguments.
12835   // The new location is a better location than the complete location that was
12836   // passed in.
12837   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12838   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12839 
12840   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12841   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12842     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12843         Loc, S.SourceMgr, S.getLangOpts());
12844     if (MacroName == "NULL")
12845       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12846   }
12847 
12848   // Only warn if the null and context location are in the same macro expansion.
12849   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12850     return;
12851 
12852   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12853       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12854       << FixItHint::CreateReplacement(Loc,
12855                                       S.getFixItZeroLiteralForType(T, Loc));
12856 }
12857 
12858 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12859                                   ObjCArrayLiteral *ArrayLiteral);
12860 
12861 static void
12862 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12863                            ObjCDictionaryLiteral *DictionaryLiteral);
12864 
12865 /// Check a single element within a collection literal against the
12866 /// target element type.
12867 static void checkObjCCollectionLiteralElement(Sema &S,
12868                                               QualType TargetElementType,
12869                                               Expr *Element,
12870                                               unsigned ElementKind) {
12871   // Skip a bitcast to 'id' or qualified 'id'.
12872   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12873     if (ICE->getCastKind() == CK_BitCast &&
12874         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12875       Element = ICE->getSubExpr();
12876   }
12877 
12878   QualType ElementType = Element->getType();
12879   ExprResult ElementResult(Element);
12880   if (ElementType->getAs<ObjCObjectPointerType>() &&
12881       S.CheckSingleAssignmentConstraints(TargetElementType,
12882                                          ElementResult,
12883                                          false, false)
12884         != Sema::Compatible) {
12885     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12886         << ElementType << ElementKind << TargetElementType
12887         << Element->getSourceRange();
12888   }
12889 
12890   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12891     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12892   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12893     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12894 }
12895 
12896 /// Check an Objective-C array literal being converted to the given
12897 /// target type.
12898 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12899                                   ObjCArrayLiteral *ArrayLiteral) {
12900   if (!S.NSArrayDecl)
12901     return;
12902 
12903   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12904   if (!TargetObjCPtr)
12905     return;
12906 
12907   if (TargetObjCPtr->isUnspecialized() ||
12908       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12909         != S.NSArrayDecl->getCanonicalDecl())
12910     return;
12911 
12912   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12913   if (TypeArgs.size() != 1)
12914     return;
12915 
12916   QualType TargetElementType = TypeArgs[0];
12917   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12918     checkObjCCollectionLiteralElement(S, TargetElementType,
12919                                       ArrayLiteral->getElement(I),
12920                                       0);
12921   }
12922 }
12923 
12924 /// Check an Objective-C dictionary literal being converted to the given
12925 /// target type.
12926 static void
12927 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12928                            ObjCDictionaryLiteral *DictionaryLiteral) {
12929   if (!S.NSDictionaryDecl)
12930     return;
12931 
12932   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12933   if (!TargetObjCPtr)
12934     return;
12935 
12936   if (TargetObjCPtr->isUnspecialized() ||
12937       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12938         != S.NSDictionaryDecl->getCanonicalDecl())
12939     return;
12940 
12941   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12942   if (TypeArgs.size() != 2)
12943     return;
12944 
12945   QualType TargetKeyType = TypeArgs[0];
12946   QualType TargetObjectType = TypeArgs[1];
12947   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12948     auto Element = DictionaryLiteral->getKeyValueElement(I);
12949     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12950     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12951   }
12952 }
12953 
12954 // Helper function to filter out cases for constant width constant conversion.
12955 // Don't warn on char array initialization or for non-decimal values.
12956 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12957                                           SourceLocation CC) {
12958   // If initializing from a constant, and the constant starts with '0',
12959   // then it is a binary, octal, or hexadecimal.  Allow these constants
12960   // to fill all the bits, even if there is a sign change.
12961   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12962     const char FirstLiteralCharacter =
12963         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12964     if (FirstLiteralCharacter == '0')
12965       return false;
12966   }
12967 
12968   // If the CC location points to a '{', and the type is char, then assume
12969   // assume it is an array initialization.
12970   if (CC.isValid() && T->isCharType()) {
12971     const char FirstContextCharacter =
12972         S.getSourceManager().getCharacterData(CC)[0];
12973     if (FirstContextCharacter == '{')
12974       return false;
12975   }
12976 
12977   return true;
12978 }
12979 
12980 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12981   const auto *IL = dyn_cast<IntegerLiteral>(E);
12982   if (!IL) {
12983     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12984       if (UO->getOpcode() == UO_Minus)
12985         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12986     }
12987   }
12988 
12989   return IL;
12990 }
12991 
12992 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12993   E = E->IgnoreParenImpCasts();
12994   SourceLocation ExprLoc = E->getExprLoc();
12995 
12996   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12997     BinaryOperator::Opcode Opc = BO->getOpcode();
12998     Expr::EvalResult Result;
12999     // Do not diagnose unsigned shifts.
13000     if (Opc == BO_Shl) {
13001       const auto *LHS = getIntegerLiteral(BO->getLHS());
13002       const auto *RHS = getIntegerLiteral(BO->getRHS());
13003       if (LHS && LHS->getValue() == 0)
13004         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
13005       else if (!E->isValueDependent() && LHS && RHS &&
13006                RHS->getValue().isNonNegative() &&
13007                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
13008         S.Diag(ExprLoc, diag::warn_left_shift_always)
13009             << (Result.Val.getInt() != 0);
13010       else if (E->getType()->isSignedIntegerType())
13011         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
13012     }
13013   }
13014 
13015   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
13016     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
13017     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
13018     if (!LHS || !RHS)
13019       return;
13020     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13021         (RHS->getValue() == 0 || RHS->getValue() == 1))
13022       // Do not diagnose common idioms.
13023       return;
13024     if (LHS->getValue() != 0 && RHS->getValue() != 0)
13025       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
13026   }
13027 }
13028 
13029 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
13030                                     SourceLocation CC,
13031                                     bool *ICContext = nullptr,
13032                                     bool IsListInit = false) {
13033   if (E->isTypeDependent() || E->isValueDependent()) return;
13034 
13035   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
13036   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
13037   if (Source == Target) return;
13038   if (Target->isDependentType()) return;
13039 
13040   // If the conversion context location is invalid don't complain. We also
13041   // don't want to emit a warning if the issue occurs from the expansion of
13042   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13043   // delay this check as long as possible. Once we detect we are in that
13044   // scenario, we just return.
13045   if (CC.isInvalid())
13046     return;
13047 
13048   if (Source->isAtomicType())
13049     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
13050 
13051   // Diagnose implicit casts to bool.
13052   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
13053     if (isa<StringLiteral>(E))
13054       // Warn on string literal to bool.  Checks for string literals in logical
13055       // and expressions, for instance, assert(0 && "error here"), are
13056       // prevented by a check in AnalyzeImplicitConversions().
13057       return DiagnoseImpCast(S, E, T, CC,
13058                              diag::warn_impcast_string_literal_to_bool);
13059     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
13060         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
13061       // This covers the literal expressions that evaluate to Objective-C
13062       // objects.
13063       return DiagnoseImpCast(S, E, T, CC,
13064                              diag::warn_impcast_objective_c_literal_to_bool);
13065     }
13066     if (Source->isPointerType() || Source->canDecayToPointerType()) {
13067       // Warn on pointer to bool conversion that is always true.
13068       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
13069                                      SourceRange(CC));
13070     }
13071   }
13072 
13073   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13074   // is a typedef for signed char (macOS), then that constant value has to be 1
13075   // or 0.
13076   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
13077     Expr::EvalResult Result;
13078     if (E->EvaluateAsInt(Result, S.getASTContext(),
13079                          Expr::SE_AllowSideEffects)) {
13080       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13081         adornObjCBoolConversionDiagWithTernaryFixit(
13082             S, E,
13083             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13084                 << toString(Result.Val.getInt(), 10));
13085       }
13086       return;
13087     }
13088   }
13089 
13090   // Check implicit casts from Objective-C collection literals to specialized
13091   // collection types, e.g., NSArray<NSString *> *.
13092   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13093     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
13094   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13095     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
13096 
13097   // Strip vector types.
13098   if (isa<VectorType>(Source)) {
13099     if (Target->isVLSTBuiltinType() &&
13100         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
13101                                          QualType(Source, 0)) ||
13102          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
13103                                             QualType(Source, 0))))
13104       return;
13105 
13106     if (!isa<VectorType>(Target)) {
13107       if (S.SourceMgr.isInSystemMacro(CC))
13108         return;
13109       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
13110     }
13111 
13112     // If the vector cast is cast between two vectors of the same size, it is
13113     // a bitcast, not a conversion.
13114     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
13115       return;
13116 
13117     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13118     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13119   }
13120   if (auto VecTy = dyn_cast<VectorType>(Target))
13121     Target = VecTy->getElementType().getTypePtr();
13122 
13123   // Strip complex types.
13124   if (isa<ComplexType>(Source)) {
13125     if (!isa<ComplexType>(Target)) {
13126       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13127         return;
13128 
13129       return DiagnoseImpCast(S, E, T, CC,
13130                              S.getLangOpts().CPlusPlus
13131                                  ? diag::err_impcast_complex_scalar
13132                                  : diag::warn_impcast_complex_scalar);
13133     }
13134 
13135     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13136     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13137   }
13138 
13139   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13140   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13141 
13142   // If the source is floating point...
13143   if (SourceBT && SourceBT->isFloatingPoint()) {
13144     // ...and the target is floating point...
13145     if (TargetBT && TargetBT->isFloatingPoint()) {
13146       // ...then warn if we're dropping FP rank.
13147 
13148       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
13149           QualType(SourceBT, 0), QualType(TargetBT, 0));
13150       if (Order > 0) {
13151         // Don't warn about float constants that are precisely
13152         // representable in the target type.
13153         Expr::EvalResult result;
13154         if (E->EvaluateAsRValue(result, S.Context)) {
13155           // Value might be a float, a float vector, or a float complex.
13156           if (IsSameFloatAfterCast(result.Val,
13157                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13158                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13159             return;
13160         }
13161 
13162         if (S.SourceMgr.isInSystemMacro(CC))
13163           return;
13164 
13165         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
13166       }
13167       // ... or possibly if we're increasing rank, too
13168       else if (Order < 0) {
13169         if (S.SourceMgr.isInSystemMacro(CC))
13170           return;
13171 
13172         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
13173       }
13174       return;
13175     }
13176 
13177     // If the target is integral, always warn.
13178     if (TargetBT && TargetBT->isInteger()) {
13179       if (S.SourceMgr.isInSystemMacro(CC))
13180         return;
13181 
13182       DiagnoseFloatingImpCast(S, E, T, CC);
13183     }
13184 
13185     // Detect the case where a call result is converted from floating-point to
13186     // to bool, and the final argument to the call is converted from bool, to
13187     // discover this typo:
13188     //
13189     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
13190     //
13191     // FIXME: This is an incredibly special case; is there some more general
13192     // way to detect this class of misplaced-parentheses bug?
13193     if (Target->isBooleanType() && isa<CallExpr>(E)) {
13194       // Check last argument of function call to see if it is an
13195       // implicit cast from a type matching the type the result
13196       // is being cast to.
13197       CallExpr *CEx = cast<CallExpr>(E);
13198       if (unsigned NumArgs = CEx->getNumArgs()) {
13199         Expr *LastA = CEx->getArg(NumArgs - 1);
13200         Expr *InnerE = LastA->IgnoreParenImpCasts();
13201         if (isa<ImplicitCastExpr>(LastA) &&
13202             InnerE->getType()->isBooleanType()) {
13203           // Warn on this floating-point to bool conversion
13204           DiagnoseImpCast(S, E, T, CC,
13205                           diag::warn_impcast_floating_point_to_bool);
13206         }
13207       }
13208     }
13209     return;
13210   }
13211 
13212   // Valid casts involving fixed point types should be accounted for here.
13213   if (Source->isFixedPointType()) {
13214     if (Target->isUnsaturatedFixedPointType()) {
13215       Expr::EvalResult Result;
13216       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
13217                                   S.isConstantEvaluated())) {
13218         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13219         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
13220         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
13221         if (Value > MaxVal || Value < MinVal) {
13222           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13223                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13224                                     << Value.toString() << T
13225                                     << E->getSourceRange()
13226                                     << clang::SourceRange(CC));
13227           return;
13228         }
13229       }
13230     } else if (Target->isIntegerType()) {
13231       Expr::EvalResult Result;
13232       if (!S.isConstantEvaluated() &&
13233           E->EvaluateAsFixedPoint(Result, S.Context,
13234                                   Expr::SE_AllowSideEffects)) {
13235         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13236 
13237         bool Overflowed;
13238         llvm::APSInt IntResult = FXResult.convertToInt(
13239             S.Context.getIntWidth(T),
13240             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
13241 
13242         if (Overflowed) {
13243           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13244                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13245                                     << FXResult.toString() << T
13246                                     << E->getSourceRange()
13247                                     << clang::SourceRange(CC));
13248           return;
13249         }
13250       }
13251     }
13252   } else if (Target->isUnsaturatedFixedPointType()) {
13253     if (Source->isIntegerType()) {
13254       Expr::EvalResult Result;
13255       if (!S.isConstantEvaluated() &&
13256           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
13257         llvm::APSInt Value = Result.Val.getInt();
13258 
13259         bool Overflowed;
13260         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13261             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
13262 
13263         if (Overflowed) {
13264           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13265                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13266                                     << toString(Value, /*Radix=*/10) << T
13267                                     << E->getSourceRange()
13268                                     << clang::SourceRange(CC));
13269           return;
13270         }
13271       }
13272     }
13273   }
13274 
13275   // If we are casting an integer type to a floating point type without
13276   // initialization-list syntax, we might lose accuracy if the floating
13277   // point type has a narrower significand than the integer type.
13278   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13279       TargetBT->isFloatingType() && !IsListInit) {
13280     // Determine the number of precision bits in the source integer type.
13281     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
13282                                         /*Approximate*/ true);
13283     unsigned int SourcePrecision = SourceRange.Width;
13284 
13285     // Determine the number of precision bits in the
13286     // target floating point type.
13287     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13288         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13289 
13290     if (SourcePrecision > 0 && TargetPrecision > 0 &&
13291         SourcePrecision > TargetPrecision) {
13292 
13293       if (Optional<llvm::APSInt> SourceInt =
13294               E->getIntegerConstantExpr(S.Context)) {
13295         // If the source integer is a constant, convert it to the target
13296         // floating point type. Issue a warning if the value changes
13297         // during the whole conversion.
13298         llvm::APFloat TargetFloatValue(
13299             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13300         llvm::APFloat::opStatus ConversionStatus =
13301             TargetFloatValue.convertFromAPInt(
13302                 *SourceInt, SourceBT->isSignedInteger(),
13303                 llvm::APFloat::rmNearestTiesToEven);
13304 
13305         if (ConversionStatus != llvm::APFloat::opOK) {
13306           SmallString<32> PrettySourceValue;
13307           SourceInt->toString(PrettySourceValue, 10);
13308           SmallString<32> PrettyTargetValue;
13309           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13310 
13311           S.DiagRuntimeBehavior(
13312               E->getExprLoc(), E,
13313               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
13314                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
13315                   << E->getSourceRange() << clang::SourceRange(CC));
13316         }
13317       } else {
13318         // Otherwise, the implicit conversion may lose precision.
13319         DiagnoseImpCast(S, E, T, CC,
13320                         diag::warn_impcast_integer_float_precision);
13321       }
13322     }
13323   }
13324 
13325   DiagnoseNullConversion(S, E, T, CC);
13326 
13327   S.DiscardMisalignedMemberAddress(Target, E);
13328 
13329   if (Target->isBooleanType())
13330     DiagnoseIntInBoolContext(S, E);
13331 
13332   if (!Source->isIntegerType() || !Target->isIntegerType())
13333     return;
13334 
13335   // TODO: remove this early return once the false positives for constant->bool
13336   // in templates, macros, etc, are reduced or removed.
13337   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13338     return;
13339 
13340   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
13341       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13342     return adornObjCBoolConversionDiagWithTernaryFixit(
13343         S, E,
13344         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13345             << E->getType());
13346   }
13347 
13348   IntRange SourceTypeRange =
13349       IntRange::forTargetOfCanonicalType(S.Context, Source);
13350   IntRange LikelySourceRange =
13351       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
13352   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
13353 
13354   if (LikelySourceRange.Width > TargetRange.Width) {
13355     // If the source is a constant, use a default-on diagnostic.
13356     // TODO: this should happen for bitfield stores, too.
13357     Expr::EvalResult Result;
13358     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
13359                          S.isConstantEvaluated())) {
13360       llvm::APSInt Value(32);
13361       Value = Result.Val.getInt();
13362 
13363       if (S.SourceMgr.isInSystemMacro(CC))
13364         return;
13365 
13366       std::string PrettySourceValue = toString(Value, 10);
13367       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13368 
13369       S.DiagRuntimeBehavior(
13370           E->getExprLoc(), E,
13371           S.PDiag(diag::warn_impcast_integer_precision_constant)
13372               << PrettySourceValue << PrettyTargetValue << E->getType() << T
13373               << E->getSourceRange() << SourceRange(CC));
13374       return;
13375     }
13376 
13377     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13378     if (S.SourceMgr.isInSystemMacro(CC))
13379       return;
13380 
13381     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
13382       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
13383                              /* pruneControlFlow */ true);
13384     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
13385   }
13386 
13387   if (TargetRange.Width > SourceTypeRange.Width) {
13388     if (auto *UO = dyn_cast<UnaryOperator>(E))
13389       if (UO->getOpcode() == UO_Minus)
13390         if (Source->isUnsignedIntegerType()) {
13391           if (Target->isUnsignedIntegerType())
13392             return DiagnoseImpCast(S, E, T, CC,
13393                                    diag::warn_impcast_high_order_zero_bits);
13394           if (Target->isSignedIntegerType())
13395             return DiagnoseImpCast(S, E, T, CC,
13396                                    diag::warn_impcast_nonnegative_result);
13397         }
13398   }
13399 
13400   if (TargetRange.Width == LikelySourceRange.Width &&
13401       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13402       Source->isSignedIntegerType()) {
13403     // Warn when doing a signed to signed conversion, warn if the positive
13404     // source value is exactly the width of the target type, which will
13405     // cause a negative value to be stored.
13406 
13407     Expr::EvalResult Result;
13408     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
13409         !S.SourceMgr.isInSystemMacro(CC)) {
13410       llvm::APSInt Value = Result.Val.getInt();
13411       if (isSameWidthConstantConversion(S, E, T, CC)) {
13412         std::string PrettySourceValue = toString(Value, 10);
13413         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13414 
13415         S.DiagRuntimeBehavior(
13416             E->getExprLoc(), E,
13417             S.PDiag(diag::warn_impcast_integer_precision_constant)
13418                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13419                 << E->getSourceRange() << SourceRange(CC));
13420         return;
13421       }
13422     }
13423 
13424     // Fall through for non-constants to give a sign conversion warning.
13425   }
13426 
13427   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13428       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13429        LikelySourceRange.Width == TargetRange.Width)) {
13430     if (S.SourceMgr.isInSystemMacro(CC))
13431       return;
13432 
13433     unsigned DiagID = diag::warn_impcast_integer_sign;
13434 
13435     // Traditionally, gcc has warned about this under -Wsign-compare.
13436     // We also want to warn about it in -Wconversion.
13437     // So if -Wconversion is off, use a completely identical diagnostic
13438     // in the sign-compare group.
13439     // The conditional-checking code will
13440     if (ICContext) {
13441       DiagID = diag::warn_impcast_integer_sign_conditional;
13442       *ICContext = true;
13443     }
13444 
13445     return DiagnoseImpCast(S, E, T, CC, DiagID);
13446   }
13447 
13448   // Diagnose conversions between different enumeration types.
13449   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13450   // type, to give us better diagnostics.
13451   QualType SourceType = E->getType();
13452   if (!S.getLangOpts().CPlusPlus) {
13453     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13454       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13455         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13456         SourceType = S.Context.getTypeDeclType(Enum);
13457         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13458       }
13459   }
13460 
13461   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13462     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13463       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13464           TargetEnum->getDecl()->hasNameForLinkage() &&
13465           SourceEnum != TargetEnum) {
13466         if (S.SourceMgr.isInSystemMacro(CC))
13467           return;
13468 
13469         return DiagnoseImpCast(S, E, SourceType, T, CC,
13470                                diag::warn_impcast_different_enum_types);
13471       }
13472 }
13473 
13474 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13475                                      SourceLocation CC, QualType T);
13476 
13477 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13478                                     SourceLocation CC, bool &ICContext) {
13479   E = E->IgnoreParenImpCasts();
13480 
13481   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13482     return CheckConditionalOperator(S, CO, CC, T);
13483 
13484   AnalyzeImplicitConversions(S, E, CC);
13485   if (E->getType() != T)
13486     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13487 }
13488 
13489 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13490                                      SourceLocation CC, QualType T) {
13491   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13492 
13493   Expr *TrueExpr = E->getTrueExpr();
13494   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13495     TrueExpr = BCO->getCommon();
13496 
13497   bool Suspicious = false;
13498   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13499   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13500 
13501   if (T->isBooleanType())
13502     DiagnoseIntInBoolContext(S, E);
13503 
13504   // If -Wconversion would have warned about either of the candidates
13505   // for a signedness conversion to the context type...
13506   if (!Suspicious) return;
13507 
13508   // ...but it's currently ignored...
13509   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13510     return;
13511 
13512   // ...then check whether it would have warned about either of the
13513   // candidates for a signedness conversion to the condition type.
13514   if (E->getType() == T) return;
13515 
13516   Suspicious = false;
13517   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13518                           E->getType(), CC, &Suspicious);
13519   if (!Suspicious)
13520     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13521                             E->getType(), CC, &Suspicious);
13522 }
13523 
13524 /// Check conversion of given expression to boolean.
13525 /// Input argument E is a logical expression.
13526 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13527   if (S.getLangOpts().Bool)
13528     return;
13529   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13530     return;
13531   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13532 }
13533 
13534 namespace {
13535 struct AnalyzeImplicitConversionsWorkItem {
13536   Expr *E;
13537   SourceLocation CC;
13538   bool IsListInit;
13539 };
13540 }
13541 
13542 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13543 /// that should be visited are added to WorkList.
13544 static void AnalyzeImplicitConversions(
13545     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13546     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13547   Expr *OrigE = Item.E;
13548   SourceLocation CC = Item.CC;
13549 
13550   QualType T = OrigE->getType();
13551   Expr *E = OrigE->IgnoreParenImpCasts();
13552 
13553   // Propagate whether we are in a C++ list initialization expression.
13554   // If so, we do not issue warnings for implicit int-float conversion
13555   // precision loss, because C++11 narrowing already handles it.
13556   bool IsListInit = Item.IsListInit ||
13557                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13558 
13559   if (E->isTypeDependent() || E->isValueDependent())
13560     return;
13561 
13562   Expr *SourceExpr = E;
13563   // Examine, but don't traverse into the source expression of an
13564   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13565   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13566   // evaluate it in the context of checking the specific conversion to T though.
13567   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13568     if (auto *Src = OVE->getSourceExpr())
13569       SourceExpr = Src;
13570 
13571   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13572     if (UO->getOpcode() == UO_Not &&
13573         UO->getSubExpr()->isKnownToHaveBooleanValue())
13574       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13575           << OrigE->getSourceRange() << T->isBooleanType()
13576           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13577 
13578   if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
13579     if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13580         BO->getLHS()->isKnownToHaveBooleanValue() &&
13581         BO->getRHS()->isKnownToHaveBooleanValue() &&
13582         BO->getLHS()->HasSideEffects(S.Context) &&
13583         BO->getRHS()->HasSideEffects(S.Context)) {
13584       S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13585           << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange()
13586           << FixItHint::CreateReplacement(
13587                  BO->getOperatorLoc(),
13588                  (BO->getOpcode() == BO_And ? "&&" : "||"));
13589       S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13590     }
13591 
13592   // For conditional operators, we analyze the arguments as if they
13593   // were being fed directly into the output.
13594   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13595     CheckConditionalOperator(S, CO, CC, T);
13596     return;
13597   }
13598 
13599   // Check implicit argument conversions for function calls.
13600   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13601     CheckImplicitArgumentConversions(S, Call, CC);
13602 
13603   // Go ahead and check any implicit conversions we might have skipped.
13604   // The non-canonical typecheck is just an optimization;
13605   // CheckImplicitConversion will filter out dead implicit conversions.
13606   if (SourceExpr->getType() != T)
13607     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13608 
13609   // Now continue drilling into this expression.
13610 
13611   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13612     // The bound subexpressions in a PseudoObjectExpr are not reachable
13613     // as transitive children.
13614     // FIXME: Use a more uniform representation for this.
13615     for (auto *SE : POE->semantics())
13616       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13617         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13618   }
13619 
13620   // Skip past explicit casts.
13621   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13622     E = CE->getSubExpr()->IgnoreParenImpCasts();
13623     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13624       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13625     WorkList.push_back({E, CC, IsListInit});
13626     return;
13627   }
13628 
13629   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13630     // Do a somewhat different check with comparison operators.
13631     if (BO->isComparisonOp())
13632       return AnalyzeComparison(S, BO);
13633 
13634     // And with simple assignments.
13635     if (BO->getOpcode() == BO_Assign)
13636       return AnalyzeAssignment(S, BO);
13637     // And with compound assignments.
13638     if (BO->isAssignmentOp())
13639       return AnalyzeCompoundAssignment(S, BO);
13640   }
13641 
13642   // These break the otherwise-useful invariant below.  Fortunately,
13643   // we don't really need to recurse into them, because any internal
13644   // expressions should have been analyzed already when they were
13645   // built into statements.
13646   if (isa<StmtExpr>(E)) return;
13647 
13648   // Don't descend into unevaluated contexts.
13649   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13650 
13651   // Now just recurse over the expression's children.
13652   CC = E->getExprLoc();
13653   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13654   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13655   for (Stmt *SubStmt : E->children()) {
13656     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13657     if (!ChildExpr)
13658       continue;
13659 
13660     if (IsLogicalAndOperator &&
13661         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13662       // Ignore checking string literals that are in logical and operators.
13663       // This is a common pattern for asserts.
13664       continue;
13665     WorkList.push_back({ChildExpr, CC, IsListInit});
13666   }
13667 
13668   if (BO && BO->isLogicalOp()) {
13669     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13670     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13671       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13672 
13673     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13674     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13675       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13676   }
13677 
13678   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13679     if (U->getOpcode() == UO_LNot) {
13680       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13681     } else if (U->getOpcode() != UO_AddrOf) {
13682       if (U->getSubExpr()->getType()->isAtomicType())
13683         S.Diag(U->getSubExpr()->getBeginLoc(),
13684                diag::warn_atomic_implicit_seq_cst);
13685     }
13686   }
13687 }
13688 
13689 /// AnalyzeImplicitConversions - Find and report any interesting
13690 /// implicit conversions in the given expression.  There are a couple
13691 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13692 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13693                                        bool IsListInit/*= false*/) {
13694   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13695   WorkList.push_back({OrigE, CC, IsListInit});
13696   while (!WorkList.empty())
13697     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13698 }
13699 
13700 /// Diagnose integer type and any valid implicit conversion to it.
13701 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13702   // Taking into account implicit conversions,
13703   // allow any integer.
13704   if (!E->getType()->isIntegerType()) {
13705     S.Diag(E->getBeginLoc(),
13706            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13707     return true;
13708   }
13709   // Potentially emit standard warnings for implicit conversions if enabled
13710   // using -Wconversion.
13711   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13712   return false;
13713 }
13714 
13715 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13716 // Returns true when emitting a warning about taking the address of a reference.
13717 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13718                               const PartialDiagnostic &PD) {
13719   E = E->IgnoreParenImpCasts();
13720 
13721   const FunctionDecl *FD = nullptr;
13722 
13723   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13724     if (!DRE->getDecl()->getType()->isReferenceType())
13725       return false;
13726   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13727     if (!M->getMemberDecl()->getType()->isReferenceType())
13728       return false;
13729   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13730     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13731       return false;
13732     FD = Call->getDirectCallee();
13733   } else {
13734     return false;
13735   }
13736 
13737   SemaRef.Diag(E->getExprLoc(), PD);
13738 
13739   // If possible, point to location of function.
13740   if (FD) {
13741     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13742   }
13743 
13744   return true;
13745 }
13746 
13747 // Returns true if the SourceLocation is expanded from any macro body.
13748 // Returns false if the SourceLocation is invalid, is from not in a macro
13749 // expansion, or is from expanded from a top-level macro argument.
13750 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13751   if (Loc.isInvalid())
13752     return false;
13753 
13754   while (Loc.isMacroID()) {
13755     if (SM.isMacroBodyExpansion(Loc))
13756       return true;
13757     Loc = SM.getImmediateMacroCallerLoc(Loc);
13758   }
13759 
13760   return false;
13761 }
13762 
13763 /// Diagnose pointers that are always non-null.
13764 /// \param E the expression containing the pointer
13765 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13766 /// compared to a null pointer
13767 /// \param IsEqual True when the comparison is equal to a null pointer
13768 /// \param Range Extra SourceRange to highlight in the diagnostic
13769 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13770                                         Expr::NullPointerConstantKind NullKind,
13771                                         bool IsEqual, SourceRange Range) {
13772   if (!E)
13773     return;
13774 
13775   // Don't warn inside macros.
13776   if (E->getExprLoc().isMacroID()) {
13777     const SourceManager &SM = getSourceManager();
13778     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13779         IsInAnyMacroBody(SM, Range.getBegin()))
13780       return;
13781   }
13782   E = E->IgnoreImpCasts();
13783 
13784   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13785 
13786   if (isa<CXXThisExpr>(E)) {
13787     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13788                                 : diag::warn_this_bool_conversion;
13789     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13790     return;
13791   }
13792 
13793   bool IsAddressOf = false;
13794 
13795   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13796     if (UO->getOpcode() != UO_AddrOf)
13797       return;
13798     IsAddressOf = true;
13799     E = UO->getSubExpr();
13800   }
13801 
13802   if (IsAddressOf) {
13803     unsigned DiagID = IsCompare
13804                           ? diag::warn_address_of_reference_null_compare
13805                           : diag::warn_address_of_reference_bool_conversion;
13806     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13807                                          << IsEqual;
13808     if (CheckForReference(*this, E, PD)) {
13809       return;
13810     }
13811   }
13812 
13813   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13814     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13815     std::string Str;
13816     llvm::raw_string_ostream S(Str);
13817     E->printPretty(S, nullptr, getPrintingPolicy());
13818     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13819                                 : diag::warn_cast_nonnull_to_bool;
13820     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13821       << E->getSourceRange() << Range << IsEqual;
13822     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13823   };
13824 
13825   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13826   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13827     if (auto *Callee = Call->getDirectCallee()) {
13828       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13829         ComplainAboutNonnullParamOrCall(A);
13830         return;
13831       }
13832     }
13833   }
13834 
13835   // Expect to find a single Decl.  Skip anything more complicated.
13836   ValueDecl *D = nullptr;
13837   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13838     D = R->getDecl();
13839   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13840     D = M->getMemberDecl();
13841   }
13842 
13843   // Weak Decls can be null.
13844   if (!D || D->isWeak())
13845     return;
13846 
13847   // Check for parameter decl with nonnull attribute
13848   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13849     if (getCurFunction() &&
13850         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13851       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13852         ComplainAboutNonnullParamOrCall(A);
13853         return;
13854       }
13855 
13856       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13857         // Skip function template not specialized yet.
13858         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13859           return;
13860         auto ParamIter = llvm::find(FD->parameters(), PV);
13861         assert(ParamIter != FD->param_end());
13862         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13863 
13864         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13865           if (!NonNull->args_size()) {
13866               ComplainAboutNonnullParamOrCall(NonNull);
13867               return;
13868           }
13869 
13870           for (const ParamIdx &ArgNo : NonNull->args()) {
13871             if (ArgNo.getASTIndex() == ParamNo) {
13872               ComplainAboutNonnullParamOrCall(NonNull);
13873               return;
13874             }
13875           }
13876         }
13877       }
13878     }
13879   }
13880 
13881   QualType T = D->getType();
13882   const bool IsArray = T->isArrayType();
13883   const bool IsFunction = T->isFunctionType();
13884 
13885   // Address of function is used to silence the function warning.
13886   if (IsAddressOf && IsFunction) {
13887     return;
13888   }
13889 
13890   // Found nothing.
13891   if (!IsAddressOf && !IsFunction && !IsArray)
13892     return;
13893 
13894   // Pretty print the expression for the diagnostic.
13895   std::string Str;
13896   llvm::raw_string_ostream S(Str);
13897   E->printPretty(S, nullptr, getPrintingPolicy());
13898 
13899   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13900                               : diag::warn_impcast_pointer_to_bool;
13901   enum {
13902     AddressOf,
13903     FunctionPointer,
13904     ArrayPointer
13905   } DiagType;
13906   if (IsAddressOf)
13907     DiagType = AddressOf;
13908   else if (IsFunction)
13909     DiagType = FunctionPointer;
13910   else if (IsArray)
13911     DiagType = ArrayPointer;
13912   else
13913     llvm_unreachable("Could not determine diagnostic.");
13914   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13915                                 << Range << IsEqual;
13916 
13917   if (!IsFunction)
13918     return;
13919 
13920   // Suggest '&' to silence the function warning.
13921   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13922       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13923 
13924   // Check to see if '()' fixit should be emitted.
13925   QualType ReturnType;
13926   UnresolvedSet<4> NonTemplateOverloads;
13927   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13928   if (ReturnType.isNull())
13929     return;
13930 
13931   if (IsCompare) {
13932     // There are two cases here.  If there is null constant, the only suggest
13933     // for a pointer return type.  If the null is 0, then suggest if the return
13934     // type is a pointer or an integer type.
13935     if (!ReturnType->isPointerType()) {
13936       if (NullKind == Expr::NPCK_ZeroExpression ||
13937           NullKind == Expr::NPCK_ZeroLiteral) {
13938         if (!ReturnType->isIntegerType())
13939           return;
13940       } else {
13941         return;
13942       }
13943     }
13944   } else { // !IsCompare
13945     // For function to bool, only suggest if the function pointer has bool
13946     // return type.
13947     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13948       return;
13949   }
13950   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13951       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13952 }
13953 
13954 /// Diagnoses "dangerous" implicit conversions within the given
13955 /// expression (which is a full expression).  Implements -Wconversion
13956 /// and -Wsign-compare.
13957 ///
13958 /// \param CC the "context" location of the implicit conversion, i.e.
13959 ///   the most location of the syntactic entity requiring the implicit
13960 ///   conversion
13961 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13962   // Don't diagnose in unevaluated contexts.
13963   if (isUnevaluatedContext())
13964     return;
13965 
13966   // Don't diagnose for value- or type-dependent expressions.
13967   if (E->isTypeDependent() || E->isValueDependent())
13968     return;
13969 
13970   // Check for array bounds violations in cases where the check isn't triggered
13971   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13972   // ArraySubscriptExpr is on the RHS of a variable initialization.
13973   CheckArrayAccess(E);
13974 
13975   // This is not the right CC for (e.g.) a variable initialization.
13976   AnalyzeImplicitConversions(*this, E, CC);
13977 }
13978 
13979 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13980 /// Input argument E is a logical expression.
13981 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13982   ::CheckBoolLikeConversion(*this, E, CC);
13983 }
13984 
13985 /// Diagnose when expression is an integer constant expression and its evaluation
13986 /// results in integer overflow
13987 void Sema::CheckForIntOverflow (Expr *E) {
13988   // Use a work list to deal with nested struct initializers.
13989   SmallVector<Expr *, 2> Exprs(1, E);
13990 
13991   do {
13992     Expr *OriginalE = Exprs.pop_back_val();
13993     Expr *E = OriginalE->IgnoreParenCasts();
13994 
13995     if (isa<BinaryOperator>(E)) {
13996       E->EvaluateForOverflow(Context);
13997       continue;
13998     }
13999 
14000     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
14001       Exprs.append(InitList->inits().begin(), InitList->inits().end());
14002     else if (isa<ObjCBoxedExpr>(OriginalE))
14003       E->EvaluateForOverflow(Context);
14004     else if (auto Call = dyn_cast<CallExpr>(E))
14005       Exprs.append(Call->arg_begin(), Call->arg_end());
14006     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
14007       Exprs.append(Message->arg_begin(), Message->arg_end());
14008   } while (!Exprs.empty());
14009 }
14010 
14011 namespace {
14012 
14013 /// Visitor for expressions which looks for unsequenced operations on the
14014 /// same object.
14015 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14016   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14017 
14018   /// A tree of sequenced regions within an expression. Two regions are
14019   /// unsequenced if one is an ancestor or a descendent of the other. When we
14020   /// finish processing an expression with sequencing, such as a comma
14021   /// expression, we fold its tree nodes into its parent, since they are
14022   /// unsequenced with respect to nodes we will visit later.
14023   class SequenceTree {
14024     struct Value {
14025       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14026       unsigned Parent : 31;
14027       unsigned Merged : 1;
14028     };
14029     SmallVector<Value, 8> Values;
14030 
14031   public:
14032     /// A region within an expression which may be sequenced with respect
14033     /// to some other region.
14034     class Seq {
14035       friend class SequenceTree;
14036 
14037       unsigned Index;
14038 
14039       explicit Seq(unsigned N) : Index(N) {}
14040 
14041     public:
14042       Seq() : Index(0) {}
14043     };
14044 
14045     SequenceTree() { Values.push_back(Value(0)); }
14046     Seq root() const { return Seq(0); }
14047 
14048     /// Create a new sequence of operations, which is an unsequenced
14049     /// subset of \p Parent. This sequence of operations is sequenced with
14050     /// respect to other children of \p Parent.
14051     Seq allocate(Seq Parent) {
14052       Values.push_back(Value(Parent.Index));
14053       return Seq(Values.size() - 1);
14054     }
14055 
14056     /// Merge a sequence of operations into its parent.
14057     void merge(Seq S) {
14058       Values[S.Index].Merged = true;
14059     }
14060 
14061     /// Determine whether two operations are unsequenced. This operation
14062     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14063     /// should have been merged into its parent as appropriate.
14064     bool isUnsequenced(Seq Cur, Seq Old) {
14065       unsigned C = representative(Cur.Index);
14066       unsigned Target = representative(Old.Index);
14067       while (C >= Target) {
14068         if (C == Target)
14069           return true;
14070         C = Values[C].Parent;
14071       }
14072       return false;
14073     }
14074 
14075   private:
14076     /// Pick a representative for a sequence.
14077     unsigned representative(unsigned K) {
14078       if (Values[K].Merged)
14079         // Perform path compression as we go.
14080         return Values[K].Parent = representative(Values[K].Parent);
14081       return K;
14082     }
14083   };
14084 
14085   /// An object for which we can track unsequenced uses.
14086   using Object = const NamedDecl *;
14087 
14088   /// Different flavors of object usage which we track. We only track the
14089   /// least-sequenced usage of each kind.
14090   enum UsageKind {
14091     /// A read of an object. Multiple unsequenced reads are OK.
14092     UK_Use,
14093 
14094     /// A modification of an object which is sequenced before the value
14095     /// computation of the expression, such as ++n in C++.
14096     UK_ModAsValue,
14097 
14098     /// A modification of an object which is not sequenced before the value
14099     /// computation of the expression, such as n++.
14100     UK_ModAsSideEffect,
14101 
14102     UK_Count = UK_ModAsSideEffect + 1
14103   };
14104 
14105   /// Bundle together a sequencing region and the expression corresponding
14106   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14107   struct Usage {
14108     const Expr *UsageExpr;
14109     SequenceTree::Seq Seq;
14110 
14111     Usage() : UsageExpr(nullptr) {}
14112   };
14113 
14114   struct UsageInfo {
14115     Usage Uses[UK_Count];
14116 
14117     /// Have we issued a diagnostic for this object already?
14118     bool Diagnosed;
14119 
14120     UsageInfo() : Diagnosed(false) {}
14121   };
14122   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14123 
14124   Sema &SemaRef;
14125 
14126   /// Sequenced regions within the expression.
14127   SequenceTree Tree;
14128 
14129   /// Declaration modifications and references which we have seen.
14130   UsageInfoMap UsageMap;
14131 
14132   /// The region we are currently within.
14133   SequenceTree::Seq Region;
14134 
14135   /// Filled in with declarations which were modified as a side-effect
14136   /// (that is, post-increment operations).
14137   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14138 
14139   /// Expressions to check later. We defer checking these to reduce
14140   /// stack usage.
14141   SmallVectorImpl<const Expr *> &WorkList;
14142 
14143   /// RAII object wrapping the visitation of a sequenced subexpression of an
14144   /// expression. At the end of this process, the side-effects of the evaluation
14145   /// become sequenced with respect to the value computation of the result, so
14146   /// we downgrade any UK_ModAsSideEffect within the evaluation to
14147   /// UK_ModAsValue.
14148   struct SequencedSubexpression {
14149     SequencedSubexpression(SequenceChecker &Self)
14150       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14151       Self.ModAsSideEffect = &ModAsSideEffect;
14152     }
14153 
14154     ~SequencedSubexpression() {
14155       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14156         // Add a new usage with usage kind UK_ModAsValue, and then restore
14157         // the previous usage with UK_ModAsSideEffect (thus clearing it if
14158         // the previous one was empty).
14159         UsageInfo &UI = Self.UsageMap[M.first];
14160         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14161         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14162         SideEffectUsage = M.second;
14163       }
14164       Self.ModAsSideEffect = OldModAsSideEffect;
14165     }
14166 
14167     SequenceChecker &Self;
14168     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14169     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14170   };
14171 
14172   /// RAII object wrapping the visitation of a subexpression which we might
14173   /// choose to evaluate as a constant. If any subexpression is evaluated and
14174   /// found to be non-constant, this allows us to suppress the evaluation of
14175   /// the outer expression.
14176   class EvaluationTracker {
14177   public:
14178     EvaluationTracker(SequenceChecker &Self)
14179         : Self(Self), Prev(Self.EvalTracker) {
14180       Self.EvalTracker = this;
14181     }
14182 
14183     ~EvaluationTracker() {
14184       Self.EvalTracker = Prev;
14185       if (Prev)
14186         Prev->EvalOK &= EvalOK;
14187     }
14188 
14189     bool evaluate(const Expr *E, bool &Result) {
14190       if (!EvalOK || E->isValueDependent())
14191         return false;
14192       EvalOK = E->EvaluateAsBooleanCondition(
14193           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
14194       return EvalOK;
14195     }
14196 
14197   private:
14198     SequenceChecker &Self;
14199     EvaluationTracker *Prev;
14200     bool EvalOK = true;
14201   } *EvalTracker = nullptr;
14202 
14203   /// Find the object which is produced by the specified expression,
14204   /// if any.
14205   Object getObject(const Expr *E, bool Mod) const {
14206     E = E->IgnoreParenCasts();
14207     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14208       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14209         return getObject(UO->getSubExpr(), Mod);
14210     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14211       if (BO->getOpcode() == BO_Comma)
14212         return getObject(BO->getRHS(), Mod);
14213       if (Mod && BO->isAssignmentOp())
14214         return getObject(BO->getLHS(), Mod);
14215     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14216       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14217       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14218         return ME->getMemberDecl();
14219     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14220       // FIXME: If this is a reference, map through to its value.
14221       return DRE->getDecl();
14222     return nullptr;
14223   }
14224 
14225   /// Note that an object \p O was modified or used by an expression
14226   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14227   /// the object \p O as obtained via the \p UsageMap.
14228   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14229     // Get the old usage for the given object and usage kind.
14230     Usage &U = UI.Uses[UK];
14231     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14232       // If we have a modification as side effect and are in a sequenced
14233       // subexpression, save the old Usage so that we can restore it later
14234       // in SequencedSubexpression::~SequencedSubexpression.
14235       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14236         ModAsSideEffect->push_back(std::make_pair(O, U));
14237       // Then record the new usage with the current sequencing region.
14238       U.UsageExpr = UsageExpr;
14239       U.Seq = Region;
14240     }
14241   }
14242 
14243   /// Check whether a modification or use of an object \p O in an expression
14244   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14245   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14246   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14247   /// usage and false we are checking for a mod-use unsequenced usage.
14248   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14249                   UsageKind OtherKind, bool IsModMod) {
14250     if (UI.Diagnosed)
14251       return;
14252 
14253     const Usage &U = UI.Uses[OtherKind];
14254     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14255       return;
14256 
14257     const Expr *Mod = U.UsageExpr;
14258     const Expr *ModOrUse = UsageExpr;
14259     if (OtherKind == UK_Use)
14260       std::swap(Mod, ModOrUse);
14261 
14262     SemaRef.DiagRuntimeBehavior(
14263         Mod->getExprLoc(), {Mod, ModOrUse},
14264         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14265                                : diag::warn_unsequenced_mod_use)
14266             << O << SourceRange(ModOrUse->getExprLoc()));
14267     UI.Diagnosed = true;
14268   }
14269 
14270   // A note on note{Pre, Post}{Use, Mod}:
14271   //
14272   // (It helps to follow the algorithm with an expression such as
14273   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14274   //  operations before C++17 and both are well-defined in C++17).
14275   //
14276   // When visiting a node which uses/modify an object we first call notePreUse
14277   // or notePreMod before visiting its sub-expression(s). At this point the
14278   // children of the current node have not yet been visited and so the eventual
14279   // uses/modifications resulting from the children of the current node have not
14280   // been recorded yet.
14281   //
14282   // We then visit the children of the current node. After that notePostUse or
14283   // notePostMod is called. These will 1) detect an unsequenced modification
14284   // as side effect (as in "k++ + k") and 2) add a new usage with the
14285   // appropriate usage kind.
14286   //
14287   // We also have to be careful that some operation sequences modification as
14288   // side effect as well (for example: || or ,). To account for this we wrap
14289   // the visitation of such a sub-expression (for example: the LHS of || or ,)
14290   // with SequencedSubexpression. SequencedSubexpression is an RAII object
14291   // which record usages which are modifications as side effect, and then
14292   // downgrade them (or more accurately restore the previous usage which was a
14293   // modification as side effect) when exiting the scope of the sequenced
14294   // subexpression.
14295 
14296   void notePreUse(Object O, const Expr *UseExpr) {
14297     UsageInfo &UI = UsageMap[O];
14298     // Uses conflict with other modifications.
14299     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14300   }
14301 
14302   void notePostUse(Object O, const Expr *UseExpr) {
14303     UsageInfo &UI = UsageMap[O];
14304     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14305                /*IsModMod=*/false);
14306     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14307   }
14308 
14309   void notePreMod(Object O, const Expr *ModExpr) {
14310     UsageInfo &UI = UsageMap[O];
14311     // Modifications conflict with other modifications and with uses.
14312     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14313     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14314   }
14315 
14316   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14317     UsageInfo &UI = UsageMap[O];
14318     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14319                /*IsModMod=*/true);
14320     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14321   }
14322 
14323 public:
14324   SequenceChecker(Sema &S, const Expr *E,
14325                   SmallVectorImpl<const Expr *> &WorkList)
14326       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14327     Visit(E);
14328     // Silence a -Wunused-private-field since WorkList is now unused.
14329     // TODO: Evaluate if it can be used, and if not remove it.
14330     (void)this->WorkList;
14331   }
14332 
14333   void VisitStmt(const Stmt *S) {
14334     // Skip all statements which aren't expressions for now.
14335   }
14336 
14337   void VisitExpr(const Expr *E) {
14338     // By default, just recurse to evaluated subexpressions.
14339     Base::VisitStmt(E);
14340   }
14341 
14342   void VisitCastExpr(const CastExpr *E) {
14343     Object O = Object();
14344     if (E->getCastKind() == CK_LValueToRValue)
14345       O = getObject(E->getSubExpr(), false);
14346 
14347     if (O)
14348       notePreUse(O, E);
14349     VisitExpr(E);
14350     if (O)
14351       notePostUse(O, E);
14352   }
14353 
14354   void VisitSequencedExpressions(const Expr *SequencedBefore,
14355                                  const Expr *SequencedAfter) {
14356     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14357     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14358     SequenceTree::Seq OldRegion = Region;
14359 
14360     {
14361       SequencedSubexpression SeqBefore(*this);
14362       Region = BeforeRegion;
14363       Visit(SequencedBefore);
14364     }
14365 
14366     Region = AfterRegion;
14367     Visit(SequencedAfter);
14368 
14369     Region = OldRegion;
14370 
14371     Tree.merge(BeforeRegion);
14372     Tree.merge(AfterRegion);
14373   }
14374 
14375   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14376     // C++17 [expr.sub]p1:
14377     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14378     //   expression E1 is sequenced before the expression E2.
14379     if (SemaRef.getLangOpts().CPlusPlus17)
14380       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14381     else {
14382       Visit(ASE->getLHS());
14383       Visit(ASE->getRHS());
14384     }
14385   }
14386 
14387   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14388   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14389   void VisitBinPtrMem(const BinaryOperator *BO) {
14390     // C++17 [expr.mptr.oper]p4:
14391     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14392     //  the expression E1 is sequenced before the expression E2.
14393     if (SemaRef.getLangOpts().CPlusPlus17)
14394       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14395     else {
14396       Visit(BO->getLHS());
14397       Visit(BO->getRHS());
14398     }
14399   }
14400 
14401   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14402   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14403   void VisitBinShlShr(const BinaryOperator *BO) {
14404     // C++17 [expr.shift]p4:
14405     //  The expression E1 is sequenced before the expression E2.
14406     if (SemaRef.getLangOpts().CPlusPlus17)
14407       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14408     else {
14409       Visit(BO->getLHS());
14410       Visit(BO->getRHS());
14411     }
14412   }
14413 
14414   void VisitBinComma(const BinaryOperator *BO) {
14415     // C++11 [expr.comma]p1:
14416     //   Every value computation and side effect associated with the left
14417     //   expression is sequenced before every value computation and side
14418     //   effect associated with the right expression.
14419     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14420   }
14421 
14422   void VisitBinAssign(const BinaryOperator *BO) {
14423     SequenceTree::Seq RHSRegion;
14424     SequenceTree::Seq LHSRegion;
14425     if (SemaRef.getLangOpts().CPlusPlus17) {
14426       RHSRegion = Tree.allocate(Region);
14427       LHSRegion = Tree.allocate(Region);
14428     } else {
14429       RHSRegion = Region;
14430       LHSRegion = Region;
14431     }
14432     SequenceTree::Seq OldRegion = Region;
14433 
14434     // C++11 [expr.ass]p1:
14435     //  [...] the assignment is sequenced after the value computation
14436     //  of the right and left operands, [...]
14437     //
14438     // so check it before inspecting the operands and update the
14439     // map afterwards.
14440     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14441     if (O)
14442       notePreMod(O, BO);
14443 
14444     if (SemaRef.getLangOpts().CPlusPlus17) {
14445       // C++17 [expr.ass]p1:
14446       //  [...] The right operand is sequenced before the left operand. [...]
14447       {
14448         SequencedSubexpression SeqBefore(*this);
14449         Region = RHSRegion;
14450         Visit(BO->getRHS());
14451       }
14452 
14453       Region = LHSRegion;
14454       Visit(BO->getLHS());
14455 
14456       if (O && isa<CompoundAssignOperator>(BO))
14457         notePostUse(O, BO);
14458 
14459     } else {
14460       // C++11 does not specify any sequencing between the LHS and RHS.
14461       Region = LHSRegion;
14462       Visit(BO->getLHS());
14463 
14464       if (O && isa<CompoundAssignOperator>(BO))
14465         notePostUse(O, BO);
14466 
14467       Region = RHSRegion;
14468       Visit(BO->getRHS());
14469     }
14470 
14471     // C++11 [expr.ass]p1:
14472     //  the assignment is sequenced [...] before the value computation of the
14473     //  assignment expression.
14474     // C11 6.5.16/3 has no such rule.
14475     Region = OldRegion;
14476     if (O)
14477       notePostMod(O, BO,
14478                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14479                                                   : UK_ModAsSideEffect);
14480     if (SemaRef.getLangOpts().CPlusPlus17) {
14481       Tree.merge(RHSRegion);
14482       Tree.merge(LHSRegion);
14483     }
14484   }
14485 
14486   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14487     VisitBinAssign(CAO);
14488   }
14489 
14490   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14491   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14492   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14493     Object O = getObject(UO->getSubExpr(), true);
14494     if (!O)
14495       return VisitExpr(UO);
14496 
14497     notePreMod(O, UO);
14498     Visit(UO->getSubExpr());
14499     // C++11 [expr.pre.incr]p1:
14500     //   the expression ++x is equivalent to x+=1
14501     notePostMod(O, UO,
14502                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14503                                                 : UK_ModAsSideEffect);
14504   }
14505 
14506   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14507   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14508   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14509     Object O = getObject(UO->getSubExpr(), true);
14510     if (!O)
14511       return VisitExpr(UO);
14512 
14513     notePreMod(O, UO);
14514     Visit(UO->getSubExpr());
14515     notePostMod(O, UO, UK_ModAsSideEffect);
14516   }
14517 
14518   void VisitBinLOr(const BinaryOperator *BO) {
14519     // C++11 [expr.log.or]p2:
14520     //  If the second expression is evaluated, every value computation and
14521     //  side effect associated with the first expression is sequenced before
14522     //  every value computation and side effect associated with the
14523     //  second expression.
14524     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14525     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14526     SequenceTree::Seq OldRegion = Region;
14527 
14528     EvaluationTracker Eval(*this);
14529     {
14530       SequencedSubexpression Sequenced(*this);
14531       Region = LHSRegion;
14532       Visit(BO->getLHS());
14533     }
14534 
14535     // C++11 [expr.log.or]p1:
14536     //  [...] the second operand is not evaluated if the first operand
14537     //  evaluates to true.
14538     bool EvalResult = false;
14539     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14540     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14541     if (ShouldVisitRHS) {
14542       Region = RHSRegion;
14543       Visit(BO->getRHS());
14544     }
14545 
14546     Region = OldRegion;
14547     Tree.merge(LHSRegion);
14548     Tree.merge(RHSRegion);
14549   }
14550 
14551   void VisitBinLAnd(const BinaryOperator *BO) {
14552     // C++11 [expr.log.and]p2:
14553     //  If the second expression is evaluated, every value computation and
14554     //  side effect associated with the first expression is sequenced before
14555     //  every value computation and side effect associated with the
14556     //  second expression.
14557     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14558     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14559     SequenceTree::Seq OldRegion = Region;
14560 
14561     EvaluationTracker Eval(*this);
14562     {
14563       SequencedSubexpression Sequenced(*this);
14564       Region = LHSRegion;
14565       Visit(BO->getLHS());
14566     }
14567 
14568     // C++11 [expr.log.and]p1:
14569     //  [...] the second operand is not evaluated if the first operand is false.
14570     bool EvalResult = false;
14571     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14572     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14573     if (ShouldVisitRHS) {
14574       Region = RHSRegion;
14575       Visit(BO->getRHS());
14576     }
14577 
14578     Region = OldRegion;
14579     Tree.merge(LHSRegion);
14580     Tree.merge(RHSRegion);
14581   }
14582 
14583   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14584     // C++11 [expr.cond]p1:
14585     //  [...] Every value computation and side effect associated with the first
14586     //  expression is sequenced before every value computation and side effect
14587     //  associated with the second or third expression.
14588     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14589 
14590     // No sequencing is specified between the true and false expression.
14591     // However since exactly one of both is going to be evaluated we can
14592     // consider them to be sequenced. This is needed to avoid warning on
14593     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14594     // both the true and false expressions because we can't evaluate x.
14595     // This will still allow us to detect an expression like (pre C++17)
14596     // "(x ? y += 1 : y += 2) = y".
14597     //
14598     // We don't wrap the visitation of the true and false expression with
14599     // SequencedSubexpression because we don't want to downgrade modifications
14600     // as side effect in the true and false expressions after the visition
14601     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14602     // not warn between the two "y++", but we should warn between the "y++"
14603     // and the "y".
14604     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14605     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14606     SequenceTree::Seq OldRegion = Region;
14607 
14608     EvaluationTracker Eval(*this);
14609     {
14610       SequencedSubexpression Sequenced(*this);
14611       Region = ConditionRegion;
14612       Visit(CO->getCond());
14613     }
14614 
14615     // C++11 [expr.cond]p1:
14616     // [...] The first expression is contextually converted to bool (Clause 4).
14617     // It is evaluated and if it is true, the result of the conditional
14618     // expression is the value of the second expression, otherwise that of the
14619     // third expression. Only one of the second and third expressions is
14620     // evaluated. [...]
14621     bool EvalResult = false;
14622     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14623     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14624     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14625     if (ShouldVisitTrueExpr) {
14626       Region = TrueRegion;
14627       Visit(CO->getTrueExpr());
14628     }
14629     if (ShouldVisitFalseExpr) {
14630       Region = FalseRegion;
14631       Visit(CO->getFalseExpr());
14632     }
14633 
14634     Region = OldRegion;
14635     Tree.merge(ConditionRegion);
14636     Tree.merge(TrueRegion);
14637     Tree.merge(FalseRegion);
14638   }
14639 
14640   void VisitCallExpr(const CallExpr *CE) {
14641     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14642 
14643     if (CE->isUnevaluatedBuiltinCall(Context))
14644       return;
14645 
14646     // C++11 [intro.execution]p15:
14647     //   When calling a function [...], every value computation and side effect
14648     //   associated with any argument expression, or with the postfix expression
14649     //   designating the called function, is sequenced before execution of every
14650     //   expression or statement in the body of the function [and thus before
14651     //   the value computation of its result].
14652     SequencedSubexpression Sequenced(*this);
14653     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14654       // C++17 [expr.call]p5
14655       //   The postfix-expression is sequenced before each expression in the
14656       //   expression-list and any default argument. [...]
14657       SequenceTree::Seq CalleeRegion;
14658       SequenceTree::Seq OtherRegion;
14659       if (SemaRef.getLangOpts().CPlusPlus17) {
14660         CalleeRegion = Tree.allocate(Region);
14661         OtherRegion = Tree.allocate(Region);
14662       } else {
14663         CalleeRegion = Region;
14664         OtherRegion = Region;
14665       }
14666       SequenceTree::Seq OldRegion = Region;
14667 
14668       // Visit the callee expression first.
14669       Region = CalleeRegion;
14670       if (SemaRef.getLangOpts().CPlusPlus17) {
14671         SequencedSubexpression Sequenced(*this);
14672         Visit(CE->getCallee());
14673       } else {
14674         Visit(CE->getCallee());
14675       }
14676 
14677       // Then visit the argument expressions.
14678       Region = OtherRegion;
14679       for (const Expr *Argument : CE->arguments())
14680         Visit(Argument);
14681 
14682       Region = OldRegion;
14683       if (SemaRef.getLangOpts().CPlusPlus17) {
14684         Tree.merge(CalleeRegion);
14685         Tree.merge(OtherRegion);
14686       }
14687     });
14688   }
14689 
14690   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14691     // C++17 [over.match.oper]p2:
14692     //   [...] the operator notation is first transformed to the equivalent
14693     //   function-call notation as summarized in Table 12 (where @ denotes one
14694     //   of the operators covered in the specified subclause). However, the
14695     //   operands are sequenced in the order prescribed for the built-in
14696     //   operator (Clause 8).
14697     //
14698     // From the above only overloaded binary operators and overloaded call
14699     // operators have sequencing rules in C++17 that we need to handle
14700     // separately.
14701     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14702         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14703       return VisitCallExpr(CXXOCE);
14704 
14705     enum {
14706       NoSequencing,
14707       LHSBeforeRHS,
14708       RHSBeforeLHS,
14709       LHSBeforeRest
14710     } SequencingKind;
14711     switch (CXXOCE->getOperator()) {
14712     case OO_Equal:
14713     case OO_PlusEqual:
14714     case OO_MinusEqual:
14715     case OO_StarEqual:
14716     case OO_SlashEqual:
14717     case OO_PercentEqual:
14718     case OO_CaretEqual:
14719     case OO_AmpEqual:
14720     case OO_PipeEqual:
14721     case OO_LessLessEqual:
14722     case OO_GreaterGreaterEqual:
14723       SequencingKind = RHSBeforeLHS;
14724       break;
14725 
14726     case OO_LessLess:
14727     case OO_GreaterGreater:
14728     case OO_AmpAmp:
14729     case OO_PipePipe:
14730     case OO_Comma:
14731     case OO_ArrowStar:
14732     case OO_Subscript:
14733       SequencingKind = LHSBeforeRHS;
14734       break;
14735 
14736     case OO_Call:
14737       SequencingKind = LHSBeforeRest;
14738       break;
14739 
14740     default:
14741       SequencingKind = NoSequencing;
14742       break;
14743     }
14744 
14745     if (SequencingKind == NoSequencing)
14746       return VisitCallExpr(CXXOCE);
14747 
14748     // This is a call, so all subexpressions are sequenced before the result.
14749     SequencedSubexpression Sequenced(*this);
14750 
14751     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14752       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14753              "Should only get there with C++17 and above!");
14754       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14755              "Should only get there with an overloaded binary operator"
14756              " or an overloaded call operator!");
14757 
14758       if (SequencingKind == LHSBeforeRest) {
14759         assert(CXXOCE->getOperator() == OO_Call &&
14760                "We should only have an overloaded call operator here!");
14761 
14762         // This is very similar to VisitCallExpr, except that we only have the
14763         // C++17 case. The postfix-expression is the first argument of the
14764         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14765         // are in the following arguments.
14766         //
14767         // Note that we intentionally do not visit the callee expression since
14768         // it is just a decayed reference to a function.
14769         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14770         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14771         SequenceTree::Seq OldRegion = Region;
14772 
14773         assert(CXXOCE->getNumArgs() >= 1 &&
14774                "An overloaded call operator must have at least one argument"
14775                " for the postfix-expression!");
14776         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14777         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14778                                           CXXOCE->getNumArgs() - 1);
14779 
14780         // Visit the postfix-expression first.
14781         {
14782           Region = PostfixExprRegion;
14783           SequencedSubexpression Sequenced(*this);
14784           Visit(PostfixExpr);
14785         }
14786 
14787         // Then visit the argument expressions.
14788         Region = ArgsRegion;
14789         for (const Expr *Arg : Args)
14790           Visit(Arg);
14791 
14792         Region = OldRegion;
14793         Tree.merge(PostfixExprRegion);
14794         Tree.merge(ArgsRegion);
14795       } else {
14796         assert(CXXOCE->getNumArgs() == 2 &&
14797                "Should only have two arguments here!");
14798         assert((SequencingKind == LHSBeforeRHS ||
14799                 SequencingKind == RHSBeforeLHS) &&
14800                "Unexpected sequencing kind!");
14801 
14802         // We do not visit the callee expression since it is just a decayed
14803         // reference to a function.
14804         const Expr *E1 = CXXOCE->getArg(0);
14805         const Expr *E2 = CXXOCE->getArg(1);
14806         if (SequencingKind == RHSBeforeLHS)
14807           std::swap(E1, E2);
14808 
14809         return VisitSequencedExpressions(E1, E2);
14810       }
14811     });
14812   }
14813 
14814   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14815     // This is a call, so all subexpressions are sequenced before the result.
14816     SequencedSubexpression Sequenced(*this);
14817 
14818     if (!CCE->isListInitialization())
14819       return VisitExpr(CCE);
14820 
14821     // In C++11, list initializations are sequenced.
14822     SmallVector<SequenceTree::Seq, 32> Elts;
14823     SequenceTree::Seq Parent = Region;
14824     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14825                                               E = CCE->arg_end();
14826          I != E; ++I) {
14827       Region = Tree.allocate(Parent);
14828       Elts.push_back(Region);
14829       Visit(*I);
14830     }
14831 
14832     // Forget that the initializers are sequenced.
14833     Region = Parent;
14834     for (unsigned I = 0; I < Elts.size(); ++I)
14835       Tree.merge(Elts[I]);
14836   }
14837 
14838   void VisitInitListExpr(const InitListExpr *ILE) {
14839     if (!SemaRef.getLangOpts().CPlusPlus11)
14840       return VisitExpr(ILE);
14841 
14842     // In C++11, list initializations are sequenced.
14843     SmallVector<SequenceTree::Seq, 32> Elts;
14844     SequenceTree::Seq Parent = Region;
14845     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14846       const Expr *E = ILE->getInit(I);
14847       if (!E)
14848         continue;
14849       Region = Tree.allocate(Parent);
14850       Elts.push_back(Region);
14851       Visit(E);
14852     }
14853 
14854     // Forget that the initializers are sequenced.
14855     Region = Parent;
14856     for (unsigned I = 0; I < Elts.size(); ++I)
14857       Tree.merge(Elts[I]);
14858   }
14859 };
14860 
14861 } // namespace
14862 
14863 void Sema::CheckUnsequencedOperations(const Expr *E) {
14864   SmallVector<const Expr *, 8> WorkList;
14865   WorkList.push_back(E);
14866   while (!WorkList.empty()) {
14867     const Expr *Item = WorkList.pop_back_val();
14868     SequenceChecker(*this, Item, WorkList);
14869   }
14870 }
14871 
14872 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14873                               bool IsConstexpr) {
14874   llvm::SaveAndRestore<bool> ConstantContext(
14875       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14876   CheckImplicitConversions(E, CheckLoc);
14877   if (!E->isInstantiationDependent())
14878     CheckUnsequencedOperations(E);
14879   if (!IsConstexpr && !E->isValueDependent())
14880     CheckForIntOverflow(E);
14881   DiagnoseMisalignedMembers();
14882 }
14883 
14884 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14885                                        FieldDecl *BitField,
14886                                        Expr *Init) {
14887   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14888 }
14889 
14890 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14891                                          SourceLocation Loc) {
14892   if (!PType->isVariablyModifiedType())
14893     return;
14894   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14895     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14896     return;
14897   }
14898   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14899     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14900     return;
14901   }
14902   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14903     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14904     return;
14905   }
14906 
14907   const ArrayType *AT = S.Context.getAsArrayType(PType);
14908   if (!AT)
14909     return;
14910 
14911   if (AT->getSizeModifier() != ArrayType::Star) {
14912     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14913     return;
14914   }
14915 
14916   S.Diag(Loc, diag::err_array_star_in_function_definition);
14917 }
14918 
14919 /// CheckParmsForFunctionDef - Check that the parameters of the given
14920 /// function are appropriate for the definition of a function. This
14921 /// takes care of any checks that cannot be performed on the
14922 /// declaration itself, e.g., that the types of each of the function
14923 /// parameters are complete.
14924 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14925                                     bool CheckParameterNames) {
14926   bool HasInvalidParm = false;
14927   for (ParmVarDecl *Param : Parameters) {
14928     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14929     // function declarator that is part of a function definition of
14930     // that function shall not have incomplete type.
14931     //
14932     // This is also C++ [dcl.fct]p6.
14933     if (!Param->isInvalidDecl() &&
14934         RequireCompleteType(Param->getLocation(), Param->getType(),
14935                             diag::err_typecheck_decl_incomplete_type)) {
14936       Param->setInvalidDecl();
14937       HasInvalidParm = true;
14938     }
14939 
14940     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14941     // declaration of each parameter shall include an identifier.
14942     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14943         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14944       // Diagnose this as an extension in C17 and earlier.
14945       if (!getLangOpts().C2x)
14946         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14947     }
14948 
14949     // C99 6.7.5.3p12:
14950     //   If the function declarator is not part of a definition of that
14951     //   function, parameters may have incomplete type and may use the [*]
14952     //   notation in their sequences of declarator specifiers to specify
14953     //   variable length array types.
14954     QualType PType = Param->getOriginalType();
14955     // FIXME: This diagnostic should point the '[*]' if source-location
14956     // information is added for it.
14957     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14958 
14959     // If the parameter is a c++ class type and it has to be destructed in the
14960     // callee function, declare the destructor so that it can be called by the
14961     // callee function. Do not perform any direct access check on the dtor here.
14962     if (!Param->isInvalidDecl()) {
14963       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14964         if (!ClassDecl->isInvalidDecl() &&
14965             !ClassDecl->hasIrrelevantDestructor() &&
14966             !ClassDecl->isDependentContext() &&
14967             ClassDecl->isParamDestroyedInCallee()) {
14968           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14969           MarkFunctionReferenced(Param->getLocation(), Destructor);
14970           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14971         }
14972       }
14973     }
14974 
14975     // Parameters with the pass_object_size attribute only need to be marked
14976     // constant at function definitions. Because we lack information about
14977     // whether we're on a declaration or definition when we're instantiating the
14978     // attribute, we need to check for constness here.
14979     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14980       if (!Param->getType().isConstQualified())
14981         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14982             << Attr->getSpelling() << 1;
14983 
14984     // Check for parameter names shadowing fields from the class.
14985     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14986       // The owning context for the parameter should be the function, but we
14987       // want to see if this function's declaration context is a record.
14988       DeclContext *DC = Param->getDeclContext();
14989       if (DC && DC->isFunctionOrMethod()) {
14990         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14991           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14992                                      RD, /*DeclIsField*/ false);
14993       }
14994     }
14995   }
14996 
14997   return HasInvalidParm;
14998 }
14999 
15000 Optional<std::pair<CharUnits, CharUnits>>
15001 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
15002 
15003 /// Compute the alignment and offset of the base class object given the
15004 /// derived-to-base cast expression and the alignment and offset of the derived
15005 /// class object.
15006 static std::pair<CharUnits, CharUnits>
15007 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
15008                                    CharUnits BaseAlignment, CharUnits Offset,
15009                                    ASTContext &Ctx) {
15010   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15011        ++PathI) {
15012     const CXXBaseSpecifier *Base = *PathI;
15013     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15014     if (Base->isVirtual()) {
15015       // The complete object may have a lower alignment than the non-virtual
15016       // alignment of the base, in which case the base may be misaligned. Choose
15017       // the smaller of the non-virtual alignment and BaseAlignment, which is a
15018       // conservative lower bound of the complete object alignment.
15019       CharUnits NonVirtualAlignment =
15020           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
15021       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15022       Offset = CharUnits::Zero();
15023     } else {
15024       const ASTRecordLayout &RL =
15025           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
15026       Offset += RL.getBaseClassOffset(BaseDecl);
15027     }
15028     DerivedType = Base->getType();
15029   }
15030 
15031   return std::make_pair(BaseAlignment, Offset);
15032 }
15033 
15034 /// Compute the alignment and offset of a binary additive operator.
15035 static Optional<std::pair<CharUnits, CharUnits>>
15036 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
15037                                      bool IsSub, ASTContext &Ctx) {
15038   QualType PointeeType = PtrE->getType()->getPointeeType();
15039 
15040   if (!PointeeType->isConstantSizeType())
15041     return llvm::None;
15042 
15043   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
15044 
15045   if (!P)
15046     return llvm::None;
15047 
15048   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
15049   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15050     CharUnits Offset = EltSize * IdxRes->getExtValue();
15051     if (IsSub)
15052       Offset = -Offset;
15053     return std::make_pair(P->first, P->second + Offset);
15054   }
15055 
15056   // If the integer expression isn't a constant expression, compute the lower
15057   // bound of the alignment using the alignment and offset of the pointer
15058   // expression and the element size.
15059   return std::make_pair(
15060       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15061       CharUnits::Zero());
15062 }
15063 
15064 /// This helper function takes an lvalue expression and returns the alignment of
15065 /// a VarDecl and a constant offset from the VarDecl.
15066 Optional<std::pair<CharUnits, CharUnits>>
15067 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
15068   E = E->IgnoreParens();
15069   switch (E->getStmtClass()) {
15070   default:
15071     break;
15072   case Stmt::CStyleCastExprClass:
15073   case Stmt::CXXStaticCastExprClass:
15074   case Stmt::ImplicitCastExprClass: {
15075     auto *CE = cast<CastExpr>(E);
15076     const Expr *From = CE->getSubExpr();
15077     switch (CE->getCastKind()) {
15078     default:
15079       break;
15080     case CK_NoOp:
15081       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15082     case CK_UncheckedDerivedToBase:
15083     case CK_DerivedToBase: {
15084       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15085       if (!P)
15086         break;
15087       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15088                                                 P->second, Ctx);
15089     }
15090     }
15091     break;
15092   }
15093   case Stmt::ArraySubscriptExprClass: {
15094     auto *ASE = cast<ArraySubscriptExpr>(E);
15095     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
15096                                                 false, Ctx);
15097   }
15098   case Stmt::DeclRefExprClass: {
15099     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15100       // FIXME: If VD is captured by copy or is an escaping __block variable,
15101       // use the alignment of VD's type.
15102       if (!VD->getType()->isReferenceType())
15103         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15104       if (VD->hasInit())
15105         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15106     }
15107     break;
15108   }
15109   case Stmt::MemberExprClass: {
15110     auto *ME = cast<MemberExpr>(E);
15111     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15112     if (!FD || FD->getType()->isReferenceType() ||
15113         FD->getParent()->isInvalidDecl())
15114       break;
15115     Optional<std::pair<CharUnits, CharUnits>> P;
15116     if (ME->isArrow())
15117       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15118     else
15119       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15120     if (!P)
15121       break;
15122     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15123     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15124     return std::make_pair(P->first,
15125                           P->second + CharUnits::fromQuantity(Offset));
15126   }
15127   case Stmt::UnaryOperatorClass: {
15128     auto *UO = cast<UnaryOperator>(E);
15129     switch (UO->getOpcode()) {
15130     default:
15131       break;
15132     case UO_Deref:
15133       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
15134     }
15135     break;
15136   }
15137   case Stmt::BinaryOperatorClass: {
15138     auto *BO = cast<BinaryOperator>(E);
15139     auto Opcode = BO->getOpcode();
15140     switch (Opcode) {
15141     default:
15142       break;
15143     case BO_Comma:
15144       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
15145     }
15146     break;
15147   }
15148   }
15149   return llvm::None;
15150 }
15151 
15152 /// This helper function takes a pointer expression and returns the alignment of
15153 /// a VarDecl and a constant offset from the VarDecl.
15154 Optional<std::pair<CharUnits, CharUnits>>
15155 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
15156   E = E->IgnoreParens();
15157   switch (E->getStmtClass()) {
15158   default:
15159     break;
15160   case Stmt::CStyleCastExprClass:
15161   case Stmt::CXXStaticCastExprClass:
15162   case Stmt::ImplicitCastExprClass: {
15163     auto *CE = cast<CastExpr>(E);
15164     const Expr *From = CE->getSubExpr();
15165     switch (CE->getCastKind()) {
15166     default:
15167       break;
15168     case CK_NoOp:
15169       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15170     case CK_ArrayToPointerDecay:
15171       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15172     case CK_UncheckedDerivedToBase:
15173     case CK_DerivedToBase: {
15174       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15175       if (!P)
15176         break;
15177       return getDerivedToBaseAlignmentAndOffset(
15178           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15179     }
15180     }
15181     break;
15182   }
15183   case Stmt::CXXThisExprClass: {
15184     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15185     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
15186     return std::make_pair(Alignment, CharUnits::Zero());
15187   }
15188   case Stmt::UnaryOperatorClass: {
15189     auto *UO = cast<UnaryOperator>(E);
15190     if (UO->getOpcode() == UO_AddrOf)
15191       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
15192     break;
15193   }
15194   case Stmt::BinaryOperatorClass: {
15195     auto *BO = cast<BinaryOperator>(E);
15196     auto Opcode = BO->getOpcode();
15197     switch (Opcode) {
15198     default:
15199       break;
15200     case BO_Add:
15201     case BO_Sub: {
15202       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15203       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15204         std::swap(LHS, RHS);
15205       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15206                                                   Ctx);
15207     }
15208     case BO_Comma:
15209       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15210     }
15211     break;
15212   }
15213   }
15214   return llvm::None;
15215 }
15216 
15217 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
15218   // See if we can compute the alignment of a VarDecl and an offset from it.
15219   Optional<std::pair<CharUnits, CharUnits>> P =
15220       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
15221 
15222   if (P)
15223     return P->first.alignmentAtOffset(P->second);
15224 
15225   // If that failed, return the type's alignment.
15226   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
15227 }
15228 
15229 /// CheckCastAlign - Implements -Wcast-align, which warns when a
15230 /// pointer cast increases the alignment requirements.
15231 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
15232   // This is actually a lot of work to potentially be doing on every
15233   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15234   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15235     return;
15236 
15237   // Ignore dependent types.
15238   if (T->isDependentType() || Op->getType()->isDependentType())
15239     return;
15240 
15241   // Require that the destination be a pointer type.
15242   const PointerType *DestPtr = T->getAs<PointerType>();
15243   if (!DestPtr) return;
15244 
15245   // If the destination has alignment 1, we're done.
15246   QualType DestPointee = DestPtr->getPointeeType();
15247   if (DestPointee->isIncompleteType()) return;
15248   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15249   if (DestAlign.isOne()) return;
15250 
15251   // Require that the source be a pointer type.
15252   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15253   if (!SrcPtr) return;
15254   QualType SrcPointee = SrcPtr->getPointeeType();
15255 
15256   // Explicitly allow casts from cv void*.  We already implicitly
15257   // allowed casts to cv void*, since they have alignment 1.
15258   // Also allow casts involving incomplete types, which implicitly
15259   // includes 'void'.
15260   if (SrcPointee->isIncompleteType()) return;
15261 
15262   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15263 
15264   if (SrcAlign >= DestAlign) return;
15265 
15266   Diag(TRange.getBegin(), diag::warn_cast_align)
15267     << Op->getType() << T
15268     << static_cast<unsigned>(SrcAlign.getQuantity())
15269     << static_cast<unsigned>(DestAlign.getQuantity())
15270     << TRange << Op->getSourceRange();
15271 }
15272 
15273 /// Check whether this array fits the idiom of a size-one tail padded
15274 /// array member of a struct.
15275 ///
15276 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
15277 /// commonly used to emulate flexible arrays in C89 code.
15278 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
15279                                     const NamedDecl *ND) {
15280   if (Size != 1 || !ND) return false;
15281 
15282   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
15283   if (!FD) return false;
15284 
15285   // Don't consider sizes resulting from macro expansions or template argument
15286   // substitution to form C89 tail-padded arrays.
15287 
15288   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
15289   while (TInfo) {
15290     TypeLoc TL = TInfo->getTypeLoc();
15291     // Look through typedefs.
15292     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
15293       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
15294       TInfo = TDL->getTypeSourceInfo();
15295       continue;
15296     }
15297     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
15298       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
15299       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
15300         return false;
15301     }
15302     break;
15303   }
15304 
15305   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
15306   if (!RD) return false;
15307   if (RD->isUnion()) return false;
15308   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15309     if (!CRD->isStandardLayout()) return false;
15310   }
15311 
15312   // See if this is the last field decl in the record.
15313   const Decl *D = FD;
15314   while ((D = D->getNextDeclInContext()))
15315     if (isa<FieldDecl>(D))
15316       return false;
15317   return true;
15318 }
15319 
15320 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15321                             const ArraySubscriptExpr *ASE,
15322                             bool AllowOnePastEnd, bool IndexNegated) {
15323   // Already diagnosed by the constant evaluator.
15324   if (isConstantEvaluated())
15325     return;
15326 
15327   IndexExpr = IndexExpr->IgnoreParenImpCasts();
15328   if (IndexExpr->isValueDependent())
15329     return;
15330 
15331   const Type *EffectiveType =
15332       BaseExpr->getType()->getPointeeOrArrayElementType();
15333   BaseExpr = BaseExpr->IgnoreParenCasts();
15334   const ConstantArrayType *ArrayTy =
15335       Context.getAsConstantArrayType(BaseExpr->getType());
15336 
15337   const Type *BaseType =
15338       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15339   bool IsUnboundedArray = (BaseType == nullptr);
15340   if (EffectiveType->isDependentType() ||
15341       (!IsUnboundedArray && BaseType->isDependentType()))
15342     return;
15343 
15344   Expr::EvalResult Result;
15345   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15346     return;
15347 
15348   llvm::APSInt index = Result.Val.getInt();
15349   if (IndexNegated) {
15350     index.setIsUnsigned(false);
15351     index = -index;
15352   }
15353 
15354   const NamedDecl *ND = nullptr;
15355   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15356     ND = DRE->getDecl();
15357   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
15358     ND = ME->getMemberDecl();
15359 
15360   if (IsUnboundedArray) {
15361     if (index.isUnsigned() || !index.isNegative()) {
15362       const auto &ASTC = getASTContext();
15363       unsigned AddrBits =
15364           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
15365               EffectiveType->getCanonicalTypeInternal()));
15366       if (index.getBitWidth() < AddrBits)
15367         index = index.zext(AddrBits);
15368       Optional<CharUnits> ElemCharUnits =
15369           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15370       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15371       // pointer) bounds-checking isn't meaningful.
15372       if (!ElemCharUnits)
15373         return;
15374       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15375       // If index has more active bits than address space, we already know
15376       // we have a bounds violation to warn about.  Otherwise, compute
15377       // address of (index + 1)th element, and warn about bounds violation
15378       // only if that address exceeds address space.
15379       if (index.getActiveBits() <= AddrBits) {
15380         bool Overflow;
15381         llvm::APInt Product(index);
15382         Product += 1;
15383         Product = Product.umul_ov(ElemBytes, Overflow);
15384         if (!Overflow && Product.getActiveBits() <= AddrBits)
15385           return;
15386       }
15387 
15388       // Need to compute max possible elements in address space, since that
15389       // is included in diag message.
15390       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15391       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15392       MaxElems += 1;
15393       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15394       MaxElems = MaxElems.udiv(ElemBytes);
15395 
15396       unsigned DiagID =
15397           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15398               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15399 
15400       // Diag message shows element size in bits and in "bytes" (platform-
15401       // dependent CharUnits)
15402       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15403                           PDiag(DiagID)
15404                               << toString(index, 10, true) << AddrBits
15405                               << (unsigned)ASTC.toBits(*ElemCharUnits)
15406                               << toString(ElemBytes, 10, false)
15407                               << toString(MaxElems, 10, false)
15408                               << (unsigned)MaxElems.getLimitedValue(~0U)
15409                               << IndexExpr->getSourceRange());
15410 
15411       if (!ND) {
15412         // Try harder to find a NamedDecl to point at in the note.
15413         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15414           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15415         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15416           ND = DRE->getDecl();
15417         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15418           ND = ME->getMemberDecl();
15419       }
15420 
15421       if (ND)
15422         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15423                             PDiag(diag::note_array_declared_here) << ND);
15424     }
15425     return;
15426   }
15427 
15428   if (index.isUnsigned() || !index.isNegative()) {
15429     // It is possible that the type of the base expression after
15430     // IgnoreParenCasts is incomplete, even though the type of the base
15431     // expression before IgnoreParenCasts is complete (see PR39746 for an
15432     // example). In this case we have no information about whether the array
15433     // access exceeds the array bounds. However we can still diagnose an array
15434     // access which precedes the array bounds.
15435     if (BaseType->isIncompleteType())
15436       return;
15437 
15438     llvm::APInt size = ArrayTy->getSize();
15439     if (!size.isStrictlyPositive())
15440       return;
15441 
15442     if (BaseType != EffectiveType) {
15443       // Make sure we're comparing apples to apples when comparing index to size
15444       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15445       uint64_t array_typesize = Context.getTypeSize(BaseType);
15446       // Handle ptrarith_typesize being zero, such as when casting to void*
15447       if (!ptrarith_typesize) ptrarith_typesize = 1;
15448       if (ptrarith_typesize != array_typesize) {
15449         // There's a cast to a different size type involved
15450         uint64_t ratio = array_typesize / ptrarith_typesize;
15451         // TODO: Be smarter about handling cases where array_typesize is not a
15452         // multiple of ptrarith_typesize
15453         if (ptrarith_typesize * ratio == array_typesize)
15454           size *= llvm::APInt(size.getBitWidth(), ratio);
15455       }
15456     }
15457 
15458     if (size.getBitWidth() > index.getBitWidth())
15459       index = index.zext(size.getBitWidth());
15460     else if (size.getBitWidth() < index.getBitWidth())
15461       size = size.zext(index.getBitWidth());
15462 
15463     // For array subscripting the index must be less than size, but for pointer
15464     // arithmetic also allow the index (offset) to be equal to size since
15465     // computing the next address after the end of the array is legal and
15466     // commonly done e.g. in C++ iterators and range-based for loops.
15467     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15468       return;
15469 
15470     // Also don't warn for arrays of size 1 which are members of some
15471     // structure. These are often used to approximate flexible arrays in C89
15472     // code.
15473     if (IsTailPaddedMemberArray(*this, size, ND))
15474       return;
15475 
15476     // Suppress the warning if the subscript expression (as identified by the
15477     // ']' location) and the index expression are both from macro expansions
15478     // within a system header.
15479     if (ASE) {
15480       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15481           ASE->getRBracketLoc());
15482       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15483         SourceLocation IndexLoc =
15484             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15485         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15486           return;
15487       }
15488     }
15489 
15490     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15491                           : diag::warn_ptr_arith_exceeds_bounds;
15492 
15493     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15494                         PDiag(DiagID) << toString(index, 10, true)
15495                                       << toString(size, 10, true)
15496                                       << (unsigned)size.getLimitedValue(~0U)
15497                                       << IndexExpr->getSourceRange());
15498   } else {
15499     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15500     if (!ASE) {
15501       DiagID = diag::warn_ptr_arith_precedes_bounds;
15502       if (index.isNegative()) index = -index;
15503     }
15504 
15505     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15506                         PDiag(DiagID) << toString(index, 10, true)
15507                                       << IndexExpr->getSourceRange());
15508   }
15509 
15510   if (!ND) {
15511     // Try harder to find a NamedDecl to point at in the note.
15512     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15513       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15514     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15515       ND = DRE->getDecl();
15516     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15517       ND = ME->getMemberDecl();
15518   }
15519 
15520   if (ND)
15521     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15522                         PDiag(diag::note_array_declared_here) << ND);
15523 }
15524 
15525 void Sema::CheckArrayAccess(const Expr *expr) {
15526   int AllowOnePastEnd = 0;
15527   while (expr) {
15528     expr = expr->IgnoreParenImpCasts();
15529     switch (expr->getStmtClass()) {
15530       case Stmt::ArraySubscriptExprClass: {
15531         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15532         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15533                          AllowOnePastEnd > 0);
15534         expr = ASE->getBase();
15535         break;
15536       }
15537       case Stmt::MemberExprClass: {
15538         expr = cast<MemberExpr>(expr)->getBase();
15539         break;
15540       }
15541       case Stmt::OMPArraySectionExprClass: {
15542         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15543         if (ASE->getLowerBound())
15544           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15545                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15546         return;
15547       }
15548       case Stmt::UnaryOperatorClass: {
15549         // Only unwrap the * and & unary operators
15550         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15551         expr = UO->getSubExpr();
15552         switch (UO->getOpcode()) {
15553           case UO_AddrOf:
15554             AllowOnePastEnd++;
15555             break;
15556           case UO_Deref:
15557             AllowOnePastEnd--;
15558             break;
15559           default:
15560             return;
15561         }
15562         break;
15563       }
15564       case Stmt::ConditionalOperatorClass: {
15565         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15566         if (const Expr *lhs = cond->getLHS())
15567           CheckArrayAccess(lhs);
15568         if (const Expr *rhs = cond->getRHS())
15569           CheckArrayAccess(rhs);
15570         return;
15571       }
15572       case Stmt::CXXOperatorCallExprClass: {
15573         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15574         for (const auto *Arg : OCE->arguments())
15575           CheckArrayAccess(Arg);
15576         return;
15577       }
15578       default:
15579         return;
15580     }
15581   }
15582 }
15583 
15584 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15585 
15586 namespace {
15587 
15588 struct RetainCycleOwner {
15589   VarDecl *Variable = nullptr;
15590   SourceRange Range;
15591   SourceLocation Loc;
15592   bool Indirect = false;
15593 
15594   RetainCycleOwner() = default;
15595 
15596   void setLocsFrom(Expr *e) {
15597     Loc = e->getExprLoc();
15598     Range = e->getSourceRange();
15599   }
15600 };
15601 
15602 } // namespace
15603 
15604 /// Consider whether capturing the given variable can possibly lead to
15605 /// a retain cycle.
15606 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15607   // In ARC, it's captured strongly iff the variable has __strong
15608   // lifetime.  In MRR, it's captured strongly if the variable is
15609   // __block and has an appropriate type.
15610   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15611     return false;
15612 
15613   owner.Variable = var;
15614   if (ref)
15615     owner.setLocsFrom(ref);
15616   return true;
15617 }
15618 
15619 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15620   while (true) {
15621     e = e->IgnoreParens();
15622     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15623       switch (cast->getCastKind()) {
15624       case CK_BitCast:
15625       case CK_LValueBitCast:
15626       case CK_LValueToRValue:
15627       case CK_ARCReclaimReturnedObject:
15628         e = cast->getSubExpr();
15629         continue;
15630 
15631       default:
15632         return false;
15633       }
15634     }
15635 
15636     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15637       ObjCIvarDecl *ivar = ref->getDecl();
15638       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15639         return false;
15640 
15641       // Try to find a retain cycle in the base.
15642       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15643         return false;
15644 
15645       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15646       owner.Indirect = true;
15647       return true;
15648     }
15649 
15650     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15651       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15652       if (!var) return false;
15653       return considerVariable(var, ref, owner);
15654     }
15655 
15656     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15657       if (member->isArrow()) return false;
15658 
15659       // Don't count this as an indirect ownership.
15660       e = member->getBase();
15661       continue;
15662     }
15663 
15664     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15665       // Only pay attention to pseudo-objects on property references.
15666       ObjCPropertyRefExpr *pre
15667         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15668                                               ->IgnoreParens());
15669       if (!pre) return false;
15670       if (pre->isImplicitProperty()) return false;
15671       ObjCPropertyDecl *property = pre->getExplicitProperty();
15672       if (!property->isRetaining() &&
15673           !(property->getPropertyIvarDecl() &&
15674             property->getPropertyIvarDecl()->getType()
15675               .getObjCLifetime() == Qualifiers::OCL_Strong))
15676           return false;
15677 
15678       owner.Indirect = true;
15679       if (pre->isSuperReceiver()) {
15680         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15681         if (!owner.Variable)
15682           return false;
15683         owner.Loc = pre->getLocation();
15684         owner.Range = pre->getSourceRange();
15685         return true;
15686       }
15687       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15688                               ->getSourceExpr());
15689       continue;
15690     }
15691 
15692     // Array ivars?
15693 
15694     return false;
15695   }
15696 }
15697 
15698 namespace {
15699 
15700   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15701     ASTContext &Context;
15702     VarDecl *Variable;
15703     Expr *Capturer = nullptr;
15704     bool VarWillBeReased = false;
15705 
15706     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15707         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15708           Context(Context), Variable(variable) {}
15709 
15710     void VisitDeclRefExpr(DeclRefExpr *ref) {
15711       if (ref->getDecl() == Variable && !Capturer)
15712         Capturer = ref;
15713     }
15714 
15715     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15716       if (Capturer) return;
15717       Visit(ref->getBase());
15718       if (Capturer && ref->isFreeIvar())
15719         Capturer = ref;
15720     }
15721 
15722     void VisitBlockExpr(BlockExpr *block) {
15723       // Look inside nested blocks
15724       if (block->getBlockDecl()->capturesVariable(Variable))
15725         Visit(block->getBlockDecl()->getBody());
15726     }
15727 
15728     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15729       if (Capturer) return;
15730       if (OVE->getSourceExpr())
15731         Visit(OVE->getSourceExpr());
15732     }
15733 
15734     void VisitBinaryOperator(BinaryOperator *BinOp) {
15735       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15736         return;
15737       Expr *LHS = BinOp->getLHS();
15738       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15739         if (DRE->getDecl() != Variable)
15740           return;
15741         if (Expr *RHS = BinOp->getRHS()) {
15742           RHS = RHS->IgnoreParenCasts();
15743           Optional<llvm::APSInt> Value;
15744           VarWillBeReased =
15745               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15746                *Value == 0);
15747         }
15748       }
15749     }
15750   };
15751 
15752 } // namespace
15753 
15754 /// Check whether the given argument is a block which captures a
15755 /// variable.
15756 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15757   assert(owner.Variable && owner.Loc.isValid());
15758 
15759   e = e->IgnoreParenCasts();
15760 
15761   // Look through [^{...} copy] and Block_copy(^{...}).
15762   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15763     Selector Cmd = ME->getSelector();
15764     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15765       e = ME->getInstanceReceiver();
15766       if (!e)
15767         return nullptr;
15768       e = e->IgnoreParenCasts();
15769     }
15770   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15771     if (CE->getNumArgs() == 1) {
15772       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15773       if (Fn) {
15774         const IdentifierInfo *FnI = Fn->getIdentifier();
15775         if (FnI && FnI->isStr("_Block_copy")) {
15776           e = CE->getArg(0)->IgnoreParenCasts();
15777         }
15778       }
15779     }
15780   }
15781 
15782   BlockExpr *block = dyn_cast<BlockExpr>(e);
15783   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15784     return nullptr;
15785 
15786   FindCaptureVisitor visitor(S.Context, owner.Variable);
15787   visitor.Visit(block->getBlockDecl()->getBody());
15788   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15789 }
15790 
15791 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15792                                 RetainCycleOwner &owner) {
15793   assert(capturer);
15794   assert(owner.Variable && owner.Loc.isValid());
15795 
15796   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15797     << owner.Variable << capturer->getSourceRange();
15798   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15799     << owner.Indirect << owner.Range;
15800 }
15801 
15802 /// Check for a keyword selector that starts with the word 'add' or
15803 /// 'set'.
15804 static bool isSetterLikeSelector(Selector sel) {
15805   if (sel.isUnarySelector()) return false;
15806 
15807   StringRef str = sel.getNameForSlot(0);
15808   while (!str.empty() && str.front() == '_') str = str.substr(1);
15809   if (str.startswith("set"))
15810     str = str.substr(3);
15811   else if (str.startswith("add")) {
15812     // Specially allow 'addOperationWithBlock:'.
15813     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15814       return false;
15815     str = str.substr(3);
15816   }
15817   else
15818     return false;
15819 
15820   if (str.empty()) return true;
15821   return !isLowercase(str.front());
15822 }
15823 
15824 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15825                                                     ObjCMessageExpr *Message) {
15826   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15827                                                 Message->getReceiverInterface(),
15828                                                 NSAPI::ClassId_NSMutableArray);
15829   if (!IsMutableArray) {
15830     return None;
15831   }
15832 
15833   Selector Sel = Message->getSelector();
15834 
15835   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15836     S.NSAPIObj->getNSArrayMethodKind(Sel);
15837   if (!MKOpt) {
15838     return None;
15839   }
15840 
15841   NSAPI::NSArrayMethodKind MK = *MKOpt;
15842 
15843   switch (MK) {
15844     case NSAPI::NSMutableArr_addObject:
15845     case NSAPI::NSMutableArr_insertObjectAtIndex:
15846     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15847       return 0;
15848     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15849       return 1;
15850 
15851     default:
15852       return None;
15853   }
15854 
15855   return None;
15856 }
15857 
15858 static
15859 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15860                                                   ObjCMessageExpr *Message) {
15861   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15862                                             Message->getReceiverInterface(),
15863                                             NSAPI::ClassId_NSMutableDictionary);
15864   if (!IsMutableDictionary) {
15865     return None;
15866   }
15867 
15868   Selector Sel = Message->getSelector();
15869 
15870   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15871     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15872   if (!MKOpt) {
15873     return None;
15874   }
15875 
15876   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15877 
15878   switch (MK) {
15879     case NSAPI::NSMutableDict_setObjectForKey:
15880     case NSAPI::NSMutableDict_setValueForKey:
15881     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15882       return 0;
15883 
15884     default:
15885       return None;
15886   }
15887 
15888   return None;
15889 }
15890 
15891 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15892   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15893                                                 Message->getReceiverInterface(),
15894                                                 NSAPI::ClassId_NSMutableSet);
15895 
15896   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15897                                             Message->getReceiverInterface(),
15898                                             NSAPI::ClassId_NSMutableOrderedSet);
15899   if (!IsMutableSet && !IsMutableOrderedSet) {
15900     return None;
15901   }
15902 
15903   Selector Sel = Message->getSelector();
15904 
15905   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15906   if (!MKOpt) {
15907     return None;
15908   }
15909 
15910   NSAPI::NSSetMethodKind MK = *MKOpt;
15911 
15912   switch (MK) {
15913     case NSAPI::NSMutableSet_addObject:
15914     case NSAPI::NSOrderedSet_setObjectAtIndex:
15915     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15916     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15917       return 0;
15918     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15919       return 1;
15920   }
15921 
15922   return None;
15923 }
15924 
15925 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15926   if (!Message->isInstanceMessage()) {
15927     return;
15928   }
15929 
15930   Optional<int> ArgOpt;
15931 
15932   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15933       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15934       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15935     return;
15936   }
15937 
15938   int ArgIndex = *ArgOpt;
15939 
15940   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15941   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15942     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15943   }
15944 
15945   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15946     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15947       if (ArgRE->isObjCSelfExpr()) {
15948         Diag(Message->getSourceRange().getBegin(),
15949              diag::warn_objc_circular_container)
15950           << ArgRE->getDecl() << StringRef("'super'");
15951       }
15952     }
15953   } else {
15954     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15955 
15956     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15957       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15958     }
15959 
15960     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15961       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15962         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15963           ValueDecl *Decl = ReceiverRE->getDecl();
15964           Diag(Message->getSourceRange().getBegin(),
15965                diag::warn_objc_circular_container)
15966             << Decl << Decl;
15967           if (!ArgRE->isObjCSelfExpr()) {
15968             Diag(Decl->getLocation(),
15969                  diag::note_objc_circular_container_declared_here)
15970               << Decl;
15971           }
15972         }
15973       }
15974     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15975       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15976         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15977           ObjCIvarDecl *Decl = IvarRE->getDecl();
15978           Diag(Message->getSourceRange().getBegin(),
15979                diag::warn_objc_circular_container)
15980             << Decl << Decl;
15981           Diag(Decl->getLocation(),
15982                diag::note_objc_circular_container_declared_here)
15983             << Decl;
15984         }
15985       }
15986     }
15987   }
15988 }
15989 
15990 /// Check a message send to see if it's likely to cause a retain cycle.
15991 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15992   // Only check instance methods whose selector looks like a setter.
15993   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15994     return;
15995 
15996   // Try to find a variable that the receiver is strongly owned by.
15997   RetainCycleOwner owner;
15998   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15999     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
16000       return;
16001   } else {
16002     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
16003     owner.Variable = getCurMethodDecl()->getSelfDecl();
16004     owner.Loc = msg->getSuperLoc();
16005     owner.Range = msg->getSuperLoc();
16006   }
16007 
16008   // Check whether the receiver is captured by any of the arguments.
16009   const ObjCMethodDecl *MD = msg->getMethodDecl();
16010   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
16011     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
16012       // noescape blocks should not be retained by the method.
16013       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
16014         continue;
16015       return diagnoseRetainCycle(*this, capturer, owner);
16016     }
16017   }
16018 }
16019 
16020 /// Check a property assign to see if it's likely to cause a retain cycle.
16021 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
16022   RetainCycleOwner owner;
16023   if (!findRetainCycleOwner(*this, receiver, owner))
16024     return;
16025 
16026   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
16027     diagnoseRetainCycle(*this, capturer, owner);
16028 }
16029 
16030 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
16031   RetainCycleOwner Owner;
16032   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
16033     return;
16034 
16035   // Because we don't have an expression for the variable, we have to set the
16036   // location explicitly here.
16037   Owner.Loc = Var->getLocation();
16038   Owner.Range = Var->getSourceRange();
16039 
16040   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
16041     diagnoseRetainCycle(*this, Capturer, Owner);
16042 }
16043 
16044 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
16045                                      Expr *RHS, bool isProperty) {
16046   // Check if RHS is an Objective-C object literal, which also can get
16047   // immediately zapped in a weak reference.  Note that we explicitly
16048   // allow ObjCStringLiterals, since those are designed to never really die.
16049   RHS = RHS->IgnoreParenImpCasts();
16050 
16051   // This enum needs to match with the 'select' in
16052   // warn_objc_arc_literal_assign (off-by-1).
16053   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
16054   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
16055     return false;
16056 
16057   S.Diag(Loc, diag::warn_arc_literal_assign)
16058     << (unsigned) Kind
16059     << (isProperty ? 0 : 1)
16060     << RHS->getSourceRange();
16061 
16062   return true;
16063 }
16064 
16065 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
16066                                     Qualifiers::ObjCLifetime LT,
16067                                     Expr *RHS, bool isProperty) {
16068   // Strip off any implicit cast added to get to the one ARC-specific.
16069   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16070     if (cast->getCastKind() == CK_ARCConsumeObject) {
16071       S.Diag(Loc, diag::warn_arc_retained_assign)
16072         << (LT == Qualifiers::OCL_ExplicitNone)
16073         << (isProperty ? 0 : 1)
16074         << RHS->getSourceRange();
16075       return true;
16076     }
16077     RHS = cast->getSubExpr();
16078   }
16079 
16080   if (LT == Qualifiers::OCL_Weak &&
16081       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16082     return true;
16083 
16084   return false;
16085 }
16086 
16087 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
16088                               QualType LHS, Expr *RHS) {
16089   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
16090 
16091   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
16092     return false;
16093 
16094   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
16095     return true;
16096 
16097   return false;
16098 }
16099 
16100 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
16101                               Expr *LHS, Expr *RHS) {
16102   QualType LHSType;
16103   // PropertyRef on LHS type need be directly obtained from
16104   // its declaration as it has a PseudoType.
16105   ObjCPropertyRefExpr *PRE
16106     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
16107   if (PRE && !PRE->isImplicitProperty()) {
16108     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16109     if (PD)
16110       LHSType = PD->getType();
16111   }
16112 
16113   if (LHSType.isNull())
16114     LHSType = LHS->getType();
16115 
16116   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
16117 
16118   if (LT == Qualifiers::OCL_Weak) {
16119     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
16120       getCurFunction()->markSafeWeakUse(LHS);
16121   }
16122 
16123   if (checkUnsafeAssigns(Loc, LHSType, RHS))
16124     return;
16125 
16126   // FIXME. Check for other life times.
16127   if (LT != Qualifiers::OCL_None)
16128     return;
16129 
16130   if (PRE) {
16131     if (PRE->isImplicitProperty())
16132       return;
16133     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16134     if (!PD)
16135       return;
16136 
16137     unsigned Attributes = PD->getPropertyAttributes();
16138     if (Attributes & ObjCPropertyAttribute::kind_assign) {
16139       // when 'assign' attribute was not explicitly specified
16140       // by user, ignore it and rely on property type itself
16141       // for lifetime info.
16142       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16143       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16144           LHSType->isObjCRetainableType())
16145         return;
16146 
16147       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16148         if (cast->getCastKind() == CK_ARCConsumeObject) {
16149           Diag(Loc, diag::warn_arc_retained_property_assign)
16150           << RHS->getSourceRange();
16151           return;
16152         }
16153         RHS = cast->getSubExpr();
16154       }
16155     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16156       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
16157         return;
16158     }
16159   }
16160 }
16161 
16162 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16163 
16164 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16165                                         SourceLocation StmtLoc,
16166                                         const NullStmt *Body) {
16167   // Do not warn if the body is a macro that expands to nothing, e.g:
16168   //
16169   // #define CALL(x)
16170   // if (condition)
16171   //   CALL(0);
16172   if (Body->hasLeadingEmptyMacro())
16173     return false;
16174 
16175   // Get line numbers of statement and body.
16176   bool StmtLineInvalid;
16177   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16178                                                       &StmtLineInvalid);
16179   if (StmtLineInvalid)
16180     return false;
16181 
16182   bool BodyLineInvalid;
16183   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16184                                                       &BodyLineInvalid);
16185   if (BodyLineInvalid)
16186     return false;
16187 
16188   // Warn if null statement and body are on the same line.
16189   if (StmtLine != BodyLine)
16190     return false;
16191 
16192   return true;
16193 }
16194 
16195 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
16196                                  const Stmt *Body,
16197                                  unsigned DiagID) {
16198   // Since this is a syntactic check, don't emit diagnostic for template
16199   // instantiations, this just adds noise.
16200   if (CurrentInstantiationScope)
16201     return;
16202 
16203   // The body should be a null statement.
16204   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16205   if (!NBody)
16206     return;
16207 
16208   // Do the usual checks.
16209   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16210     return;
16211 
16212   Diag(NBody->getSemiLoc(), DiagID);
16213   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16214 }
16215 
16216 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
16217                                  const Stmt *PossibleBody) {
16218   assert(!CurrentInstantiationScope); // Ensured by caller
16219 
16220   SourceLocation StmtLoc;
16221   const Stmt *Body;
16222   unsigned DiagID;
16223   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16224     StmtLoc = FS->getRParenLoc();
16225     Body = FS->getBody();
16226     DiagID = diag::warn_empty_for_body;
16227   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16228     StmtLoc = WS->getCond()->getSourceRange().getEnd();
16229     Body = WS->getBody();
16230     DiagID = diag::warn_empty_while_body;
16231   } else
16232     return; // Neither `for' nor `while'.
16233 
16234   // The body should be a null statement.
16235   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16236   if (!NBody)
16237     return;
16238 
16239   // Skip expensive checks if diagnostic is disabled.
16240   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16241     return;
16242 
16243   // Do the usual checks.
16244   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16245     return;
16246 
16247   // `for(...);' and `while(...);' are popular idioms, so in order to keep
16248   // noise level low, emit diagnostics only if for/while is followed by a
16249   // CompoundStmt, e.g.:
16250   //    for (int i = 0; i < n; i++);
16251   //    {
16252   //      a(i);
16253   //    }
16254   // or if for/while is followed by a statement with more indentation
16255   // than for/while itself:
16256   //    for (int i = 0; i < n; i++);
16257   //      a(i);
16258   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16259   if (!ProbableTypo) {
16260     bool BodyColInvalid;
16261     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16262         PossibleBody->getBeginLoc(), &BodyColInvalid);
16263     if (BodyColInvalid)
16264       return;
16265 
16266     bool StmtColInvalid;
16267     unsigned StmtCol =
16268         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16269     if (StmtColInvalid)
16270       return;
16271 
16272     if (BodyCol > StmtCol)
16273       ProbableTypo = true;
16274   }
16275 
16276   if (ProbableTypo) {
16277     Diag(NBody->getSemiLoc(), DiagID);
16278     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16279   }
16280 }
16281 
16282 //===--- CHECK: Warn on self move with std::move. -------------------------===//
16283 
16284 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
16285 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16286                              SourceLocation OpLoc) {
16287   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16288     return;
16289 
16290   if (inTemplateInstantiation())
16291     return;
16292 
16293   // Strip parens and casts away.
16294   LHSExpr = LHSExpr->IgnoreParenImpCasts();
16295   RHSExpr = RHSExpr->IgnoreParenImpCasts();
16296 
16297   // Check for a call expression
16298   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
16299   if (!CE || CE->getNumArgs() != 1)
16300     return;
16301 
16302   // Check for a call to std::move
16303   if (!CE->isCallToStdMove())
16304     return;
16305 
16306   // Get argument from std::move
16307   RHSExpr = CE->getArg(0);
16308 
16309   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16310   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16311 
16312   // Two DeclRefExpr's, check that the decls are the same.
16313   if (LHSDeclRef && RHSDeclRef) {
16314     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16315       return;
16316     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16317         RHSDeclRef->getDecl()->getCanonicalDecl())
16318       return;
16319 
16320     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16321                                         << LHSExpr->getSourceRange()
16322                                         << RHSExpr->getSourceRange();
16323     return;
16324   }
16325 
16326   // Member variables require a different approach to check for self moves.
16327   // MemberExpr's are the same if every nested MemberExpr refers to the same
16328   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16329   // the base Expr's are CXXThisExpr's.
16330   const Expr *LHSBase = LHSExpr;
16331   const Expr *RHSBase = RHSExpr;
16332   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16333   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16334   if (!LHSME || !RHSME)
16335     return;
16336 
16337   while (LHSME && RHSME) {
16338     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16339         RHSME->getMemberDecl()->getCanonicalDecl())
16340       return;
16341 
16342     LHSBase = LHSME->getBase();
16343     RHSBase = RHSME->getBase();
16344     LHSME = dyn_cast<MemberExpr>(LHSBase);
16345     RHSME = dyn_cast<MemberExpr>(RHSBase);
16346   }
16347 
16348   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16349   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16350   if (LHSDeclRef && RHSDeclRef) {
16351     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16352       return;
16353     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16354         RHSDeclRef->getDecl()->getCanonicalDecl())
16355       return;
16356 
16357     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16358                                         << LHSExpr->getSourceRange()
16359                                         << RHSExpr->getSourceRange();
16360     return;
16361   }
16362 
16363   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16364     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16365                                         << LHSExpr->getSourceRange()
16366                                         << RHSExpr->getSourceRange();
16367 }
16368 
16369 //===--- Layout compatibility ----------------------------------------------//
16370 
16371 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
16372 
16373 /// Check if two enumeration types are layout-compatible.
16374 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
16375   // C++11 [dcl.enum] p8:
16376   // Two enumeration types are layout-compatible if they have the same
16377   // underlying type.
16378   return ED1->isComplete() && ED2->isComplete() &&
16379          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16380 }
16381 
16382 /// Check if two fields are layout-compatible.
16383 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
16384                                FieldDecl *Field2) {
16385   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16386     return false;
16387 
16388   if (Field1->isBitField() != Field2->isBitField())
16389     return false;
16390 
16391   if (Field1->isBitField()) {
16392     // Make sure that the bit-fields are the same length.
16393     unsigned Bits1 = Field1->getBitWidthValue(C);
16394     unsigned Bits2 = Field2->getBitWidthValue(C);
16395 
16396     if (Bits1 != Bits2)
16397       return false;
16398   }
16399 
16400   return true;
16401 }
16402 
16403 /// Check if two standard-layout structs are layout-compatible.
16404 /// (C++11 [class.mem] p17)
16405 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
16406                                      RecordDecl *RD2) {
16407   // If both records are C++ classes, check that base classes match.
16408   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
16409     // If one of records is a CXXRecordDecl we are in C++ mode,
16410     // thus the other one is a CXXRecordDecl, too.
16411     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
16412     // Check number of base classes.
16413     if (D1CXX->getNumBases() != D2CXX->getNumBases())
16414       return false;
16415 
16416     // Check the base classes.
16417     for (CXXRecordDecl::base_class_const_iterator
16418                Base1 = D1CXX->bases_begin(),
16419            BaseEnd1 = D1CXX->bases_end(),
16420               Base2 = D2CXX->bases_begin();
16421          Base1 != BaseEnd1;
16422          ++Base1, ++Base2) {
16423       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16424         return false;
16425     }
16426   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16427     // If only RD2 is a C++ class, it should have zero base classes.
16428     if (D2CXX->getNumBases() > 0)
16429       return false;
16430   }
16431 
16432   // Check the fields.
16433   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16434                              Field2End = RD2->field_end(),
16435                              Field1 = RD1->field_begin(),
16436                              Field1End = RD1->field_end();
16437   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16438     if (!isLayoutCompatible(C, *Field1, *Field2))
16439       return false;
16440   }
16441   if (Field1 != Field1End || Field2 != Field2End)
16442     return false;
16443 
16444   return true;
16445 }
16446 
16447 /// Check if two standard-layout unions are layout-compatible.
16448 /// (C++11 [class.mem] p18)
16449 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16450                                     RecordDecl *RD2) {
16451   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16452   for (auto *Field2 : RD2->fields())
16453     UnmatchedFields.insert(Field2);
16454 
16455   for (auto *Field1 : RD1->fields()) {
16456     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16457         I = UnmatchedFields.begin(),
16458         E = UnmatchedFields.end();
16459 
16460     for ( ; I != E; ++I) {
16461       if (isLayoutCompatible(C, Field1, *I)) {
16462         bool Result = UnmatchedFields.erase(*I);
16463         (void) Result;
16464         assert(Result);
16465         break;
16466       }
16467     }
16468     if (I == E)
16469       return false;
16470   }
16471 
16472   return UnmatchedFields.empty();
16473 }
16474 
16475 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16476                                RecordDecl *RD2) {
16477   if (RD1->isUnion() != RD2->isUnion())
16478     return false;
16479 
16480   if (RD1->isUnion())
16481     return isLayoutCompatibleUnion(C, RD1, RD2);
16482   else
16483     return isLayoutCompatibleStruct(C, RD1, RD2);
16484 }
16485 
16486 /// Check if two types are layout-compatible in C++11 sense.
16487 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16488   if (T1.isNull() || T2.isNull())
16489     return false;
16490 
16491   // C++11 [basic.types] p11:
16492   // If two types T1 and T2 are the same type, then T1 and T2 are
16493   // layout-compatible types.
16494   if (C.hasSameType(T1, T2))
16495     return true;
16496 
16497   T1 = T1.getCanonicalType().getUnqualifiedType();
16498   T2 = T2.getCanonicalType().getUnqualifiedType();
16499 
16500   const Type::TypeClass TC1 = T1->getTypeClass();
16501   const Type::TypeClass TC2 = T2->getTypeClass();
16502 
16503   if (TC1 != TC2)
16504     return false;
16505 
16506   if (TC1 == Type::Enum) {
16507     return isLayoutCompatible(C,
16508                               cast<EnumType>(T1)->getDecl(),
16509                               cast<EnumType>(T2)->getDecl());
16510   } else if (TC1 == Type::Record) {
16511     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16512       return false;
16513 
16514     return isLayoutCompatible(C,
16515                               cast<RecordType>(T1)->getDecl(),
16516                               cast<RecordType>(T2)->getDecl());
16517   }
16518 
16519   return false;
16520 }
16521 
16522 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16523 
16524 /// Given a type tag expression find the type tag itself.
16525 ///
16526 /// \param TypeExpr Type tag expression, as it appears in user's code.
16527 ///
16528 /// \param VD Declaration of an identifier that appears in a type tag.
16529 ///
16530 /// \param MagicValue Type tag magic value.
16531 ///
16532 /// \param isConstantEvaluated whether the evalaution should be performed in
16533 
16534 /// constant context.
16535 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16536                             const ValueDecl **VD, uint64_t *MagicValue,
16537                             bool isConstantEvaluated) {
16538   while(true) {
16539     if (!TypeExpr)
16540       return false;
16541 
16542     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16543 
16544     switch (TypeExpr->getStmtClass()) {
16545     case Stmt::UnaryOperatorClass: {
16546       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16547       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16548         TypeExpr = UO->getSubExpr();
16549         continue;
16550       }
16551       return false;
16552     }
16553 
16554     case Stmt::DeclRefExprClass: {
16555       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16556       *VD = DRE->getDecl();
16557       return true;
16558     }
16559 
16560     case Stmt::IntegerLiteralClass: {
16561       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16562       llvm::APInt MagicValueAPInt = IL->getValue();
16563       if (MagicValueAPInt.getActiveBits() <= 64) {
16564         *MagicValue = MagicValueAPInt.getZExtValue();
16565         return true;
16566       } else
16567         return false;
16568     }
16569 
16570     case Stmt::BinaryConditionalOperatorClass:
16571     case Stmt::ConditionalOperatorClass: {
16572       const AbstractConditionalOperator *ACO =
16573           cast<AbstractConditionalOperator>(TypeExpr);
16574       bool Result;
16575       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16576                                                      isConstantEvaluated)) {
16577         if (Result)
16578           TypeExpr = ACO->getTrueExpr();
16579         else
16580           TypeExpr = ACO->getFalseExpr();
16581         continue;
16582       }
16583       return false;
16584     }
16585 
16586     case Stmt::BinaryOperatorClass: {
16587       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16588       if (BO->getOpcode() == BO_Comma) {
16589         TypeExpr = BO->getRHS();
16590         continue;
16591       }
16592       return false;
16593     }
16594 
16595     default:
16596       return false;
16597     }
16598   }
16599 }
16600 
16601 /// Retrieve the C type corresponding to type tag TypeExpr.
16602 ///
16603 /// \param TypeExpr Expression that specifies a type tag.
16604 ///
16605 /// \param MagicValues Registered magic values.
16606 ///
16607 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16608 ///        kind.
16609 ///
16610 /// \param TypeInfo Information about the corresponding C type.
16611 ///
16612 /// \param isConstantEvaluated whether the evalaution should be performed in
16613 /// constant context.
16614 ///
16615 /// \returns true if the corresponding C type was found.
16616 static bool GetMatchingCType(
16617     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16618     const ASTContext &Ctx,
16619     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16620         *MagicValues,
16621     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16622     bool isConstantEvaluated) {
16623   FoundWrongKind = false;
16624 
16625   // Variable declaration that has type_tag_for_datatype attribute.
16626   const ValueDecl *VD = nullptr;
16627 
16628   uint64_t MagicValue;
16629 
16630   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16631     return false;
16632 
16633   if (VD) {
16634     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16635       if (I->getArgumentKind() != ArgumentKind) {
16636         FoundWrongKind = true;
16637         return false;
16638       }
16639       TypeInfo.Type = I->getMatchingCType();
16640       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16641       TypeInfo.MustBeNull = I->getMustBeNull();
16642       return true;
16643     }
16644     return false;
16645   }
16646 
16647   if (!MagicValues)
16648     return false;
16649 
16650   llvm::DenseMap<Sema::TypeTagMagicValue,
16651                  Sema::TypeTagData>::const_iterator I =
16652       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16653   if (I == MagicValues->end())
16654     return false;
16655 
16656   TypeInfo = I->second;
16657   return true;
16658 }
16659 
16660 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16661                                       uint64_t MagicValue, QualType Type,
16662                                       bool LayoutCompatible,
16663                                       bool MustBeNull) {
16664   if (!TypeTagForDatatypeMagicValues)
16665     TypeTagForDatatypeMagicValues.reset(
16666         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16667 
16668   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16669   (*TypeTagForDatatypeMagicValues)[Magic] =
16670       TypeTagData(Type, LayoutCompatible, MustBeNull);
16671 }
16672 
16673 static bool IsSameCharType(QualType T1, QualType T2) {
16674   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16675   if (!BT1)
16676     return false;
16677 
16678   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16679   if (!BT2)
16680     return false;
16681 
16682   BuiltinType::Kind T1Kind = BT1->getKind();
16683   BuiltinType::Kind T2Kind = BT2->getKind();
16684 
16685   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16686          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16687          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16688          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16689 }
16690 
16691 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16692                                     const ArrayRef<const Expr *> ExprArgs,
16693                                     SourceLocation CallSiteLoc) {
16694   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16695   bool IsPointerAttr = Attr->getIsPointer();
16696 
16697   // Retrieve the argument representing the 'type_tag'.
16698   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16699   if (TypeTagIdxAST >= ExprArgs.size()) {
16700     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16701         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16702     return;
16703   }
16704   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16705   bool FoundWrongKind;
16706   TypeTagData TypeInfo;
16707   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16708                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16709                         TypeInfo, isConstantEvaluated())) {
16710     if (FoundWrongKind)
16711       Diag(TypeTagExpr->getExprLoc(),
16712            diag::warn_type_tag_for_datatype_wrong_kind)
16713         << TypeTagExpr->getSourceRange();
16714     return;
16715   }
16716 
16717   // Retrieve the argument representing the 'arg_idx'.
16718   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16719   if (ArgumentIdxAST >= ExprArgs.size()) {
16720     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16721         << 1 << Attr->getArgumentIdx().getSourceIndex();
16722     return;
16723   }
16724   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16725   if (IsPointerAttr) {
16726     // Skip implicit cast of pointer to `void *' (as a function argument).
16727     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16728       if (ICE->getType()->isVoidPointerType() &&
16729           ICE->getCastKind() == CK_BitCast)
16730         ArgumentExpr = ICE->getSubExpr();
16731   }
16732   QualType ArgumentType = ArgumentExpr->getType();
16733 
16734   // Passing a `void*' pointer shouldn't trigger a warning.
16735   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16736     return;
16737 
16738   if (TypeInfo.MustBeNull) {
16739     // Type tag with matching void type requires a null pointer.
16740     if (!ArgumentExpr->isNullPointerConstant(Context,
16741                                              Expr::NPC_ValueDependentIsNotNull)) {
16742       Diag(ArgumentExpr->getExprLoc(),
16743            diag::warn_type_safety_null_pointer_required)
16744           << ArgumentKind->getName()
16745           << ArgumentExpr->getSourceRange()
16746           << TypeTagExpr->getSourceRange();
16747     }
16748     return;
16749   }
16750 
16751   QualType RequiredType = TypeInfo.Type;
16752   if (IsPointerAttr)
16753     RequiredType = Context.getPointerType(RequiredType);
16754 
16755   bool mismatch = false;
16756   if (!TypeInfo.LayoutCompatible) {
16757     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16758 
16759     // C++11 [basic.fundamental] p1:
16760     // Plain char, signed char, and unsigned char are three distinct types.
16761     //
16762     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16763     // char' depending on the current char signedness mode.
16764     if (mismatch)
16765       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16766                                            RequiredType->getPointeeType())) ||
16767           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16768         mismatch = false;
16769   } else
16770     if (IsPointerAttr)
16771       mismatch = !isLayoutCompatible(Context,
16772                                      ArgumentType->getPointeeType(),
16773                                      RequiredType->getPointeeType());
16774     else
16775       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16776 
16777   if (mismatch)
16778     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16779         << ArgumentType << ArgumentKind
16780         << TypeInfo.LayoutCompatible << RequiredType
16781         << ArgumentExpr->getSourceRange()
16782         << TypeTagExpr->getSourceRange();
16783 }
16784 
16785 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16786                                          CharUnits Alignment) {
16787   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16788 }
16789 
16790 void Sema::DiagnoseMisalignedMembers() {
16791   for (MisalignedMember &m : MisalignedMembers) {
16792     const NamedDecl *ND = m.RD;
16793     if (ND->getName().empty()) {
16794       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16795         ND = TD;
16796     }
16797     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16798         << m.MD << ND << m.E->getSourceRange();
16799   }
16800   MisalignedMembers.clear();
16801 }
16802 
16803 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16804   E = E->IgnoreParens();
16805   if (!T->isPointerType() && !T->isIntegerType())
16806     return;
16807   if (isa<UnaryOperator>(E) &&
16808       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16809     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16810     if (isa<MemberExpr>(Op)) {
16811       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16812       if (MA != MisalignedMembers.end() &&
16813           (T->isIntegerType() ||
16814            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16815                                    Context.getTypeAlignInChars(
16816                                        T->getPointeeType()) <= MA->Alignment))))
16817         MisalignedMembers.erase(MA);
16818     }
16819   }
16820 }
16821 
16822 void Sema::RefersToMemberWithReducedAlignment(
16823     Expr *E,
16824     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16825         Action) {
16826   const auto *ME = dyn_cast<MemberExpr>(E);
16827   if (!ME)
16828     return;
16829 
16830   // No need to check expressions with an __unaligned-qualified type.
16831   if (E->getType().getQualifiers().hasUnaligned())
16832     return;
16833 
16834   // For a chain of MemberExpr like "a.b.c.d" this list
16835   // will keep FieldDecl's like [d, c, b].
16836   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16837   const MemberExpr *TopME = nullptr;
16838   bool AnyIsPacked = false;
16839   do {
16840     QualType BaseType = ME->getBase()->getType();
16841     if (BaseType->isDependentType())
16842       return;
16843     if (ME->isArrow())
16844       BaseType = BaseType->getPointeeType();
16845     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16846     if (RD->isInvalidDecl())
16847       return;
16848 
16849     ValueDecl *MD = ME->getMemberDecl();
16850     auto *FD = dyn_cast<FieldDecl>(MD);
16851     // We do not care about non-data members.
16852     if (!FD || FD->isInvalidDecl())
16853       return;
16854 
16855     AnyIsPacked =
16856         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16857     ReverseMemberChain.push_back(FD);
16858 
16859     TopME = ME;
16860     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16861   } while (ME);
16862   assert(TopME && "We did not compute a topmost MemberExpr!");
16863 
16864   // Not the scope of this diagnostic.
16865   if (!AnyIsPacked)
16866     return;
16867 
16868   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16869   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16870   // TODO: The innermost base of the member expression may be too complicated.
16871   // For now, just disregard these cases. This is left for future
16872   // improvement.
16873   if (!DRE && !isa<CXXThisExpr>(TopBase))
16874       return;
16875 
16876   // Alignment expected by the whole expression.
16877   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16878 
16879   // No need to do anything else with this case.
16880   if (ExpectedAlignment.isOne())
16881     return;
16882 
16883   // Synthesize offset of the whole access.
16884   CharUnits Offset;
16885   for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16886     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16887 
16888   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16889   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16890       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16891 
16892   // The base expression of the innermost MemberExpr may give
16893   // stronger guarantees than the class containing the member.
16894   if (DRE && !TopME->isArrow()) {
16895     const ValueDecl *VD = DRE->getDecl();
16896     if (!VD->getType()->isReferenceType())
16897       CompleteObjectAlignment =
16898           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16899   }
16900 
16901   // Check if the synthesized offset fulfills the alignment.
16902   if (Offset % ExpectedAlignment != 0 ||
16903       // It may fulfill the offset it but the effective alignment may still be
16904       // lower than the expected expression alignment.
16905       CompleteObjectAlignment < ExpectedAlignment) {
16906     // If this happens, we want to determine a sensible culprit of this.
16907     // Intuitively, watching the chain of member expressions from right to
16908     // left, we start with the required alignment (as required by the field
16909     // type) but some packed attribute in that chain has reduced the alignment.
16910     // It may happen that another packed structure increases it again. But if
16911     // we are here such increase has not been enough. So pointing the first
16912     // FieldDecl that either is packed or else its RecordDecl is,
16913     // seems reasonable.
16914     FieldDecl *FD = nullptr;
16915     CharUnits Alignment;
16916     for (FieldDecl *FDI : ReverseMemberChain) {
16917       if (FDI->hasAttr<PackedAttr>() ||
16918           FDI->getParent()->hasAttr<PackedAttr>()) {
16919         FD = FDI;
16920         Alignment = std::min(
16921             Context.getTypeAlignInChars(FD->getType()),
16922             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16923         break;
16924       }
16925     }
16926     assert(FD && "We did not find a packed FieldDecl!");
16927     Action(E, FD->getParent(), FD, Alignment);
16928   }
16929 }
16930 
16931 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16932   using namespace std::placeholders;
16933 
16934   RefersToMemberWithReducedAlignment(
16935       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16936                      _2, _3, _4));
16937 }
16938 
16939 // Check if \p Ty is a valid type for the elementwise math builtins. If it is
16940 // not a valid type, emit an error message and return true. Otherwise return
16941 // false.
16942 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc,
16943                                         QualType Ty) {
16944   if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) {
16945     S.Diag(Loc, diag::err_builtin_invalid_arg_type)
16946         << 1 << /* vector, integer or float ty*/ 0 << Ty;
16947     return true;
16948   }
16949   return false;
16950 }
16951 
16952 bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) {
16953   if (checkArgCount(*this, TheCall, 1))
16954     return true;
16955 
16956   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16957   if (A.isInvalid())
16958     return true;
16959 
16960   TheCall->setArg(0, A.get());
16961   QualType TyA = A.get()->getType();
16962 
16963   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
16964     return true;
16965 
16966   TheCall->setType(TyA);
16967   return false;
16968 }
16969 
16970 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) {
16971   if (checkArgCount(*this, TheCall, 2))
16972     return true;
16973 
16974   ExprResult A = TheCall->getArg(0);
16975   ExprResult B = TheCall->getArg(1);
16976   // Do standard promotions between the two arguments, returning their common
16977   // type.
16978   QualType Res =
16979       UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
16980   if (A.isInvalid() || B.isInvalid())
16981     return true;
16982 
16983   QualType TyA = A.get()->getType();
16984   QualType TyB = B.get()->getType();
16985 
16986   if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
16987     return Diag(A.get()->getBeginLoc(),
16988                 diag::err_typecheck_call_different_arg_types)
16989            << TyA << TyB;
16990 
16991   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
16992     return true;
16993 
16994   TheCall->setArg(0, A.get());
16995   TheCall->setArg(1, B.get());
16996   TheCall->setType(Res);
16997   return false;
16998 }
16999 
17000 bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
17001   if (checkArgCount(*this, TheCall, 1))
17002     return true;
17003 
17004   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17005   if (A.isInvalid())
17006     return true;
17007 
17008   TheCall->setArg(0, A.get());
17009   return false;
17010 }
17011 
17012 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
17013                                             ExprResult CallResult) {
17014   if (checkArgCount(*this, TheCall, 1))
17015     return ExprError();
17016 
17017   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
17018   if (MatrixArg.isInvalid())
17019     return MatrixArg;
17020   Expr *Matrix = MatrixArg.get();
17021 
17022   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17023   if (!MType) {
17024     Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17025         << 1 << /* matrix ty*/ 1 << Matrix->getType();
17026     return ExprError();
17027   }
17028 
17029   // Create returned matrix type by swapping rows and columns of the argument
17030   // matrix type.
17031   QualType ResultType = Context.getConstantMatrixType(
17032       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
17033 
17034   // Change the return type to the type of the returned matrix.
17035   TheCall->setType(ResultType);
17036 
17037   // Update call argument to use the possibly converted matrix argument.
17038   TheCall->setArg(0, Matrix);
17039   return CallResult;
17040 }
17041 
17042 // Get and verify the matrix dimensions.
17043 static llvm::Optional<unsigned>
17044 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
17045   SourceLocation ErrorPos;
17046   Optional<llvm::APSInt> Value =
17047       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
17048   if (!Value) {
17049     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
17050         << Name;
17051     return {};
17052   }
17053   uint64_t Dim = Value->getZExtValue();
17054   if (!ConstantMatrixType::isDimensionValid(Dim)) {
17055     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
17056         << Name << ConstantMatrixType::getMaxElementsPerDimension();
17057     return {};
17058   }
17059   return Dim;
17060 }
17061 
17062 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17063                                                   ExprResult CallResult) {
17064   if (!getLangOpts().MatrixTypes) {
17065     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17066     return ExprError();
17067   }
17068 
17069   if (checkArgCount(*this, TheCall, 4))
17070     return ExprError();
17071 
17072   unsigned PtrArgIdx = 0;
17073   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17074   Expr *RowsExpr = TheCall->getArg(1);
17075   Expr *ColumnsExpr = TheCall->getArg(2);
17076   Expr *StrideExpr = TheCall->getArg(3);
17077 
17078   bool ArgError = false;
17079 
17080   // Check pointer argument.
17081   {
17082     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17083     if (PtrConv.isInvalid())
17084       return PtrConv;
17085     PtrExpr = PtrConv.get();
17086     TheCall->setArg(0, PtrExpr);
17087     if (PtrExpr->isTypeDependent()) {
17088       TheCall->setType(Context.DependentTy);
17089       return TheCall;
17090     }
17091   }
17092 
17093   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17094   QualType ElementTy;
17095   if (!PtrTy) {
17096     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17097         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17098     ArgError = true;
17099   } else {
17100     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17101 
17102     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
17103       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17104           << PtrArgIdx + 1 << /* pointer to element ty*/ 2
17105           << PtrExpr->getType();
17106       ArgError = true;
17107     }
17108   }
17109 
17110   // Apply default Lvalue conversions and convert the expression to size_t.
17111   auto ApplyArgumentConversions = [this](Expr *E) {
17112     ExprResult Conv = DefaultLvalueConversion(E);
17113     if (Conv.isInvalid())
17114       return Conv;
17115 
17116     return tryConvertExprToType(Conv.get(), Context.getSizeType());
17117   };
17118 
17119   // Apply conversion to row and column expressions.
17120   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17121   if (!RowsConv.isInvalid()) {
17122     RowsExpr = RowsConv.get();
17123     TheCall->setArg(1, RowsExpr);
17124   } else
17125     RowsExpr = nullptr;
17126 
17127   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17128   if (!ColumnsConv.isInvalid()) {
17129     ColumnsExpr = ColumnsConv.get();
17130     TheCall->setArg(2, ColumnsExpr);
17131   } else
17132     ColumnsExpr = nullptr;
17133 
17134   // If any any part of the result matrix type is still pending, just use
17135   // Context.DependentTy, until all parts are resolved.
17136   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17137       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17138     TheCall->setType(Context.DependentTy);
17139     return CallResult;
17140   }
17141 
17142   // Check row and column dimensions.
17143   llvm::Optional<unsigned> MaybeRows;
17144   if (RowsExpr)
17145     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17146 
17147   llvm::Optional<unsigned> MaybeColumns;
17148   if (ColumnsExpr)
17149     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17150 
17151   // Check stride argument.
17152   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17153   if (StrideConv.isInvalid())
17154     return ExprError();
17155   StrideExpr = StrideConv.get();
17156   TheCall->setArg(3, StrideExpr);
17157 
17158   if (MaybeRows) {
17159     if (Optional<llvm::APSInt> Value =
17160             StrideExpr->getIntegerConstantExpr(Context)) {
17161       uint64_t Stride = Value->getZExtValue();
17162       if (Stride < *MaybeRows) {
17163         Diag(StrideExpr->getBeginLoc(),
17164              diag::err_builtin_matrix_stride_too_small);
17165         ArgError = true;
17166       }
17167     }
17168   }
17169 
17170   if (ArgError || !MaybeRows || !MaybeColumns)
17171     return ExprError();
17172 
17173   TheCall->setType(
17174       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17175   return CallResult;
17176 }
17177 
17178 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17179                                                    ExprResult CallResult) {
17180   if (checkArgCount(*this, TheCall, 3))
17181     return ExprError();
17182 
17183   unsigned PtrArgIdx = 1;
17184   Expr *MatrixExpr = TheCall->getArg(0);
17185   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17186   Expr *StrideExpr = TheCall->getArg(2);
17187 
17188   bool ArgError = false;
17189 
17190   {
17191     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17192     if (MatrixConv.isInvalid())
17193       return MatrixConv;
17194     MatrixExpr = MatrixConv.get();
17195     TheCall->setArg(0, MatrixExpr);
17196   }
17197   if (MatrixExpr->isTypeDependent()) {
17198     TheCall->setType(Context.DependentTy);
17199     return TheCall;
17200   }
17201 
17202   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17203   if (!MatrixTy) {
17204     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17205         << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
17206     ArgError = true;
17207   }
17208 
17209   {
17210     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17211     if (PtrConv.isInvalid())
17212       return PtrConv;
17213     PtrExpr = PtrConv.get();
17214     TheCall->setArg(1, PtrExpr);
17215     if (PtrExpr->isTypeDependent()) {
17216       TheCall->setType(Context.DependentTy);
17217       return TheCall;
17218     }
17219   }
17220 
17221   // Check pointer argument.
17222   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17223   if (!PtrTy) {
17224     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17225         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17226     ArgError = true;
17227   } else {
17228     QualType ElementTy = PtrTy->getPointeeType();
17229     if (ElementTy.isConstQualified()) {
17230       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17231       ArgError = true;
17232     }
17233     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17234     if (MatrixTy &&
17235         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17236       Diag(PtrExpr->getBeginLoc(),
17237            diag::err_builtin_matrix_pointer_arg_mismatch)
17238           << ElementTy << MatrixTy->getElementType();
17239       ArgError = true;
17240     }
17241   }
17242 
17243   // Apply default Lvalue conversions and convert the stride expression to
17244   // size_t.
17245   {
17246     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17247     if (StrideConv.isInvalid())
17248       return StrideConv;
17249 
17250     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17251     if (StrideConv.isInvalid())
17252       return StrideConv;
17253     StrideExpr = StrideConv.get();
17254     TheCall->setArg(2, StrideExpr);
17255   }
17256 
17257   // Check stride argument.
17258   if (MatrixTy) {
17259     if (Optional<llvm::APSInt> Value =
17260             StrideExpr->getIntegerConstantExpr(Context)) {
17261       uint64_t Stride = Value->getZExtValue();
17262       if (Stride < MatrixTy->getNumRows()) {
17263         Diag(StrideExpr->getBeginLoc(),
17264              diag::err_builtin_matrix_stride_too_small);
17265         ArgError = true;
17266       }
17267     }
17268   }
17269 
17270   if (ArgError)
17271     return ExprError();
17272 
17273   return CallResult;
17274 }
17275 
17276 /// \brief Enforce the bounds of a TCB
17277 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
17278 /// directly calls other functions in the same TCB as marked by the enforce_tcb
17279 /// and enforce_tcb_leaf attributes.
17280 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
17281                                const FunctionDecl *Callee) {
17282   const FunctionDecl *Caller = getCurFunctionDecl();
17283 
17284   // Calls to builtins are not enforced.
17285   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
17286       Callee->getBuiltinID() != 0)
17287     return;
17288 
17289   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17290   // all TCBs the callee is a part of.
17291   llvm::StringSet<> CalleeTCBs;
17292   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
17293            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17294   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
17295            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17296 
17297   // Go through the TCBs the caller is a part of and emit warnings if Caller
17298   // is in a TCB that the Callee is not.
17299   for_each(
17300       Caller->specific_attrs<EnforceTCBAttr>(),
17301       [&](const auto *A) {
17302         StringRef CallerTCB = A->getTCBName();
17303         if (CalleeTCBs.count(CallerTCB) == 0) {
17304           this->Diag(TheCall->getExprLoc(),
17305                      diag::warn_tcb_enforcement_violation) << Callee
17306                                                            << CallerTCB;
17307         }
17308       });
17309 }
17310