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_ppc_ldarx:
3608   case PPC::BI__builtin_ppc_stdcx:
3609   case PPC::BI__builtin_ppc_tdw:
3610   case PPC::BI__builtin_ppc_trapd:
3611   case PPC::BI__builtin_ppc_cmpeqb:
3612   case PPC::BI__builtin_ppc_setb:
3613   case PPC::BI__builtin_ppc_mulhd:
3614   case PPC::BI__builtin_ppc_mulhdu:
3615   case PPC::BI__builtin_ppc_maddhd:
3616   case PPC::BI__builtin_ppc_maddhdu:
3617   case PPC::BI__builtin_ppc_maddld:
3618   case PPC::BI__builtin_ppc_load8r:
3619   case PPC::BI__builtin_ppc_store8r:
3620   case PPC::BI__builtin_ppc_insert_exp:
3621   case PPC::BI__builtin_ppc_extract_sig:
3622   case PPC::BI__builtin_ppc_addex:
3623   case PPC::BI__builtin_darn:
3624   case PPC::BI__builtin_darn_raw:
3625   case PPC::BI__builtin_ppc_compare_and_swaplp:
3626   case PPC::BI__builtin_ppc_fetch_and_addlp:
3627   case PPC::BI__builtin_ppc_fetch_and_andlp:
3628   case PPC::BI__builtin_ppc_fetch_and_orlp:
3629   case PPC::BI__builtin_ppc_fetch_and_swaplp:
3630     return true;
3631   }
3632   return false;
3633 }
3634 
3635 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3636                              StringRef FeatureToCheck, unsigned DiagID,
3637                              StringRef DiagArg = "") {
3638   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3639     return false;
3640 
3641   if (DiagArg.empty())
3642     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3643   else
3644     S.Diag(TheCall->getBeginLoc(), DiagID)
3645         << DiagArg << TheCall->getSourceRange();
3646 
3647   return true;
3648 }
3649 
3650 /// Returns true if the argument consists of one contiguous run of 1s with any
3651 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3652 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3653 /// since all 1s are not contiguous.
3654 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3655   llvm::APSInt Result;
3656   // We can't check the value of a dependent argument.
3657   Expr *Arg = TheCall->getArg(ArgNum);
3658   if (Arg->isTypeDependent() || Arg->isValueDependent())
3659     return false;
3660 
3661   // Check constant-ness first.
3662   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3663     return true;
3664 
3665   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3666   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3667     return false;
3668 
3669   return Diag(TheCall->getBeginLoc(),
3670               diag::err_argument_not_contiguous_bit_field)
3671          << ArgNum << Arg->getSourceRange();
3672 }
3673 
3674 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3675                                        CallExpr *TheCall) {
3676   unsigned i = 0, l = 0, u = 0;
3677   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3678   llvm::APSInt Result;
3679 
3680   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3681     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3682            << TheCall->getSourceRange();
3683 
3684   switch (BuiltinID) {
3685   default: return false;
3686   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3687   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3688     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3689            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3690   case PPC::BI__builtin_altivec_dss:
3691     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3692   case PPC::BI__builtin_tbegin:
3693   case PPC::BI__builtin_tend:
3694     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 1) ||
3695            SemaFeatureCheck(*this, TheCall, "htm",
3696                             diag::err_ppc_builtin_requires_htm);
3697   case PPC::BI__builtin_tsr:
3698     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3699            SemaFeatureCheck(*this, TheCall, "htm",
3700                             diag::err_ppc_builtin_requires_htm);
3701   case PPC::BI__builtin_tabortwc:
3702   case PPC::BI__builtin_tabortdc:
3703     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3704            SemaFeatureCheck(*this, TheCall, "htm",
3705                             diag::err_ppc_builtin_requires_htm);
3706   case PPC::BI__builtin_tabortwci:
3707   case PPC::BI__builtin_tabortdci:
3708     return SemaFeatureCheck(*this, TheCall, "htm",
3709                             diag::err_ppc_builtin_requires_htm) ||
3710            (SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3711             SemaBuiltinConstantArgRange(TheCall, 2, 0, 31));
3712   case PPC::BI__builtin_tabort:
3713   case PPC::BI__builtin_tcheck:
3714   case PPC::BI__builtin_treclaim:
3715   case PPC::BI__builtin_trechkpt:
3716   case PPC::BI__builtin_tendall:
3717   case PPC::BI__builtin_tresume:
3718   case PPC::BI__builtin_tsuspend:
3719   case PPC::BI__builtin_get_texasr:
3720   case PPC::BI__builtin_get_texasru:
3721   case PPC::BI__builtin_get_tfhar:
3722   case PPC::BI__builtin_get_tfiar:
3723   case PPC::BI__builtin_set_texasr:
3724   case PPC::BI__builtin_set_texasru:
3725   case PPC::BI__builtin_set_tfhar:
3726   case PPC::BI__builtin_set_tfiar:
3727   case PPC::BI__builtin_ttest:
3728     return SemaFeatureCheck(*this, TheCall, "htm",
3729                             diag::err_ppc_builtin_requires_htm);
3730   // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05',
3731   // __builtin_(un)pack_longdouble are available only if long double uses IBM
3732   // extended double representation.
3733   case PPC::BI__builtin_unpack_longdouble:
3734     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1))
3735       return true;
3736     LLVM_FALLTHROUGH;
3737   case PPC::BI__builtin_pack_longdouble:
3738     if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble())
3739       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi)
3740              << "ibmlongdouble";
3741     return false;
3742   case PPC::BI__builtin_altivec_dst:
3743   case PPC::BI__builtin_altivec_dstt:
3744   case PPC::BI__builtin_altivec_dstst:
3745   case PPC::BI__builtin_altivec_dststt:
3746     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3747   case PPC::BI__builtin_vsx_xxpermdi:
3748   case PPC::BI__builtin_vsx_xxsldwi:
3749     return SemaBuiltinVSX(TheCall);
3750   case PPC::BI__builtin_divwe:
3751   case PPC::BI__builtin_divweu:
3752   case PPC::BI__builtin_divde:
3753   case PPC::BI__builtin_divdeu:
3754     return SemaFeatureCheck(*this, TheCall, "extdiv",
3755                             diag::err_ppc_builtin_only_on_arch, "7");
3756   case PPC::BI__builtin_bpermd:
3757     return SemaFeatureCheck(*this, TheCall, "bpermd",
3758                             diag::err_ppc_builtin_only_on_arch, "7");
3759   case PPC::BI__builtin_unpack_vector_int128:
3760     return SemaFeatureCheck(*this, TheCall, "vsx",
3761                             diag::err_ppc_builtin_only_on_arch, "7") ||
3762            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3763   case PPC::BI__builtin_pack_vector_int128:
3764     return SemaFeatureCheck(*this, TheCall, "vsx",
3765                             diag::err_ppc_builtin_only_on_arch, "7");
3766   case PPC::BI__builtin_altivec_vgnb:
3767      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3768   case PPC::BI__builtin_altivec_vec_replace_elt:
3769   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3770     QualType VecTy = TheCall->getArg(0)->getType();
3771     QualType EltTy = TheCall->getArg(1)->getType();
3772     unsigned Width = Context.getIntWidth(EltTy);
3773     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3774            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3775   }
3776   case PPC::BI__builtin_vsx_xxeval:
3777      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3778   case PPC::BI__builtin_altivec_vsldbi:
3779      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3780   case PPC::BI__builtin_altivec_vsrdbi:
3781      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3782   case PPC::BI__builtin_vsx_xxpermx:
3783      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3784   case PPC::BI__builtin_ppc_tw:
3785   case PPC::BI__builtin_ppc_tdw:
3786     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3787   case PPC::BI__builtin_ppc_cmpeqb:
3788   case PPC::BI__builtin_ppc_setb:
3789   case PPC::BI__builtin_ppc_maddhd:
3790   case PPC::BI__builtin_ppc_maddhdu:
3791   case PPC::BI__builtin_ppc_maddld:
3792     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3793                             diag::err_ppc_builtin_only_on_arch, "9");
3794   case PPC::BI__builtin_ppc_cmprb:
3795     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3796                             diag::err_ppc_builtin_only_on_arch, "9") ||
3797            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3798   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3799   // be a constant that represents a contiguous bit field.
3800   case PPC::BI__builtin_ppc_rlwnm:
3801     return SemaValueIsRunOfOnes(TheCall, 2);
3802   case PPC::BI__builtin_ppc_rlwimi:
3803   case PPC::BI__builtin_ppc_rldimi:
3804     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3805            SemaValueIsRunOfOnes(TheCall, 3);
3806   case PPC::BI__builtin_ppc_extract_exp:
3807   case PPC::BI__builtin_ppc_extract_sig:
3808   case PPC::BI__builtin_ppc_insert_exp:
3809     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3810                             diag::err_ppc_builtin_only_on_arch, "9");
3811   case PPC::BI__builtin_ppc_addex: {
3812     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3813                          diag::err_ppc_builtin_only_on_arch, "9") ||
3814         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
3815       return true;
3816     // Output warning for reserved values 1 to 3.
3817     int ArgValue =
3818         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
3819     if (ArgValue != 0)
3820       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
3821           << ArgValue;
3822     return false;
3823   }
3824   case PPC::BI__builtin_ppc_mtfsb0:
3825   case PPC::BI__builtin_ppc_mtfsb1:
3826     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3827   case PPC::BI__builtin_ppc_mtfsf:
3828     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3829   case PPC::BI__builtin_ppc_mtfsfi:
3830     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3831            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3832   case PPC::BI__builtin_ppc_alignx:
3833     return SemaBuiltinConstantArgPower2(TheCall, 0);
3834   case PPC::BI__builtin_ppc_rdlam:
3835     return SemaValueIsRunOfOnes(TheCall, 2);
3836   case PPC::BI__builtin_ppc_icbt:
3837   case PPC::BI__builtin_ppc_sthcx:
3838   case PPC::BI__builtin_ppc_stbcx:
3839   case PPC::BI__builtin_ppc_lharx:
3840   case PPC::BI__builtin_ppc_lbarx:
3841     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3842                             diag::err_ppc_builtin_only_on_arch, "8");
3843   case PPC::BI__builtin_vsx_ldrmb:
3844   case PPC::BI__builtin_vsx_strmb:
3845     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3846                             diag::err_ppc_builtin_only_on_arch, "8") ||
3847            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3848   case PPC::BI__builtin_altivec_vcntmbb:
3849   case PPC::BI__builtin_altivec_vcntmbh:
3850   case PPC::BI__builtin_altivec_vcntmbw:
3851   case PPC::BI__builtin_altivec_vcntmbd:
3852     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3853   case PPC::BI__builtin_darn:
3854   case PPC::BI__builtin_darn_raw:
3855   case PPC::BI__builtin_darn_32:
3856     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3857                             diag::err_ppc_builtin_only_on_arch, "9");
3858   case PPC::BI__builtin_vsx_xxgenpcvbm:
3859   case PPC::BI__builtin_vsx_xxgenpcvhm:
3860   case PPC::BI__builtin_vsx_xxgenpcvwm:
3861   case PPC::BI__builtin_vsx_xxgenpcvdm:
3862     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3863   case PPC::BI__builtin_ppc_compare_exp_uo:
3864   case PPC::BI__builtin_ppc_compare_exp_lt:
3865   case PPC::BI__builtin_ppc_compare_exp_gt:
3866   case PPC::BI__builtin_ppc_compare_exp_eq:
3867     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3868                             diag::err_ppc_builtin_only_on_arch, "9") ||
3869            SemaFeatureCheck(*this, TheCall, "vsx",
3870                             diag::err_ppc_builtin_requires_vsx);
3871   case PPC::BI__builtin_ppc_test_data_class: {
3872     // Check if the first argument of the __builtin_ppc_test_data_class call is
3873     // valid. The argument must be either a 'float' or a 'double'.
3874     QualType ArgType = TheCall->getArg(0)->getType();
3875     if (ArgType != QualType(Context.FloatTy) &&
3876         ArgType != QualType(Context.DoubleTy))
3877       return Diag(TheCall->getBeginLoc(),
3878                   diag::err_ppc_invalid_test_data_class_type);
3879     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3880                             diag::err_ppc_builtin_only_on_arch, "9") ||
3881            SemaFeatureCheck(*this, TheCall, "vsx",
3882                             diag::err_ppc_builtin_requires_vsx) ||
3883            SemaBuiltinConstantArgRange(TheCall, 1, 0, 127);
3884   }
3885   case PPC::BI__builtin_ppc_load8r:
3886   case PPC::BI__builtin_ppc_store8r:
3887     return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions",
3888                             diag::err_ppc_builtin_only_on_arch, "7");
3889 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc)                                 \
3890   case PPC::BI__builtin_##Name:                                                \
3891     return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types);
3892 #include "clang/Basic/BuiltinsPPC.def"
3893   }
3894   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3895 }
3896 
3897 // Check if the given type is a non-pointer PPC MMA type. This function is used
3898 // in Sema to prevent invalid uses of restricted PPC MMA types.
3899 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3900   if (Type->isPointerType() || Type->isArrayType())
3901     return false;
3902 
3903   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3904 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3905   if (false
3906 #include "clang/Basic/PPCTypes.def"
3907      ) {
3908     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3909     return true;
3910   }
3911   return false;
3912 }
3913 
3914 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3915                                           CallExpr *TheCall) {
3916   // position of memory order and scope arguments in the builtin
3917   unsigned OrderIndex, ScopeIndex;
3918   switch (BuiltinID) {
3919   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3920   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3921   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3922   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3923     OrderIndex = 2;
3924     ScopeIndex = 3;
3925     break;
3926   case AMDGPU::BI__builtin_amdgcn_fence:
3927     OrderIndex = 0;
3928     ScopeIndex = 1;
3929     break;
3930   default:
3931     return false;
3932   }
3933 
3934   ExprResult Arg = TheCall->getArg(OrderIndex);
3935   auto ArgExpr = Arg.get();
3936   Expr::EvalResult ArgResult;
3937 
3938   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3939     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3940            << ArgExpr->getType();
3941   auto Ord = ArgResult.Val.getInt().getZExtValue();
3942 
3943   // Check validity of memory ordering as per C11 / C++11's memody model.
3944   // Only fence needs check. Atomic dec/inc allow all memory orders.
3945   if (!llvm::isValidAtomicOrderingCABI(Ord))
3946     return Diag(ArgExpr->getBeginLoc(),
3947                 diag::warn_atomic_op_has_invalid_memory_order)
3948            << ArgExpr->getSourceRange();
3949   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3950   case llvm::AtomicOrderingCABI::relaxed:
3951   case llvm::AtomicOrderingCABI::consume:
3952     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3953       return Diag(ArgExpr->getBeginLoc(),
3954                   diag::warn_atomic_op_has_invalid_memory_order)
3955              << ArgExpr->getSourceRange();
3956     break;
3957   case llvm::AtomicOrderingCABI::acquire:
3958   case llvm::AtomicOrderingCABI::release:
3959   case llvm::AtomicOrderingCABI::acq_rel:
3960   case llvm::AtomicOrderingCABI::seq_cst:
3961     break;
3962   }
3963 
3964   Arg = TheCall->getArg(ScopeIndex);
3965   ArgExpr = Arg.get();
3966   Expr::EvalResult ArgResult1;
3967   // Check that sync scope is a constant literal
3968   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3969     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3970            << ArgExpr->getType();
3971 
3972   return false;
3973 }
3974 
3975 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3976   llvm::APSInt Result;
3977 
3978   // We can't check the value of a dependent argument.
3979   Expr *Arg = TheCall->getArg(ArgNum);
3980   if (Arg->isTypeDependent() || Arg->isValueDependent())
3981     return false;
3982 
3983   // Check constant-ness first.
3984   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3985     return true;
3986 
3987   int64_t Val = Result.getSExtValue();
3988   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3989     return false;
3990 
3991   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3992          << Arg->getSourceRange();
3993 }
3994 
3995 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3996                                          unsigned BuiltinID,
3997                                          CallExpr *TheCall) {
3998   // CodeGenFunction can also detect this, but this gives a better error
3999   // message.
4000   bool FeatureMissing = false;
4001   SmallVector<StringRef> ReqFeatures;
4002   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
4003   Features.split(ReqFeatures, ',');
4004 
4005   // Check if each required feature is included
4006   for (StringRef F : ReqFeatures) {
4007     SmallVector<StringRef> ReqOpFeatures;
4008     F.split(ReqOpFeatures, '|');
4009     bool HasFeature = false;
4010     for (StringRef OF : ReqOpFeatures) {
4011       if (TI.hasFeature(OF)) {
4012         HasFeature = true;
4013         continue;
4014       }
4015     }
4016 
4017     if (!HasFeature) {
4018       std::string FeatureStrs;
4019       for (StringRef OF : ReqOpFeatures) {
4020         // If the feature is 64bit, alter the string so it will print better in
4021         // the diagnostic.
4022         if (OF == "64bit")
4023           OF = "RV64";
4024 
4025         // Convert features like "zbr" and "experimental-zbr" to "Zbr".
4026         OF.consume_front("experimental-");
4027         std::string FeatureStr = OF.str();
4028         FeatureStr[0] = std::toupper(FeatureStr[0]);
4029         // Combine strings.
4030         FeatureStrs += FeatureStrs == "" ? "" : ", ";
4031         FeatureStrs += "'";
4032         FeatureStrs += FeatureStr;
4033         FeatureStrs += "'";
4034       }
4035       // Error message
4036       FeatureMissing = true;
4037       Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
4038           << TheCall->getSourceRange() << StringRef(FeatureStrs);
4039     }
4040   }
4041 
4042   if (FeatureMissing)
4043     return true;
4044 
4045   switch (BuiltinID) {
4046   case RISCVVector::BI__builtin_rvv_vsetvli:
4047     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
4048            CheckRISCVLMUL(TheCall, 2);
4049   case RISCVVector::BI__builtin_rvv_vsetvlimax:
4050     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
4051            CheckRISCVLMUL(TheCall, 1);
4052   }
4053 
4054   return false;
4055 }
4056 
4057 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
4058                                            CallExpr *TheCall) {
4059   if (BuiltinID == SystemZ::BI__builtin_tabort) {
4060     Expr *Arg = TheCall->getArg(0);
4061     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
4062       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
4063         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
4064                << Arg->getSourceRange();
4065   }
4066 
4067   // For intrinsics which take an immediate value as part of the instruction,
4068   // range check them here.
4069   unsigned i = 0, l = 0, u = 0;
4070   switch (BuiltinID) {
4071   default: return false;
4072   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
4073   case SystemZ::BI__builtin_s390_verimb:
4074   case SystemZ::BI__builtin_s390_verimh:
4075   case SystemZ::BI__builtin_s390_verimf:
4076   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
4077   case SystemZ::BI__builtin_s390_vfaeb:
4078   case SystemZ::BI__builtin_s390_vfaeh:
4079   case SystemZ::BI__builtin_s390_vfaef:
4080   case SystemZ::BI__builtin_s390_vfaebs:
4081   case SystemZ::BI__builtin_s390_vfaehs:
4082   case SystemZ::BI__builtin_s390_vfaefs:
4083   case SystemZ::BI__builtin_s390_vfaezb:
4084   case SystemZ::BI__builtin_s390_vfaezh:
4085   case SystemZ::BI__builtin_s390_vfaezf:
4086   case SystemZ::BI__builtin_s390_vfaezbs:
4087   case SystemZ::BI__builtin_s390_vfaezhs:
4088   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
4089   case SystemZ::BI__builtin_s390_vfisb:
4090   case SystemZ::BI__builtin_s390_vfidb:
4091     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
4092            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
4093   case SystemZ::BI__builtin_s390_vftcisb:
4094   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
4095   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
4096   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
4097   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
4098   case SystemZ::BI__builtin_s390_vstrcb:
4099   case SystemZ::BI__builtin_s390_vstrch:
4100   case SystemZ::BI__builtin_s390_vstrcf:
4101   case SystemZ::BI__builtin_s390_vstrczb:
4102   case SystemZ::BI__builtin_s390_vstrczh:
4103   case SystemZ::BI__builtin_s390_vstrczf:
4104   case SystemZ::BI__builtin_s390_vstrcbs:
4105   case SystemZ::BI__builtin_s390_vstrchs:
4106   case SystemZ::BI__builtin_s390_vstrcfs:
4107   case SystemZ::BI__builtin_s390_vstrczbs:
4108   case SystemZ::BI__builtin_s390_vstrczhs:
4109   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
4110   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
4111   case SystemZ::BI__builtin_s390_vfminsb:
4112   case SystemZ::BI__builtin_s390_vfmaxsb:
4113   case SystemZ::BI__builtin_s390_vfmindb:
4114   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
4115   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
4116   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
4117   case SystemZ::BI__builtin_s390_vclfnhs:
4118   case SystemZ::BI__builtin_s390_vclfnls:
4119   case SystemZ::BI__builtin_s390_vcfn:
4120   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
4121   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
4122   }
4123   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
4124 }
4125 
4126 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
4127 /// This checks that the target supports __builtin_cpu_supports and
4128 /// that the string argument is constant and valid.
4129 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
4130                                    CallExpr *TheCall) {
4131   Expr *Arg = TheCall->getArg(0);
4132 
4133   // Check if the argument is a string literal.
4134   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4135     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4136            << Arg->getSourceRange();
4137 
4138   // Check the contents of the string.
4139   StringRef Feature =
4140       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4141   if (!TI.validateCpuSupports(Feature))
4142     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
4143            << Arg->getSourceRange();
4144   return false;
4145 }
4146 
4147 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
4148 /// This checks that the target supports __builtin_cpu_is and
4149 /// that the string argument is constant and valid.
4150 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
4151   Expr *Arg = TheCall->getArg(0);
4152 
4153   // Check if the argument is a string literal.
4154   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4155     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4156            << Arg->getSourceRange();
4157 
4158   // Check the contents of the string.
4159   StringRef Feature =
4160       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4161   if (!TI.validateCpuIs(Feature))
4162     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
4163            << Arg->getSourceRange();
4164   return false;
4165 }
4166 
4167 // Check if the rounding mode is legal.
4168 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
4169   // Indicates if this instruction has rounding control or just SAE.
4170   bool HasRC = false;
4171 
4172   unsigned ArgNum = 0;
4173   switch (BuiltinID) {
4174   default:
4175     return false;
4176   case X86::BI__builtin_ia32_vcvttsd2si32:
4177   case X86::BI__builtin_ia32_vcvttsd2si64:
4178   case X86::BI__builtin_ia32_vcvttsd2usi32:
4179   case X86::BI__builtin_ia32_vcvttsd2usi64:
4180   case X86::BI__builtin_ia32_vcvttss2si32:
4181   case X86::BI__builtin_ia32_vcvttss2si64:
4182   case X86::BI__builtin_ia32_vcvttss2usi32:
4183   case X86::BI__builtin_ia32_vcvttss2usi64:
4184   case X86::BI__builtin_ia32_vcvttsh2si32:
4185   case X86::BI__builtin_ia32_vcvttsh2si64:
4186   case X86::BI__builtin_ia32_vcvttsh2usi32:
4187   case X86::BI__builtin_ia32_vcvttsh2usi64:
4188     ArgNum = 1;
4189     break;
4190   case X86::BI__builtin_ia32_maxpd512:
4191   case X86::BI__builtin_ia32_maxps512:
4192   case X86::BI__builtin_ia32_minpd512:
4193   case X86::BI__builtin_ia32_minps512:
4194   case X86::BI__builtin_ia32_maxph512:
4195   case X86::BI__builtin_ia32_minph512:
4196     ArgNum = 2;
4197     break;
4198   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
4199   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
4200   case X86::BI__builtin_ia32_cvtps2pd512_mask:
4201   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
4202   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
4203   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
4204   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
4205   case X86::BI__builtin_ia32_cvttps2dq512_mask:
4206   case X86::BI__builtin_ia32_cvttps2qq512_mask:
4207   case X86::BI__builtin_ia32_cvttps2udq512_mask:
4208   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
4209   case X86::BI__builtin_ia32_vcvttph2w512_mask:
4210   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
4211   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
4212   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
4213   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
4214   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
4215   case X86::BI__builtin_ia32_exp2pd_mask:
4216   case X86::BI__builtin_ia32_exp2ps_mask:
4217   case X86::BI__builtin_ia32_getexppd512_mask:
4218   case X86::BI__builtin_ia32_getexpps512_mask:
4219   case X86::BI__builtin_ia32_getexpph512_mask:
4220   case X86::BI__builtin_ia32_rcp28pd_mask:
4221   case X86::BI__builtin_ia32_rcp28ps_mask:
4222   case X86::BI__builtin_ia32_rsqrt28pd_mask:
4223   case X86::BI__builtin_ia32_rsqrt28ps_mask:
4224   case X86::BI__builtin_ia32_vcomisd:
4225   case X86::BI__builtin_ia32_vcomiss:
4226   case X86::BI__builtin_ia32_vcomish:
4227   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
4228     ArgNum = 3;
4229     break;
4230   case X86::BI__builtin_ia32_cmppd512_mask:
4231   case X86::BI__builtin_ia32_cmpps512_mask:
4232   case X86::BI__builtin_ia32_cmpsd_mask:
4233   case X86::BI__builtin_ia32_cmpss_mask:
4234   case X86::BI__builtin_ia32_cmpsh_mask:
4235   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
4236   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
4237   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
4238   case X86::BI__builtin_ia32_getexpsd128_round_mask:
4239   case X86::BI__builtin_ia32_getexpss128_round_mask:
4240   case X86::BI__builtin_ia32_getexpsh128_round_mask:
4241   case X86::BI__builtin_ia32_getmantpd512_mask:
4242   case X86::BI__builtin_ia32_getmantps512_mask:
4243   case X86::BI__builtin_ia32_getmantph512_mask:
4244   case X86::BI__builtin_ia32_maxsd_round_mask:
4245   case X86::BI__builtin_ia32_maxss_round_mask:
4246   case X86::BI__builtin_ia32_maxsh_round_mask:
4247   case X86::BI__builtin_ia32_minsd_round_mask:
4248   case X86::BI__builtin_ia32_minss_round_mask:
4249   case X86::BI__builtin_ia32_minsh_round_mask:
4250   case X86::BI__builtin_ia32_rcp28sd_round_mask:
4251   case X86::BI__builtin_ia32_rcp28ss_round_mask:
4252   case X86::BI__builtin_ia32_reducepd512_mask:
4253   case X86::BI__builtin_ia32_reduceps512_mask:
4254   case X86::BI__builtin_ia32_reduceph512_mask:
4255   case X86::BI__builtin_ia32_rndscalepd_mask:
4256   case X86::BI__builtin_ia32_rndscaleps_mask:
4257   case X86::BI__builtin_ia32_rndscaleph_mask:
4258   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
4259   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
4260     ArgNum = 4;
4261     break;
4262   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4263   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4264   case X86::BI__builtin_ia32_fixupimmps512_mask:
4265   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4266   case X86::BI__builtin_ia32_fixupimmsd_mask:
4267   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4268   case X86::BI__builtin_ia32_fixupimmss_mask:
4269   case X86::BI__builtin_ia32_fixupimmss_maskz:
4270   case X86::BI__builtin_ia32_getmantsd_round_mask:
4271   case X86::BI__builtin_ia32_getmantss_round_mask:
4272   case X86::BI__builtin_ia32_getmantsh_round_mask:
4273   case X86::BI__builtin_ia32_rangepd512_mask:
4274   case X86::BI__builtin_ia32_rangeps512_mask:
4275   case X86::BI__builtin_ia32_rangesd128_round_mask:
4276   case X86::BI__builtin_ia32_rangess128_round_mask:
4277   case X86::BI__builtin_ia32_reducesd_mask:
4278   case X86::BI__builtin_ia32_reducess_mask:
4279   case X86::BI__builtin_ia32_reducesh_mask:
4280   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4281   case X86::BI__builtin_ia32_rndscaless_round_mask:
4282   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4283     ArgNum = 5;
4284     break;
4285   case X86::BI__builtin_ia32_vcvtsd2si64:
4286   case X86::BI__builtin_ia32_vcvtsd2si32:
4287   case X86::BI__builtin_ia32_vcvtsd2usi32:
4288   case X86::BI__builtin_ia32_vcvtsd2usi64:
4289   case X86::BI__builtin_ia32_vcvtss2si32:
4290   case X86::BI__builtin_ia32_vcvtss2si64:
4291   case X86::BI__builtin_ia32_vcvtss2usi32:
4292   case X86::BI__builtin_ia32_vcvtss2usi64:
4293   case X86::BI__builtin_ia32_vcvtsh2si32:
4294   case X86::BI__builtin_ia32_vcvtsh2si64:
4295   case X86::BI__builtin_ia32_vcvtsh2usi32:
4296   case X86::BI__builtin_ia32_vcvtsh2usi64:
4297   case X86::BI__builtin_ia32_sqrtpd512:
4298   case X86::BI__builtin_ia32_sqrtps512:
4299   case X86::BI__builtin_ia32_sqrtph512:
4300     ArgNum = 1;
4301     HasRC = true;
4302     break;
4303   case X86::BI__builtin_ia32_addph512:
4304   case X86::BI__builtin_ia32_divph512:
4305   case X86::BI__builtin_ia32_mulph512:
4306   case X86::BI__builtin_ia32_subph512:
4307   case X86::BI__builtin_ia32_addpd512:
4308   case X86::BI__builtin_ia32_addps512:
4309   case X86::BI__builtin_ia32_divpd512:
4310   case X86::BI__builtin_ia32_divps512:
4311   case X86::BI__builtin_ia32_mulpd512:
4312   case X86::BI__builtin_ia32_mulps512:
4313   case X86::BI__builtin_ia32_subpd512:
4314   case X86::BI__builtin_ia32_subps512:
4315   case X86::BI__builtin_ia32_cvtsi2sd64:
4316   case X86::BI__builtin_ia32_cvtsi2ss32:
4317   case X86::BI__builtin_ia32_cvtsi2ss64:
4318   case X86::BI__builtin_ia32_cvtusi2sd64:
4319   case X86::BI__builtin_ia32_cvtusi2ss32:
4320   case X86::BI__builtin_ia32_cvtusi2ss64:
4321   case X86::BI__builtin_ia32_vcvtusi2sh:
4322   case X86::BI__builtin_ia32_vcvtusi642sh:
4323   case X86::BI__builtin_ia32_vcvtsi2sh:
4324   case X86::BI__builtin_ia32_vcvtsi642sh:
4325     ArgNum = 2;
4326     HasRC = true;
4327     break;
4328   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
4329   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
4330   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
4331   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
4332   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
4333   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
4334   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
4335   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
4336   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
4337   case X86::BI__builtin_ia32_cvtps2dq512_mask:
4338   case X86::BI__builtin_ia32_cvtps2qq512_mask:
4339   case X86::BI__builtin_ia32_cvtps2udq512_mask:
4340   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
4341   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
4342   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
4343   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
4344   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
4345   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
4346   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
4347   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
4348   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
4349   case X86::BI__builtin_ia32_vcvtph2w512_mask:
4350   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
4351   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
4352   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
4353   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
4354   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
4355   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
4356   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
4357     ArgNum = 3;
4358     HasRC = true;
4359     break;
4360   case X86::BI__builtin_ia32_addsh_round_mask:
4361   case X86::BI__builtin_ia32_addss_round_mask:
4362   case X86::BI__builtin_ia32_addsd_round_mask:
4363   case X86::BI__builtin_ia32_divsh_round_mask:
4364   case X86::BI__builtin_ia32_divss_round_mask:
4365   case X86::BI__builtin_ia32_divsd_round_mask:
4366   case X86::BI__builtin_ia32_mulsh_round_mask:
4367   case X86::BI__builtin_ia32_mulss_round_mask:
4368   case X86::BI__builtin_ia32_mulsd_round_mask:
4369   case X86::BI__builtin_ia32_subsh_round_mask:
4370   case X86::BI__builtin_ia32_subss_round_mask:
4371   case X86::BI__builtin_ia32_subsd_round_mask:
4372   case X86::BI__builtin_ia32_scalefph512_mask:
4373   case X86::BI__builtin_ia32_scalefpd512_mask:
4374   case X86::BI__builtin_ia32_scalefps512_mask:
4375   case X86::BI__builtin_ia32_scalefsd_round_mask:
4376   case X86::BI__builtin_ia32_scalefss_round_mask:
4377   case X86::BI__builtin_ia32_scalefsh_round_mask:
4378   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4379   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4380   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4381   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4382   case X86::BI__builtin_ia32_sqrtss_round_mask:
4383   case X86::BI__builtin_ia32_sqrtsh_round_mask:
4384   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4385   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4386   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4387   case X86::BI__builtin_ia32_vfmaddss3_mask:
4388   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4389   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4390   case X86::BI__builtin_ia32_vfmaddsh3_mask:
4391   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4392   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4393   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4394   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4395   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4396   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4397   case X86::BI__builtin_ia32_vfmaddps512_mask:
4398   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4399   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4400   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4401   case X86::BI__builtin_ia32_vfmaddph512_mask:
4402   case X86::BI__builtin_ia32_vfmaddph512_maskz:
4403   case X86::BI__builtin_ia32_vfmaddph512_mask3:
4404   case X86::BI__builtin_ia32_vfmsubph512_mask3:
4405   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4406   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4407   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4408   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4409   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4410   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4411   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4412   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4413   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4414   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4415   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4416   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4417   case X86::BI__builtin_ia32_vfmaddcsh_mask:
4418   case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
4419   case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
4420   case X86::BI__builtin_ia32_vfmaddcph512_mask:
4421   case X86::BI__builtin_ia32_vfmaddcph512_maskz:
4422   case X86::BI__builtin_ia32_vfmaddcph512_mask3:
4423   case X86::BI__builtin_ia32_vfcmaddcsh_mask:
4424   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
4425   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
4426   case X86::BI__builtin_ia32_vfcmaddcph512_mask:
4427   case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
4428   case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
4429   case X86::BI__builtin_ia32_vfmulcsh_mask:
4430   case X86::BI__builtin_ia32_vfmulcph512_mask:
4431   case X86::BI__builtin_ia32_vfcmulcsh_mask:
4432   case X86::BI__builtin_ia32_vfcmulcph512_mask:
4433     ArgNum = 4;
4434     HasRC = true;
4435     break;
4436   }
4437 
4438   llvm::APSInt Result;
4439 
4440   // We can't check the value of a dependent argument.
4441   Expr *Arg = TheCall->getArg(ArgNum);
4442   if (Arg->isTypeDependent() || Arg->isValueDependent())
4443     return false;
4444 
4445   // Check constant-ness first.
4446   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4447     return true;
4448 
4449   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4450   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4451   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4452   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4453   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4454       Result == 8/*ROUND_NO_EXC*/ ||
4455       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4456       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4457     return false;
4458 
4459   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4460          << Arg->getSourceRange();
4461 }
4462 
4463 // Check if the gather/scatter scale is legal.
4464 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4465                                              CallExpr *TheCall) {
4466   unsigned ArgNum = 0;
4467   switch (BuiltinID) {
4468   default:
4469     return false;
4470   case X86::BI__builtin_ia32_gatherpfdpd:
4471   case X86::BI__builtin_ia32_gatherpfdps:
4472   case X86::BI__builtin_ia32_gatherpfqpd:
4473   case X86::BI__builtin_ia32_gatherpfqps:
4474   case X86::BI__builtin_ia32_scatterpfdpd:
4475   case X86::BI__builtin_ia32_scatterpfdps:
4476   case X86::BI__builtin_ia32_scatterpfqpd:
4477   case X86::BI__builtin_ia32_scatterpfqps:
4478     ArgNum = 3;
4479     break;
4480   case X86::BI__builtin_ia32_gatherd_pd:
4481   case X86::BI__builtin_ia32_gatherd_pd256:
4482   case X86::BI__builtin_ia32_gatherq_pd:
4483   case X86::BI__builtin_ia32_gatherq_pd256:
4484   case X86::BI__builtin_ia32_gatherd_ps:
4485   case X86::BI__builtin_ia32_gatherd_ps256:
4486   case X86::BI__builtin_ia32_gatherq_ps:
4487   case X86::BI__builtin_ia32_gatherq_ps256:
4488   case X86::BI__builtin_ia32_gatherd_q:
4489   case X86::BI__builtin_ia32_gatherd_q256:
4490   case X86::BI__builtin_ia32_gatherq_q:
4491   case X86::BI__builtin_ia32_gatherq_q256:
4492   case X86::BI__builtin_ia32_gatherd_d:
4493   case X86::BI__builtin_ia32_gatherd_d256:
4494   case X86::BI__builtin_ia32_gatherq_d:
4495   case X86::BI__builtin_ia32_gatherq_d256:
4496   case X86::BI__builtin_ia32_gather3div2df:
4497   case X86::BI__builtin_ia32_gather3div2di:
4498   case X86::BI__builtin_ia32_gather3div4df:
4499   case X86::BI__builtin_ia32_gather3div4di:
4500   case X86::BI__builtin_ia32_gather3div4sf:
4501   case X86::BI__builtin_ia32_gather3div4si:
4502   case X86::BI__builtin_ia32_gather3div8sf:
4503   case X86::BI__builtin_ia32_gather3div8si:
4504   case X86::BI__builtin_ia32_gather3siv2df:
4505   case X86::BI__builtin_ia32_gather3siv2di:
4506   case X86::BI__builtin_ia32_gather3siv4df:
4507   case X86::BI__builtin_ia32_gather3siv4di:
4508   case X86::BI__builtin_ia32_gather3siv4sf:
4509   case X86::BI__builtin_ia32_gather3siv4si:
4510   case X86::BI__builtin_ia32_gather3siv8sf:
4511   case X86::BI__builtin_ia32_gather3siv8si:
4512   case X86::BI__builtin_ia32_gathersiv8df:
4513   case X86::BI__builtin_ia32_gathersiv16sf:
4514   case X86::BI__builtin_ia32_gatherdiv8df:
4515   case X86::BI__builtin_ia32_gatherdiv16sf:
4516   case X86::BI__builtin_ia32_gathersiv8di:
4517   case X86::BI__builtin_ia32_gathersiv16si:
4518   case X86::BI__builtin_ia32_gatherdiv8di:
4519   case X86::BI__builtin_ia32_gatherdiv16si:
4520   case X86::BI__builtin_ia32_scatterdiv2df:
4521   case X86::BI__builtin_ia32_scatterdiv2di:
4522   case X86::BI__builtin_ia32_scatterdiv4df:
4523   case X86::BI__builtin_ia32_scatterdiv4di:
4524   case X86::BI__builtin_ia32_scatterdiv4sf:
4525   case X86::BI__builtin_ia32_scatterdiv4si:
4526   case X86::BI__builtin_ia32_scatterdiv8sf:
4527   case X86::BI__builtin_ia32_scatterdiv8si:
4528   case X86::BI__builtin_ia32_scattersiv2df:
4529   case X86::BI__builtin_ia32_scattersiv2di:
4530   case X86::BI__builtin_ia32_scattersiv4df:
4531   case X86::BI__builtin_ia32_scattersiv4di:
4532   case X86::BI__builtin_ia32_scattersiv4sf:
4533   case X86::BI__builtin_ia32_scattersiv4si:
4534   case X86::BI__builtin_ia32_scattersiv8sf:
4535   case X86::BI__builtin_ia32_scattersiv8si:
4536   case X86::BI__builtin_ia32_scattersiv8df:
4537   case X86::BI__builtin_ia32_scattersiv16sf:
4538   case X86::BI__builtin_ia32_scatterdiv8df:
4539   case X86::BI__builtin_ia32_scatterdiv16sf:
4540   case X86::BI__builtin_ia32_scattersiv8di:
4541   case X86::BI__builtin_ia32_scattersiv16si:
4542   case X86::BI__builtin_ia32_scatterdiv8di:
4543   case X86::BI__builtin_ia32_scatterdiv16si:
4544     ArgNum = 4;
4545     break;
4546   }
4547 
4548   llvm::APSInt Result;
4549 
4550   // We can't check the value of a dependent argument.
4551   Expr *Arg = TheCall->getArg(ArgNum);
4552   if (Arg->isTypeDependent() || Arg->isValueDependent())
4553     return false;
4554 
4555   // Check constant-ness first.
4556   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4557     return true;
4558 
4559   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4560     return false;
4561 
4562   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4563          << Arg->getSourceRange();
4564 }
4565 
4566 enum { TileRegLow = 0, TileRegHigh = 7 };
4567 
4568 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4569                                              ArrayRef<int> ArgNums) {
4570   for (int ArgNum : ArgNums) {
4571     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4572       return true;
4573   }
4574   return false;
4575 }
4576 
4577 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4578                                         ArrayRef<int> ArgNums) {
4579   // Because the max number of tile register is TileRegHigh + 1, so here we use
4580   // each bit to represent the usage of them in bitset.
4581   std::bitset<TileRegHigh + 1> ArgValues;
4582   for (int ArgNum : ArgNums) {
4583     Expr *Arg = TheCall->getArg(ArgNum);
4584     if (Arg->isTypeDependent() || Arg->isValueDependent())
4585       continue;
4586 
4587     llvm::APSInt Result;
4588     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4589       return true;
4590     int ArgExtValue = Result.getExtValue();
4591     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4592            "Incorrect tile register num.");
4593     if (ArgValues.test(ArgExtValue))
4594       return Diag(TheCall->getBeginLoc(),
4595                   diag::err_x86_builtin_tile_arg_duplicate)
4596              << TheCall->getArg(ArgNum)->getSourceRange();
4597     ArgValues.set(ArgExtValue);
4598   }
4599   return false;
4600 }
4601 
4602 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4603                                                 ArrayRef<int> ArgNums) {
4604   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4605          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4606 }
4607 
4608 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4609   switch (BuiltinID) {
4610   default:
4611     return false;
4612   case X86::BI__builtin_ia32_tileloadd64:
4613   case X86::BI__builtin_ia32_tileloaddt164:
4614   case X86::BI__builtin_ia32_tilestored64:
4615   case X86::BI__builtin_ia32_tilezero:
4616     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4617   case X86::BI__builtin_ia32_tdpbssd:
4618   case X86::BI__builtin_ia32_tdpbsud:
4619   case X86::BI__builtin_ia32_tdpbusd:
4620   case X86::BI__builtin_ia32_tdpbuud:
4621   case X86::BI__builtin_ia32_tdpbf16ps:
4622     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4623   }
4624 }
4625 static bool isX86_32Builtin(unsigned BuiltinID) {
4626   // These builtins only work on x86-32 targets.
4627   switch (BuiltinID) {
4628   case X86::BI__builtin_ia32_readeflags_u32:
4629   case X86::BI__builtin_ia32_writeeflags_u32:
4630     return true;
4631   }
4632 
4633   return false;
4634 }
4635 
4636 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4637                                        CallExpr *TheCall) {
4638   if (BuiltinID == X86::BI__builtin_cpu_supports)
4639     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4640 
4641   if (BuiltinID == X86::BI__builtin_cpu_is)
4642     return SemaBuiltinCpuIs(*this, TI, TheCall);
4643 
4644   // Check for 32-bit only builtins on a 64-bit target.
4645   const llvm::Triple &TT = TI.getTriple();
4646   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4647     return Diag(TheCall->getCallee()->getBeginLoc(),
4648                 diag::err_32_bit_builtin_64_bit_tgt);
4649 
4650   // If the intrinsic has rounding or SAE make sure its valid.
4651   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4652     return true;
4653 
4654   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4655   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4656     return true;
4657 
4658   // If the intrinsic has a tile arguments, make sure they are valid.
4659   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4660     return true;
4661 
4662   // For intrinsics which take an immediate value as part of the instruction,
4663   // range check them here.
4664   int i = 0, l = 0, u = 0;
4665   switch (BuiltinID) {
4666   default:
4667     return false;
4668   case X86::BI__builtin_ia32_vec_ext_v2si:
4669   case X86::BI__builtin_ia32_vec_ext_v2di:
4670   case X86::BI__builtin_ia32_vextractf128_pd256:
4671   case X86::BI__builtin_ia32_vextractf128_ps256:
4672   case X86::BI__builtin_ia32_vextractf128_si256:
4673   case X86::BI__builtin_ia32_extract128i256:
4674   case X86::BI__builtin_ia32_extractf64x4_mask:
4675   case X86::BI__builtin_ia32_extracti64x4_mask:
4676   case X86::BI__builtin_ia32_extractf32x8_mask:
4677   case X86::BI__builtin_ia32_extracti32x8_mask:
4678   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4679   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4680   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4681   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4682     i = 1; l = 0; u = 1;
4683     break;
4684   case X86::BI__builtin_ia32_vec_set_v2di:
4685   case X86::BI__builtin_ia32_vinsertf128_pd256:
4686   case X86::BI__builtin_ia32_vinsertf128_ps256:
4687   case X86::BI__builtin_ia32_vinsertf128_si256:
4688   case X86::BI__builtin_ia32_insert128i256:
4689   case X86::BI__builtin_ia32_insertf32x8:
4690   case X86::BI__builtin_ia32_inserti32x8:
4691   case X86::BI__builtin_ia32_insertf64x4:
4692   case X86::BI__builtin_ia32_inserti64x4:
4693   case X86::BI__builtin_ia32_insertf64x2_256:
4694   case X86::BI__builtin_ia32_inserti64x2_256:
4695   case X86::BI__builtin_ia32_insertf32x4_256:
4696   case X86::BI__builtin_ia32_inserti32x4_256:
4697     i = 2; l = 0; u = 1;
4698     break;
4699   case X86::BI__builtin_ia32_vpermilpd:
4700   case X86::BI__builtin_ia32_vec_ext_v4hi:
4701   case X86::BI__builtin_ia32_vec_ext_v4si:
4702   case X86::BI__builtin_ia32_vec_ext_v4sf:
4703   case X86::BI__builtin_ia32_vec_ext_v4di:
4704   case X86::BI__builtin_ia32_extractf32x4_mask:
4705   case X86::BI__builtin_ia32_extracti32x4_mask:
4706   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4707   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4708     i = 1; l = 0; u = 3;
4709     break;
4710   case X86::BI_mm_prefetch:
4711   case X86::BI__builtin_ia32_vec_ext_v8hi:
4712   case X86::BI__builtin_ia32_vec_ext_v8si:
4713     i = 1; l = 0; u = 7;
4714     break;
4715   case X86::BI__builtin_ia32_sha1rnds4:
4716   case X86::BI__builtin_ia32_blendpd:
4717   case X86::BI__builtin_ia32_shufpd:
4718   case X86::BI__builtin_ia32_vec_set_v4hi:
4719   case X86::BI__builtin_ia32_vec_set_v4si:
4720   case X86::BI__builtin_ia32_vec_set_v4di:
4721   case X86::BI__builtin_ia32_shuf_f32x4_256:
4722   case X86::BI__builtin_ia32_shuf_f64x2_256:
4723   case X86::BI__builtin_ia32_shuf_i32x4_256:
4724   case X86::BI__builtin_ia32_shuf_i64x2_256:
4725   case X86::BI__builtin_ia32_insertf64x2_512:
4726   case X86::BI__builtin_ia32_inserti64x2_512:
4727   case X86::BI__builtin_ia32_insertf32x4:
4728   case X86::BI__builtin_ia32_inserti32x4:
4729     i = 2; l = 0; u = 3;
4730     break;
4731   case X86::BI__builtin_ia32_vpermil2pd:
4732   case X86::BI__builtin_ia32_vpermil2pd256:
4733   case X86::BI__builtin_ia32_vpermil2ps:
4734   case X86::BI__builtin_ia32_vpermil2ps256:
4735     i = 3; l = 0; u = 3;
4736     break;
4737   case X86::BI__builtin_ia32_cmpb128_mask:
4738   case X86::BI__builtin_ia32_cmpw128_mask:
4739   case X86::BI__builtin_ia32_cmpd128_mask:
4740   case X86::BI__builtin_ia32_cmpq128_mask:
4741   case X86::BI__builtin_ia32_cmpb256_mask:
4742   case X86::BI__builtin_ia32_cmpw256_mask:
4743   case X86::BI__builtin_ia32_cmpd256_mask:
4744   case X86::BI__builtin_ia32_cmpq256_mask:
4745   case X86::BI__builtin_ia32_cmpb512_mask:
4746   case X86::BI__builtin_ia32_cmpw512_mask:
4747   case X86::BI__builtin_ia32_cmpd512_mask:
4748   case X86::BI__builtin_ia32_cmpq512_mask:
4749   case X86::BI__builtin_ia32_ucmpb128_mask:
4750   case X86::BI__builtin_ia32_ucmpw128_mask:
4751   case X86::BI__builtin_ia32_ucmpd128_mask:
4752   case X86::BI__builtin_ia32_ucmpq128_mask:
4753   case X86::BI__builtin_ia32_ucmpb256_mask:
4754   case X86::BI__builtin_ia32_ucmpw256_mask:
4755   case X86::BI__builtin_ia32_ucmpd256_mask:
4756   case X86::BI__builtin_ia32_ucmpq256_mask:
4757   case X86::BI__builtin_ia32_ucmpb512_mask:
4758   case X86::BI__builtin_ia32_ucmpw512_mask:
4759   case X86::BI__builtin_ia32_ucmpd512_mask:
4760   case X86::BI__builtin_ia32_ucmpq512_mask:
4761   case X86::BI__builtin_ia32_vpcomub:
4762   case X86::BI__builtin_ia32_vpcomuw:
4763   case X86::BI__builtin_ia32_vpcomud:
4764   case X86::BI__builtin_ia32_vpcomuq:
4765   case X86::BI__builtin_ia32_vpcomb:
4766   case X86::BI__builtin_ia32_vpcomw:
4767   case X86::BI__builtin_ia32_vpcomd:
4768   case X86::BI__builtin_ia32_vpcomq:
4769   case X86::BI__builtin_ia32_vec_set_v8hi:
4770   case X86::BI__builtin_ia32_vec_set_v8si:
4771     i = 2; l = 0; u = 7;
4772     break;
4773   case X86::BI__builtin_ia32_vpermilpd256:
4774   case X86::BI__builtin_ia32_roundps:
4775   case X86::BI__builtin_ia32_roundpd:
4776   case X86::BI__builtin_ia32_roundps256:
4777   case X86::BI__builtin_ia32_roundpd256:
4778   case X86::BI__builtin_ia32_getmantpd128_mask:
4779   case X86::BI__builtin_ia32_getmantpd256_mask:
4780   case X86::BI__builtin_ia32_getmantps128_mask:
4781   case X86::BI__builtin_ia32_getmantps256_mask:
4782   case X86::BI__builtin_ia32_getmantpd512_mask:
4783   case X86::BI__builtin_ia32_getmantps512_mask:
4784   case X86::BI__builtin_ia32_getmantph128_mask:
4785   case X86::BI__builtin_ia32_getmantph256_mask:
4786   case X86::BI__builtin_ia32_getmantph512_mask:
4787   case X86::BI__builtin_ia32_vec_ext_v16qi:
4788   case X86::BI__builtin_ia32_vec_ext_v16hi:
4789     i = 1; l = 0; u = 15;
4790     break;
4791   case X86::BI__builtin_ia32_pblendd128:
4792   case X86::BI__builtin_ia32_blendps:
4793   case X86::BI__builtin_ia32_blendpd256:
4794   case X86::BI__builtin_ia32_shufpd256:
4795   case X86::BI__builtin_ia32_roundss:
4796   case X86::BI__builtin_ia32_roundsd:
4797   case X86::BI__builtin_ia32_rangepd128_mask:
4798   case X86::BI__builtin_ia32_rangepd256_mask:
4799   case X86::BI__builtin_ia32_rangepd512_mask:
4800   case X86::BI__builtin_ia32_rangeps128_mask:
4801   case X86::BI__builtin_ia32_rangeps256_mask:
4802   case X86::BI__builtin_ia32_rangeps512_mask:
4803   case X86::BI__builtin_ia32_getmantsd_round_mask:
4804   case X86::BI__builtin_ia32_getmantss_round_mask:
4805   case X86::BI__builtin_ia32_getmantsh_round_mask:
4806   case X86::BI__builtin_ia32_vec_set_v16qi:
4807   case X86::BI__builtin_ia32_vec_set_v16hi:
4808     i = 2; l = 0; u = 15;
4809     break;
4810   case X86::BI__builtin_ia32_vec_ext_v32qi:
4811     i = 1; l = 0; u = 31;
4812     break;
4813   case X86::BI__builtin_ia32_cmpps:
4814   case X86::BI__builtin_ia32_cmpss:
4815   case X86::BI__builtin_ia32_cmppd:
4816   case X86::BI__builtin_ia32_cmpsd:
4817   case X86::BI__builtin_ia32_cmpps256:
4818   case X86::BI__builtin_ia32_cmppd256:
4819   case X86::BI__builtin_ia32_cmpps128_mask:
4820   case X86::BI__builtin_ia32_cmppd128_mask:
4821   case X86::BI__builtin_ia32_cmpps256_mask:
4822   case X86::BI__builtin_ia32_cmppd256_mask:
4823   case X86::BI__builtin_ia32_cmpps512_mask:
4824   case X86::BI__builtin_ia32_cmppd512_mask:
4825   case X86::BI__builtin_ia32_cmpsd_mask:
4826   case X86::BI__builtin_ia32_cmpss_mask:
4827   case X86::BI__builtin_ia32_vec_set_v32qi:
4828     i = 2; l = 0; u = 31;
4829     break;
4830   case X86::BI__builtin_ia32_permdf256:
4831   case X86::BI__builtin_ia32_permdi256:
4832   case X86::BI__builtin_ia32_permdf512:
4833   case X86::BI__builtin_ia32_permdi512:
4834   case X86::BI__builtin_ia32_vpermilps:
4835   case X86::BI__builtin_ia32_vpermilps256:
4836   case X86::BI__builtin_ia32_vpermilpd512:
4837   case X86::BI__builtin_ia32_vpermilps512:
4838   case X86::BI__builtin_ia32_pshufd:
4839   case X86::BI__builtin_ia32_pshufd256:
4840   case X86::BI__builtin_ia32_pshufd512:
4841   case X86::BI__builtin_ia32_pshufhw:
4842   case X86::BI__builtin_ia32_pshufhw256:
4843   case X86::BI__builtin_ia32_pshufhw512:
4844   case X86::BI__builtin_ia32_pshuflw:
4845   case X86::BI__builtin_ia32_pshuflw256:
4846   case X86::BI__builtin_ia32_pshuflw512:
4847   case X86::BI__builtin_ia32_vcvtps2ph:
4848   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4849   case X86::BI__builtin_ia32_vcvtps2ph256:
4850   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4851   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4852   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4853   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4854   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4855   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4856   case X86::BI__builtin_ia32_rndscaleps_mask:
4857   case X86::BI__builtin_ia32_rndscalepd_mask:
4858   case X86::BI__builtin_ia32_rndscaleph_mask:
4859   case X86::BI__builtin_ia32_reducepd128_mask:
4860   case X86::BI__builtin_ia32_reducepd256_mask:
4861   case X86::BI__builtin_ia32_reducepd512_mask:
4862   case X86::BI__builtin_ia32_reduceps128_mask:
4863   case X86::BI__builtin_ia32_reduceps256_mask:
4864   case X86::BI__builtin_ia32_reduceps512_mask:
4865   case X86::BI__builtin_ia32_reduceph128_mask:
4866   case X86::BI__builtin_ia32_reduceph256_mask:
4867   case X86::BI__builtin_ia32_reduceph512_mask:
4868   case X86::BI__builtin_ia32_prold512:
4869   case X86::BI__builtin_ia32_prolq512:
4870   case X86::BI__builtin_ia32_prold128:
4871   case X86::BI__builtin_ia32_prold256:
4872   case X86::BI__builtin_ia32_prolq128:
4873   case X86::BI__builtin_ia32_prolq256:
4874   case X86::BI__builtin_ia32_prord512:
4875   case X86::BI__builtin_ia32_prorq512:
4876   case X86::BI__builtin_ia32_prord128:
4877   case X86::BI__builtin_ia32_prord256:
4878   case X86::BI__builtin_ia32_prorq128:
4879   case X86::BI__builtin_ia32_prorq256:
4880   case X86::BI__builtin_ia32_fpclasspd128_mask:
4881   case X86::BI__builtin_ia32_fpclasspd256_mask:
4882   case X86::BI__builtin_ia32_fpclassps128_mask:
4883   case X86::BI__builtin_ia32_fpclassps256_mask:
4884   case X86::BI__builtin_ia32_fpclassps512_mask:
4885   case X86::BI__builtin_ia32_fpclasspd512_mask:
4886   case X86::BI__builtin_ia32_fpclassph128_mask:
4887   case X86::BI__builtin_ia32_fpclassph256_mask:
4888   case X86::BI__builtin_ia32_fpclassph512_mask:
4889   case X86::BI__builtin_ia32_fpclasssd_mask:
4890   case X86::BI__builtin_ia32_fpclassss_mask:
4891   case X86::BI__builtin_ia32_fpclasssh_mask:
4892   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4893   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4894   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4895   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4896   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4897   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4898   case X86::BI__builtin_ia32_kshiftliqi:
4899   case X86::BI__builtin_ia32_kshiftlihi:
4900   case X86::BI__builtin_ia32_kshiftlisi:
4901   case X86::BI__builtin_ia32_kshiftlidi:
4902   case X86::BI__builtin_ia32_kshiftriqi:
4903   case X86::BI__builtin_ia32_kshiftrihi:
4904   case X86::BI__builtin_ia32_kshiftrisi:
4905   case X86::BI__builtin_ia32_kshiftridi:
4906     i = 1; l = 0; u = 255;
4907     break;
4908   case X86::BI__builtin_ia32_vperm2f128_pd256:
4909   case X86::BI__builtin_ia32_vperm2f128_ps256:
4910   case X86::BI__builtin_ia32_vperm2f128_si256:
4911   case X86::BI__builtin_ia32_permti256:
4912   case X86::BI__builtin_ia32_pblendw128:
4913   case X86::BI__builtin_ia32_pblendw256:
4914   case X86::BI__builtin_ia32_blendps256:
4915   case X86::BI__builtin_ia32_pblendd256:
4916   case X86::BI__builtin_ia32_palignr128:
4917   case X86::BI__builtin_ia32_palignr256:
4918   case X86::BI__builtin_ia32_palignr512:
4919   case X86::BI__builtin_ia32_alignq512:
4920   case X86::BI__builtin_ia32_alignd512:
4921   case X86::BI__builtin_ia32_alignd128:
4922   case X86::BI__builtin_ia32_alignd256:
4923   case X86::BI__builtin_ia32_alignq128:
4924   case X86::BI__builtin_ia32_alignq256:
4925   case X86::BI__builtin_ia32_vcomisd:
4926   case X86::BI__builtin_ia32_vcomiss:
4927   case X86::BI__builtin_ia32_shuf_f32x4:
4928   case X86::BI__builtin_ia32_shuf_f64x2:
4929   case X86::BI__builtin_ia32_shuf_i32x4:
4930   case X86::BI__builtin_ia32_shuf_i64x2:
4931   case X86::BI__builtin_ia32_shufpd512:
4932   case X86::BI__builtin_ia32_shufps:
4933   case X86::BI__builtin_ia32_shufps256:
4934   case X86::BI__builtin_ia32_shufps512:
4935   case X86::BI__builtin_ia32_dbpsadbw128:
4936   case X86::BI__builtin_ia32_dbpsadbw256:
4937   case X86::BI__builtin_ia32_dbpsadbw512:
4938   case X86::BI__builtin_ia32_vpshldd128:
4939   case X86::BI__builtin_ia32_vpshldd256:
4940   case X86::BI__builtin_ia32_vpshldd512:
4941   case X86::BI__builtin_ia32_vpshldq128:
4942   case X86::BI__builtin_ia32_vpshldq256:
4943   case X86::BI__builtin_ia32_vpshldq512:
4944   case X86::BI__builtin_ia32_vpshldw128:
4945   case X86::BI__builtin_ia32_vpshldw256:
4946   case X86::BI__builtin_ia32_vpshldw512:
4947   case X86::BI__builtin_ia32_vpshrdd128:
4948   case X86::BI__builtin_ia32_vpshrdd256:
4949   case X86::BI__builtin_ia32_vpshrdd512:
4950   case X86::BI__builtin_ia32_vpshrdq128:
4951   case X86::BI__builtin_ia32_vpshrdq256:
4952   case X86::BI__builtin_ia32_vpshrdq512:
4953   case X86::BI__builtin_ia32_vpshrdw128:
4954   case X86::BI__builtin_ia32_vpshrdw256:
4955   case X86::BI__builtin_ia32_vpshrdw512:
4956     i = 2; l = 0; u = 255;
4957     break;
4958   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4959   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4960   case X86::BI__builtin_ia32_fixupimmps512_mask:
4961   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4962   case X86::BI__builtin_ia32_fixupimmsd_mask:
4963   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4964   case X86::BI__builtin_ia32_fixupimmss_mask:
4965   case X86::BI__builtin_ia32_fixupimmss_maskz:
4966   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4967   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4968   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4969   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4970   case X86::BI__builtin_ia32_fixupimmps128_mask:
4971   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4972   case X86::BI__builtin_ia32_fixupimmps256_mask:
4973   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4974   case X86::BI__builtin_ia32_pternlogd512_mask:
4975   case X86::BI__builtin_ia32_pternlogd512_maskz:
4976   case X86::BI__builtin_ia32_pternlogq512_mask:
4977   case X86::BI__builtin_ia32_pternlogq512_maskz:
4978   case X86::BI__builtin_ia32_pternlogd128_mask:
4979   case X86::BI__builtin_ia32_pternlogd128_maskz:
4980   case X86::BI__builtin_ia32_pternlogd256_mask:
4981   case X86::BI__builtin_ia32_pternlogd256_maskz:
4982   case X86::BI__builtin_ia32_pternlogq128_mask:
4983   case X86::BI__builtin_ia32_pternlogq128_maskz:
4984   case X86::BI__builtin_ia32_pternlogq256_mask:
4985   case X86::BI__builtin_ia32_pternlogq256_maskz:
4986     i = 3; l = 0; u = 255;
4987     break;
4988   case X86::BI__builtin_ia32_gatherpfdpd:
4989   case X86::BI__builtin_ia32_gatherpfdps:
4990   case X86::BI__builtin_ia32_gatherpfqpd:
4991   case X86::BI__builtin_ia32_gatherpfqps:
4992   case X86::BI__builtin_ia32_scatterpfdpd:
4993   case X86::BI__builtin_ia32_scatterpfdps:
4994   case X86::BI__builtin_ia32_scatterpfqpd:
4995   case X86::BI__builtin_ia32_scatterpfqps:
4996     i = 4; l = 2; u = 3;
4997     break;
4998   case X86::BI__builtin_ia32_reducesd_mask:
4999   case X86::BI__builtin_ia32_reducess_mask:
5000   case X86::BI__builtin_ia32_rndscalesd_round_mask:
5001   case X86::BI__builtin_ia32_rndscaless_round_mask:
5002   case X86::BI__builtin_ia32_rndscalesh_round_mask:
5003   case X86::BI__builtin_ia32_reducesh_mask:
5004     i = 4; l = 0; u = 255;
5005     break;
5006   }
5007 
5008   // Note that we don't force a hard error on the range check here, allowing
5009   // template-generated or macro-generated dead code to potentially have out-of-
5010   // range values. These need to code generate, but don't need to necessarily
5011   // make any sense. We use a warning that defaults to an error.
5012   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
5013 }
5014 
5015 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
5016 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
5017 /// Returns true when the format fits the function and the FormatStringInfo has
5018 /// been populated.
5019 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
5020                                FormatStringInfo *FSI) {
5021   FSI->HasVAListArg = Format->getFirstArg() == 0;
5022   FSI->FormatIdx = Format->getFormatIdx() - 1;
5023   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
5024 
5025   // The way the format attribute works in GCC, the implicit this argument
5026   // of member functions is counted. However, it doesn't appear in our own
5027   // lists, so decrement format_idx in that case.
5028   if (IsCXXMember) {
5029     if(FSI->FormatIdx == 0)
5030       return false;
5031     --FSI->FormatIdx;
5032     if (FSI->FirstDataArg != 0)
5033       --FSI->FirstDataArg;
5034   }
5035   return true;
5036 }
5037 
5038 /// Checks if a the given expression evaluates to null.
5039 ///
5040 /// Returns true if the value evaluates to null.
5041 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
5042   // If the expression has non-null type, it doesn't evaluate to null.
5043   if (auto nullability
5044         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
5045     if (*nullability == NullabilityKind::NonNull)
5046       return false;
5047   }
5048 
5049   // As a special case, transparent unions initialized with zero are
5050   // considered null for the purposes of the nonnull attribute.
5051   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
5052     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
5053       if (const CompoundLiteralExpr *CLE =
5054           dyn_cast<CompoundLiteralExpr>(Expr))
5055         if (const InitListExpr *ILE =
5056             dyn_cast<InitListExpr>(CLE->getInitializer()))
5057           Expr = ILE->getInit(0);
5058   }
5059 
5060   bool Result;
5061   return (!Expr->isValueDependent() &&
5062           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
5063           !Result);
5064 }
5065 
5066 static void CheckNonNullArgument(Sema &S,
5067                                  const Expr *ArgExpr,
5068                                  SourceLocation CallSiteLoc) {
5069   if (CheckNonNullExpr(S, ArgExpr))
5070     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
5071                           S.PDiag(diag::warn_null_arg)
5072                               << ArgExpr->getSourceRange());
5073 }
5074 
5075 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
5076   FormatStringInfo FSI;
5077   if ((GetFormatStringType(Format) == FST_NSString) &&
5078       getFormatStringInfo(Format, false, &FSI)) {
5079     Idx = FSI.FormatIdx;
5080     return true;
5081   }
5082   return false;
5083 }
5084 
5085 /// Diagnose use of %s directive in an NSString which is being passed
5086 /// as formatting string to formatting method.
5087 static void
5088 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
5089                                         const NamedDecl *FDecl,
5090                                         Expr **Args,
5091                                         unsigned NumArgs) {
5092   unsigned Idx = 0;
5093   bool Format = false;
5094   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
5095   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
5096     Idx = 2;
5097     Format = true;
5098   }
5099   else
5100     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5101       if (S.GetFormatNSStringIdx(I, Idx)) {
5102         Format = true;
5103         break;
5104       }
5105     }
5106   if (!Format || NumArgs <= Idx)
5107     return;
5108   const Expr *FormatExpr = Args[Idx];
5109   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
5110     FormatExpr = CSCE->getSubExpr();
5111   const StringLiteral *FormatString;
5112   if (const ObjCStringLiteral *OSL =
5113       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
5114     FormatString = OSL->getString();
5115   else
5116     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
5117   if (!FormatString)
5118     return;
5119   if (S.FormatStringHasSArg(FormatString)) {
5120     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
5121       << "%s" << 1 << 1;
5122     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
5123       << FDecl->getDeclName();
5124   }
5125 }
5126 
5127 /// Determine whether the given type has a non-null nullability annotation.
5128 static bool isNonNullType(ASTContext &ctx, QualType type) {
5129   if (auto nullability = type->getNullability(ctx))
5130     return *nullability == NullabilityKind::NonNull;
5131 
5132   return false;
5133 }
5134 
5135 static void CheckNonNullArguments(Sema &S,
5136                                   const NamedDecl *FDecl,
5137                                   const FunctionProtoType *Proto,
5138                                   ArrayRef<const Expr *> Args,
5139                                   SourceLocation CallSiteLoc) {
5140   assert((FDecl || Proto) && "Need a function declaration or prototype");
5141 
5142   // Already checked by by constant evaluator.
5143   if (S.isConstantEvaluated())
5144     return;
5145   // Check the attributes attached to the method/function itself.
5146   llvm::SmallBitVector NonNullArgs;
5147   if (FDecl) {
5148     // Handle the nonnull attribute on the function/method declaration itself.
5149     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
5150       if (!NonNull->args_size()) {
5151         // Easy case: all pointer arguments are nonnull.
5152         for (const auto *Arg : Args)
5153           if (S.isValidPointerAttrType(Arg->getType()))
5154             CheckNonNullArgument(S, Arg, CallSiteLoc);
5155         return;
5156       }
5157 
5158       for (const ParamIdx &Idx : NonNull->args()) {
5159         unsigned IdxAST = Idx.getASTIndex();
5160         if (IdxAST >= Args.size())
5161           continue;
5162         if (NonNullArgs.empty())
5163           NonNullArgs.resize(Args.size());
5164         NonNullArgs.set(IdxAST);
5165       }
5166     }
5167   }
5168 
5169   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
5170     // Handle the nonnull attribute on the parameters of the
5171     // function/method.
5172     ArrayRef<ParmVarDecl*> parms;
5173     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
5174       parms = FD->parameters();
5175     else
5176       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
5177 
5178     unsigned ParamIndex = 0;
5179     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
5180          I != E; ++I, ++ParamIndex) {
5181       const ParmVarDecl *PVD = *I;
5182       if (PVD->hasAttr<NonNullAttr>() ||
5183           isNonNullType(S.Context, PVD->getType())) {
5184         if (NonNullArgs.empty())
5185           NonNullArgs.resize(Args.size());
5186 
5187         NonNullArgs.set(ParamIndex);
5188       }
5189     }
5190   } else {
5191     // If we have a non-function, non-method declaration but no
5192     // function prototype, try to dig out the function prototype.
5193     if (!Proto) {
5194       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
5195         QualType type = VD->getType().getNonReferenceType();
5196         if (auto pointerType = type->getAs<PointerType>())
5197           type = pointerType->getPointeeType();
5198         else if (auto blockType = type->getAs<BlockPointerType>())
5199           type = blockType->getPointeeType();
5200         // FIXME: data member pointers?
5201 
5202         // Dig out the function prototype, if there is one.
5203         Proto = type->getAs<FunctionProtoType>();
5204       }
5205     }
5206 
5207     // Fill in non-null argument information from the nullability
5208     // information on the parameter types (if we have them).
5209     if (Proto) {
5210       unsigned Index = 0;
5211       for (auto paramType : Proto->getParamTypes()) {
5212         if (isNonNullType(S.Context, paramType)) {
5213           if (NonNullArgs.empty())
5214             NonNullArgs.resize(Args.size());
5215 
5216           NonNullArgs.set(Index);
5217         }
5218 
5219         ++Index;
5220       }
5221     }
5222   }
5223 
5224   // Check for non-null arguments.
5225   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
5226        ArgIndex != ArgIndexEnd; ++ArgIndex) {
5227     if (NonNullArgs[ArgIndex])
5228       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
5229   }
5230 }
5231 
5232 /// Warn if a pointer or reference argument passed to a function points to an
5233 /// object that is less aligned than the parameter. This can happen when
5234 /// creating a typedef with a lower alignment than the original type and then
5235 /// calling functions defined in terms of the original type.
5236 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
5237                              StringRef ParamName, QualType ArgTy,
5238                              QualType ParamTy) {
5239 
5240   // If a function accepts a pointer or reference type
5241   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
5242     return;
5243 
5244   // If the parameter is a pointer type, get the pointee type for the
5245   // argument too. If the parameter is a reference type, don't try to get
5246   // the pointee type for the argument.
5247   if (ParamTy->isPointerType())
5248     ArgTy = ArgTy->getPointeeType();
5249 
5250   // Remove reference or pointer
5251   ParamTy = ParamTy->getPointeeType();
5252 
5253   // Find expected alignment, and the actual alignment of the passed object.
5254   // getTypeAlignInChars requires complete types
5255   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
5256       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
5257       ArgTy->isUndeducedType())
5258     return;
5259 
5260   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
5261   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
5262 
5263   // If the argument is less aligned than the parameter, there is a
5264   // potential alignment issue.
5265   if (ArgAlign < ParamAlign)
5266     Diag(Loc, diag::warn_param_mismatched_alignment)
5267         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
5268         << ParamName << (FDecl != nullptr) << FDecl;
5269 }
5270 
5271 /// Handles the checks for format strings, non-POD arguments to vararg
5272 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
5273 /// attributes.
5274 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
5275                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
5276                      bool IsMemberFunction, SourceLocation Loc,
5277                      SourceRange Range, VariadicCallType CallType) {
5278   // FIXME: We should check as much as we can in the template definition.
5279   if (CurContext->isDependentContext())
5280     return;
5281 
5282   // Printf and scanf checking.
5283   llvm::SmallBitVector CheckedVarArgs;
5284   if (FDecl) {
5285     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5286       // Only create vector if there are format attributes.
5287       CheckedVarArgs.resize(Args.size());
5288 
5289       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
5290                            CheckedVarArgs);
5291     }
5292   }
5293 
5294   // Refuse POD arguments that weren't caught by the format string
5295   // checks above.
5296   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
5297   if (CallType != VariadicDoesNotApply &&
5298       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
5299     unsigned NumParams = Proto ? Proto->getNumParams()
5300                        : FDecl && isa<FunctionDecl>(FDecl)
5301                            ? cast<FunctionDecl>(FDecl)->getNumParams()
5302                        : FDecl && isa<ObjCMethodDecl>(FDecl)
5303                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
5304                        : 0;
5305 
5306     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
5307       // Args[ArgIdx] can be null in malformed code.
5308       if (const Expr *Arg = Args[ArgIdx]) {
5309         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
5310           checkVariadicArgument(Arg, CallType);
5311       }
5312     }
5313   }
5314 
5315   if (FDecl || Proto) {
5316     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
5317 
5318     // Type safety checking.
5319     if (FDecl) {
5320       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
5321         CheckArgumentWithTypeTag(I, Args, Loc);
5322     }
5323   }
5324 
5325   // Check that passed arguments match the alignment of original arguments.
5326   // Try to get the missing prototype from the declaration.
5327   if (!Proto && FDecl) {
5328     const auto *FT = FDecl->getFunctionType();
5329     if (isa_and_nonnull<FunctionProtoType>(FT))
5330       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
5331   }
5332   if (Proto) {
5333     // For variadic functions, we may have more args than parameters.
5334     // For some K&R functions, we may have less args than parameters.
5335     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
5336     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
5337       // Args[ArgIdx] can be null in malformed code.
5338       if (const Expr *Arg = Args[ArgIdx]) {
5339         if (Arg->containsErrors())
5340           continue;
5341 
5342         QualType ParamTy = Proto->getParamType(ArgIdx);
5343         QualType ArgTy = Arg->getType();
5344         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
5345                           ArgTy, ParamTy);
5346       }
5347     }
5348   }
5349 
5350   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
5351     auto *AA = FDecl->getAttr<AllocAlignAttr>();
5352     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
5353     if (!Arg->isValueDependent()) {
5354       Expr::EvalResult Align;
5355       if (Arg->EvaluateAsInt(Align, Context)) {
5356         const llvm::APSInt &I = Align.Val.getInt();
5357         if (!I.isPowerOf2())
5358           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
5359               << Arg->getSourceRange();
5360 
5361         if (I > Sema::MaximumAlignment)
5362           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
5363               << Arg->getSourceRange() << Sema::MaximumAlignment;
5364       }
5365     }
5366   }
5367 
5368   if (FD)
5369     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
5370 }
5371 
5372 /// CheckConstructorCall - Check a constructor call for correctness and safety
5373 /// properties not enforced by the C type system.
5374 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5375                                 ArrayRef<const Expr *> Args,
5376                                 const FunctionProtoType *Proto,
5377                                 SourceLocation Loc) {
5378   VariadicCallType CallType =
5379       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5380 
5381   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5382   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5383                     Context.getPointerType(Ctor->getThisObjectType()));
5384 
5385   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5386             Loc, SourceRange(), CallType);
5387 }
5388 
5389 /// CheckFunctionCall - Check a direct function call for various correctness
5390 /// and safety properties not strictly enforced by the C type system.
5391 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5392                              const FunctionProtoType *Proto) {
5393   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5394                               isa<CXXMethodDecl>(FDecl);
5395   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5396                           IsMemberOperatorCall;
5397   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5398                                                   TheCall->getCallee());
5399   Expr** Args = TheCall->getArgs();
5400   unsigned NumArgs = TheCall->getNumArgs();
5401 
5402   Expr *ImplicitThis = nullptr;
5403   if (IsMemberOperatorCall) {
5404     // If this is a call to a member operator, hide the first argument
5405     // from checkCall.
5406     // FIXME: Our choice of AST representation here is less than ideal.
5407     ImplicitThis = Args[0];
5408     ++Args;
5409     --NumArgs;
5410   } else if (IsMemberFunction)
5411     ImplicitThis =
5412         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5413 
5414   if (ImplicitThis) {
5415     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5416     // used.
5417     QualType ThisType = ImplicitThis->getType();
5418     if (!ThisType->isPointerType()) {
5419       assert(!ThisType->isReferenceType());
5420       ThisType = Context.getPointerType(ThisType);
5421     }
5422 
5423     QualType ThisTypeFromDecl =
5424         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5425 
5426     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5427                       ThisTypeFromDecl);
5428   }
5429 
5430   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5431             IsMemberFunction, TheCall->getRParenLoc(),
5432             TheCall->getCallee()->getSourceRange(), CallType);
5433 
5434   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5435   // None of the checks below are needed for functions that don't have
5436   // simple names (e.g., C++ conversion functions).
5437   if (!FnInfo)
5438     return false;
5439 
5440   CheckTCBEnforcement(TheCall, FDecl);
5441 
5442   CheckAbsoluteValueFunction(TheCall, FDecl);
5443   CheckMaxUnsignedZero(TheCall, FDecl);
5444 
5445   if (getLangOpts().ObjC)
5446     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5447 
5448   unsigned CMId = FDecl->getMemoryFunctionKind();
5449 
5450   // Handle memory setting and copying functions.
5451   switch (CMId) {
5452   case 0:
5453     return false;
5454   case Builtin::BIstrlcpy: // fallthrough
5455   case Builtin::BIstrlcat:
5456     CheckStrlcpycatArguments(TheCall, FnInfo);
5457     break;
5458   case Builtin::BIstrncat:
5459     CheckStrncatArguments(TheCall, FnInfo);
5460     break;
5461   case Builtin::BIfree:
5462     CheckFreeArguments(TheCall);
5463     break;
5464   default:
5465     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5466   }
5467 
5468   return false;
5469 }
5470 
5471 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5472                                ArrayRef<const Expr *> Args) {
5473   VariadicCallType CallType =
5474       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5475 
5476   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5477             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5478             CallType);
5479 
5480   return false;
5481 }
5482 
5483 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5484                             const FunctionProtoType *Proto) {
5485   QualType Ty;
5486   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5487     Ty = V->getType().getNonReferenceType();
5488   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5489     Ty = F->getType().getNonReferenceType();
5490   else
5491     return false;
5492 
5493   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5494       !Ty->isFunctionProtoType())
5495     return false;
5496 
5497   VariadicCallType CallType;
5498   if (!Proto || !Proto->isVariadic()) {
5499     CallType = VariadicDoesNotApply;
5500   } else if (Ty->isBlockPointerType()) {
5501     CallType = VariadicBlock;
5502   } else { // Ty->isFunctionPointerType()
5503     CallType = VariadicFunction;
5504   }
5505 
5506   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5507             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5508             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5509             TheCall->getCallee()->getSourceRange(), CallType);
5510 
5511   return false;
5512 }
5513 
5514 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5515 /// such as function pointers returned from functions.
5516 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5517   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5518                                                   TheCall->getCallee());
5519   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5520             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5521             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5522             TheCall->getCallee()->getSourceRange(), CallType);
5523 
5524   return false;
5525 }
5526 
5527 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5528   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5529     return false;
5530 
5531   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5532   switch (Op) {
5533   case AtomicExpr::AO__c11_atomic_init:
5534   case AtomicExpr::AO__opencl_atomic_init:
5535     llvm_unreachable("There is no ordering argument for an init");
5536 
5537   case AtomicExpr::AO__c11_atomic_load:
5538   case AtomicExpr::AO__opencl_atomic_load:
5539   case AtomicExpr::AO__hip_atomic_load:
5540   case AtomicExpr::AO__atomic_load_n:
5541   case AtomicExpr::AO__atomic_load:
5542     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5543            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5544 
5545   case AtomicExpr::AO__c11_atomic_store:
5546   case AtomicExpr::AO__opencl_atomic_store:
5547   case AtomicExpr::AO__hip_atomic_store:
5548   case AtomicExpr::AO__atomic_store:
5549   case AtomicExpr::AO__atomic_store_n:
5550     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5551            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5552            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5553 
5554   default:
5555     return true;
5556   }
5557 }
5558 
5559 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5560                                          AtomicExpr::AtomicOp Op) {
5561   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5562   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5563   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5564   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5565                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5566                          Op);
5567 }
5568 
5569 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5570                                  SourceLocation RParenLoc, MultiExprArg Args,
5571                                  AtomicExpr::AtomicOp Op,
5572                                  AtomicArgumentOrder ArgOrder) {
5573   // All the non-OpenCL operations take one of the following forms.
5574   // The OpenCL operations take the __c11 forms with one extra argument for
5575   // synchronization scope.
5576   enum {
5577     // C    __c11_atomic_init(A *, C)
5578     Init,
5579 
5580     // C    __c11_atomic_load(A *, int)
5581     Load,
5582 
5583     // void __atomic_load(A *, CP, int)
5584     LoadCopy,
5585 
5586     // void __atomic_store(A *, CP, int)
5587     Copy,
5588 
5589     // C    __c11_atomic_add(A *, M, int)
5590     Arithmetic,
5591 
5592     // C    __atomic_exchange_n(A *, CP, int)
5593     Xchg,
5594 
5595     // void __atomic_exchange(A *, C *, CP, int)
5596     GNUXchg,
5597 
5598     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5599     C11CmpXchg,
5600 
5601     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5602     GNUCmpXchg
5603   } Form = Init;
5604 
5605   const unsigned NumForm = GNUCmpXchg + 1;
5606   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5607   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5608   // where:
5609   //   C is an appropriate type,
5610   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5611   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5612   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5613   //   the int parameters are for orderings.
5614 
5615   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5616       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5617       "need to update code for modified forms");
5618   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5619                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5620                         AtomicExpr::AO__atomic_load,
5621                 "need to update code for modified C11 atomics");
5622   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5623                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5624   bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load &&
5625                Op <= AtomicExpr::AO__hip_atomic_fetch_max;
5626   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5627                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5628                IsOpenCL;
5629   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5630              Op == AtomicExpr::AO__atomic_store_n ||
5631              Op == AtomicExpr::AO__atomic_exchange_n ||
5632              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5633   bool IsAddSub = false;
5634 
5635   switch (Op) {
5636   case AtomicExpr::AO__c11_atomic_init:
5637   case AtomicExpr::AO__opencl_atomic_init:
5638     Form = Init;
5639     break;
5640 
5641   case AtomicExpr::AO__c11_atomic_load:
5642   case AtomicExpr::AO__opencl_atomic_load:
5643   case AtomicExpr::AO__hip_atomic_load:
5644   case AtomicExpr::AO__atomic_load_n:
5645     Form = Load;
5646     break;
5647 
5648   case AtomicExpr::AO__atomic_load:
5649     Form = LoadCopy;
5650     break;
5651 
5652   case AtomicExpr::AO__c11_atomic_store:
5653   case AtomicExpr::AO__opencl_atomic_store:
5654   case AtomicExpr::AO__hip_atomic_store:
5655   case AtomicExpr::AO__atomic_store:
5656   case AtomicExpr::AO__atomic_store_n:
5657     Form = Copy;
5658     break;
5659   case AtomicExpr::AO__hip_atomic_fetch_add:
5660   case AtomicExpr::AO__hip_atomic_fetch_min:
5661   case AtomicExpr::AO__hip_atomic_fetch_max:
5662   case AtomicExpr::AO__c11_atomic_fetch_add:
5663   case AtomicExpr::AO__c11_atomic_fetch_sub:
5664   case AtomicExpr::AO__opencl_atomic_fetch_add:
5665   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5666   case AtomicExpr::AO__atomic_fetch_add:
5667   case AtomicExpr::AO__atomic_fetch_sub:
5668   case AtomicExpr::AO__atomic_add_fetch:
5669   case AtomicExpr::AO__atomic_sub_fetch:
5670     IsAddSub = true;
5671     Form = Arithmetic;
5672     break;
5673   case AtomicExpr::AO__c11_atomic_fetch_and:
5674   case AtomicExpr::AO__c11_atomic_fetch_or:
5675   case AtomicExpr::AO__c11_atomic_fetch_xor:
5676   case AtomicExpr::AO__hip_atomic_fetch_and:
5677   case AtomicExpr::AO__hip_atomic_fetch_or:
5678   case AtomicExpr::AO__hip_atomic_fetch_xor:
5679   case AtomicExpr::AO__c11_atomic_fetch_nand:
5680   case AtomicExpr::AO__opencl_atomic_fetch_and:
5681   case AtomicExpr::AO__opencl_atomic_fetch_or:
5682   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5683   case AtomicExpr::AO__atomic_fetch_and:
5684   case AtomicExpr::AO__atomic_fetch_or:
5685   case AtomicExpr::AO__atomic_fetch_xor:
5686   case AtomicExpr::AO__atomic_fetch_nand:
5687   case AtomicExpr::AO__atomic_and_fetch:
5688   case AtomicExpr::AO__atomic_or_fetch:
5689   case AtomicExpr::AO__atomic_xor_fetch:
5690   case AtomicExpr::AO__atomic_nand_fetch:
5691     Form = Arithmetic;
5692     break;
5693   case AtomicExpr::AO__c11_atomic_fetch_min:
5694   case AtomicExpr::AO__c11_atomic_fetch_max:
5695   case AtomicExpr::AO__opencl_atomic_fetch_min:
5696   case AtomicExpr::AO__opencl_atomic_fetch_max:
5697   case AtomicExpr::AO__atomic_min_fetch:
5698   case AtomicExpr::AO__atomic_max_fetch:
5699   case AtomicExpr::AO__atomic_fetch_min:
5700   case AtomicExpr::AO__atomic_fetch_max:
5701     Form = Arithmetic;
5702     break;
5703 
5704   case AtomicExpr::AO__c11_atomic_exchange:
5705   case AtomicExpr::AO__hip_atomic_exchange:
5706   case AtomicExpr::AO__opencl_atomic_exchange:
5707   case AtomicExpr::AO__atomic_exchange_n:
5708     Form = Xchg;
5709     break;
5710 
5711   case AtomicExpr::AO__atomic_exchange:
5712     Form = GNUXchg;
5713     break;
5714 
5715   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5716   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5717   case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5718   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5719   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5720   case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5721     Form = C11CmpXchg;
5722     break;
5723 
5724   case AtomicExpr::AO__atomic_compare_exchange:
5725   case AtomicExpr::AO__atomic_compare_exchange_n:
5726     Form = GNUCmpXchg;
5727     break;
5728   }
5729 
5730   unsigned AdjustedNumArgs = NumArgs[Form];
5731   if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init)
5732     ++AdjustedNumArgs;
5733   // Check we have the right number of arguments.
5734   if (Args.size() < AdjustedNumArgs) {
5735     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5736         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5737         << ExprRange;
5738     return ExprError();
5739   } else if (Args.size() > AdjustedNumArgs) {
5740     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5741          diag::err_typecheck_call_too_many_args)
5742         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5743         << ExprRange;
5744     return ExprError();
5745   }
5746 
5747   // Inspect the first argument of the atomic operation.
5748   Expr *Ptr = Args[0];
5749   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5750   if (ConvertedPtr.isInvalid())
5751     return ExprError();
5752 
5753   Ptr = ConvertedPtr.get();
5754   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5755   if (!pointerType) {
5756     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5757         << Ptr->getType() << Ptr->getSourceRange();
5758     return ExprError();
5759   }
5760 
5761   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5762   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5763   QualType ValType = AtomTy; // 'C'
5764   if (IsC11) {
5765     if (!AtomTy->isAtomicType()) {
5766       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5767           << Ptr->getType() << Ptr->getSourceRange();
5768       return ExprError();
5769     }
5770     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5771         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5772       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5773           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5774           << Ptr->getSourceRange();
5775       return ExprError();
5776     }
5777     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5778   } else if (Form != Load && Form != LoadCopy) {
5779     if (ValType.isConstQualified()) {
5780       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5781           << Ptr->getType() << Ptr->getSourceRange();
5782       return ExprError();
5783     }
5784   }
5785 
5786   // For an arithmetic operation, the implied arithmetic must be well-formed.
5787   if (Form == Arithmetic) {
5788     // GCC does not enforce these rules for GNU atomics, but we do to help catch
5789     // trivial type errors.
5790     auto IsAllowedValueType = [&](QualType ValType) {
5791       if (ValType->isIntegerType())
5792         return true;
5793       if (ValType->isPointerType())
5794         return true;
5795       if (!ValType->isFloatingType())
5796         return false;
5797       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5798       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5799           &Context.getTargetInfo().getLongDoubleFormat() ==
5800               &llvm::APFloat::x87DoubleExtended())
5801         return false;
5802       return true;
5803     };
5804     if (IsAddSub && !IsAllowedValueType(ValType)) {
5805       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5806           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5807       return ExprError();
5808     }
5809     if (!IsAddSub && !ValType->isIntegerType()) {
5810       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5811           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5812       return ExprError();
5813     }
5814     if (IsC11 && ValType->isPointerType() &&
5815         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5816                             diag::err_incomplete_type)) {
5817       return ExprError();
5818     }
5819   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5820     // For __atomic_*_n operations, the value type must be a scalar integral or
5821     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5822     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5823         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5824     return ExprError();
5825   }
5826 
5827   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5828       !AtomTy->isScalarType()) {
5829     // For GNU atomics, require a trivially-copyable type. This is not part of
5830     // the GNU atomics specification but we enforce it for consistency with
5831     // other atomics which generally all require a trivially-copyable type. This
5832     // is because atomics just copy bits.
5833     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5834         << Ptr->getType() << Ptr->getSourceRange();
5835     return ExprError();
5836   }
5837 
5838   switch (ValType.getObjCLifetime()) {
5839   case Qualifiers::OCL_None:
5840   case Qualifiers::OCL_ExplicitNone:
5841     // okay
5842     break;
5843 
5844   case Qualifiers::OCL_Weak:
5845   case Qualifiers::OCL_Strong:
5846   case Qualifiers::OCL_Autoreleasing:
5847     // FIXME: Can this happen? By this point, ValType should be known
5848     // to be trivially copyable.
5849     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5850         << ValType << Ptr->getSourceRange();
5851     return ExprError();
5852   }
5853 
5854   // All atomic operations have an overload which takes a pointer to a volatile
5855   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5856   // into the result or the other operands. Similarly atomic_load takes a
5857   // pointer to a const 'A'.
5858   ValType.removeLocalVolatile();
5859   ValType.removeLocalConst();
5860   QualType ResultType = ValType;
5861   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5862       Form == Init)
5863     ResultType = Context.VoidTy;
5864   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5865     ResultType = Context.BoolTy;
5866 
5867   // The type of a parameter passed 'by value'. In the GNU atomics, such
5868   // arguments are actually passed as pointers.
5869   QualType ByValType = ValType; // 'CP'
5870   bool IsPassedByAddress = false;
5871   if (!IsC11 && !IsHIP && !IsN) {
5872     ByValType = Ptr->getType();
5873     IsPassedByAddress = true;
5874   }
5875 
5876   SmallVector<Expr *, 5> APIOrderedArgs;
5877   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5878     APIOrderedArgs.push_back(Args[0]);
5879     switch (Form) {
5880     case Init:
5881     case Load:
5882       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5883       break;
5884     case LoadCopy:
5885     case Copy:
5886     case Arithmetic:
5887     case Xchg:
5888       APIOrderedArgs.push_back(Args[2]); // Val1
5889       APIOrderedArgs.push_back(Args[1]); // Order
5890       break;
5891     case GNUXchg:
5892       APIOrderedArgs.push_back(Args[2]); // Val1
5893       APIOrderedArgs.push_back(Args[3]); // Val2
5894       APIOrderedArgs.push_back(Args[1]); // Order
5895       break;
5896     case C11CmpXchg:
5897       APIOrderedArgs.push_back(Args[2]); // Val1
5898       APIOrderedArgs.push_back(Args[4]); // Val2
5899       APIOrderedArgs.push_back(Args[1]); // Order
5900       APIOrderedArgs.push_back(Args[3]); // OrderFail
5901       break;
5902     case GNUCmpXchg:
5903       APIOrderedArgs.push_back(Args[2]); // Val1
5904       APIOrderedArgs.push_back(Args[4]); // Val2
5905       APIOrderedArgs.push_back(Args[5]); // Weak
5906       APIOrderedArgs.push_back(Args[1]); // Order
5907       APIOrderedArgs.push_back(Args[3]); // OrderFail
5908       break;
5909     }
5910   } else
5911     APIOrderedArgs.append(Args.begin(), Args.end());
5912 
5913   // The first argument's non-CV pointer type is used to deduce the type of
5914   // subsequent arguments, except for:
5915   //  - weak flag (always converted to bool)
5916   //  - memory order (always converted to int)
5917   //  - scope  (always converted to int)
5918   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5919     QualType Ty;
5920     if (i < NumVals[Form] + 1) {
5921       switch (i) {
5922       case 0:
5923         // The first argument is always a pointer. It has a fixed type.
5924         // It is always dereferenced, a nullptr is undefined.
5925         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5926         // Nothing else to do: we already know all we want about this pointer.
5927         continue;
5928       case 1:
5929         // The second argument is the non-atomic operand. For arithmetic, this
5930         // is always passed by value, and for a compare_exchange it is always
5931         // passed by address. For the rest, GNU uses by-address and C11 uses
5932         // by-value.
5933         assert(Form != Load);
5934         if (Form == Arithmetic && ValType->isPointerType())
5935           Ty = Context.getPointerDiffType();
5936         else if (Form == Init || Form == Arithmetic)
5937           Ty = ValType;
5938         else if (Form == Copy || Form == Xchg) {
5939           if (IsPassedByAddress) {
5940             // The value pointer is always dereferenced, a nullptr is undefined.
5941             CheckNonNullArgument(*this, APIOrderedArgs[i],
5942                                  ExprRange.getBegin());
5943           }
5944           Ty = ByValType;
5945         } else {
5946           Expr *ValArg = APIOrderedArgs[i];
5947           // The value pointer is always dereferenced, a nullptr is undefined.
5948           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5949           LangAS AS = LangAS::Default;
5950           // Keep address space of non-atomic pointer type.
5951           if (const PointerType *PtrTy =
5952                   ValArg->getType()->getAs<PointerType>()) {
5953             AS = PtrTy->getPointeeType().getAddressSpace();
5954           }
5955           Ty = Context.getPointerType(
5956               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5957         }
5958         break;
5959       case 2:
5960         // The third argument to compare_exchange / GNU exchange is the desired
5961         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5962         if (IsPassedByAddress)
5963           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5964         Ty = ByValType;
5965         break;
5966       case 3:
5967         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5968         Ty = Context.BoolTy;
5969         break;
5970       }
5971     } else {
5972       // The order(s) and scope are always converted to int.
5973       Ty = Context.IntTy;
5974     }
5975 
5976     InitializedEntity Entity =
5977         InitializedEntity::InitializeParameter(Context, Ty, false);
5978     ExprResult Arg = APIOrderedArgs[i];
5979     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5980     if (Arg.isInvalid())
5981       return true;
5982     APIOrderedArgs[i] = Arg.get();
5983   }
5984 
5985   // Permute the arguments into a 'consistent' order.
5986   SmallVector<Expr*, 5> SubExprs;
5987   SubExprs.push_back(Ptr);
5988   switch (Form) {
5989   case Init:
5990     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5991     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5992     break;
5993   case Load:
5994     SubExprs.push_back(APIOrderedArgs[1]); // Order
5995     break;
5996   case LoadCopy:
5997   case Copy:
5998   case Arithmetic:
5999   case Xchg:
6000     SubExprs.push_back(APIOrderedArgs[2]); // Order
6001     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6002     break;
6003   case GNUXchg:
6004     // Note, AtomicExpr::getVal2() has a special case for this atomic.
6005     SubExprs.push_back(APIOrderedArgs[3]); // Order
6006     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6007     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6008     break;
6009   case C11CmpXchg:
6010     SubExprs.push_back(APIOrderedArgs[3]); // Order
6011     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6012     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
6013     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6014     break;
6015   case GNUCmpXchg:
6016     SubExprs.push_back(APIOrderedArgs[4]); // Order
6017     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6018     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
6019     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6020     SubExprs.push_back(APIOrderedArgs[3]); // Weak
6021     break;
6022   }
6023 
6024   if (SubExprs.size() >= 2 && Form != Init) {
6025     if (Optional<llvm::APSInt> Result =
6026             SubExprs[1]->getIntegerConstantExpr(Context))
6027       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
6028         Diag(SubExprs[1]->getBeginLoc(),
6029              diag::warn_atomic_op_has_invalid_memory_order)
6030             << SubExprs[1]->getSourceRange();
6031   }
6032 
6033   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
6034     auto *Scope = Args[Args.size() - 1];
6035     if (Optional<llvm::APSInt> Result =
6036             Scope->getIntegerConstantExpr(Context)) {
6037       if (!ScopeModel->isValid(Result->getZExtValue()))
6038         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
6039             << Scope->getSourceRange();
6040     }
6041     SubExprs.push_back(Scope);
6042   }
6043 
6044   AtomicExpr *AE = new (Context)
6045       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
6046 
6047   if ((Op == AtomicExpr::AO__c11_atomic_load ||
6048        Op == AtomicExpr::AO__c11_atomic_store ||
6049        Op == AtomicExpr::AO__opencl_atomic_load ||
6050        Op == AtomicExpr::AO__hip_atomic_load ||
6051        Op == AtomicExpr::AO__opencl_atomic_store ||
6052        Op == AtomicExpr::AO__hip_atomic_store) &&
6053       Context.AtomicUsesUnsupportedLibcall(AE))
6054     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
6055         << ((Op == AtomicExpr::AO__c11_atomic_load ||
6056              Op == AtomicExpr::AO__opencl_atomic_load ||
6057              Op == AtomicExpr::AO__hip_atomic_load)
6058                 ? 0
6059                 : 1);
6060 
6061   if (ValType->isBitIntType()) {
6062     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
6063     return ExprError();
6064   }
6065 
6066   return AE;
6067 }
6068 
6069 /// checkBuiltinArgument - Given a call to a builtin function, perform
6070 /// normal type-checking on the given argument, updating the call in
6071 /// place.  This is useful when a builtin function requires custom
6072 /// type-checking for some of its arguments but not necessarily all of
6073 /// them.
6074 ///
6075 /// Returns true on error.
6076 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
6077   FunctionDecl *Fn = E->getDirectCallee();
6078   assert(Fn && "builtin call without direct callee!");
6079 
6080   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
6081   InitializedEntity Entity =
6082     InitializedEntity::InitializeParameter(S.Context, Param);
6083 
6084   ExprResult Arg = E->getArg(0);
6085   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
6086   if (Arg.isInvalid())
6087     return true;
6088 
6089   E->setArg(ArgIndex, Arg.get());
6090   return false;
6091 }
6092 
6093 /// We have a call to a function like __sync_fetch_and_add, which is an
6094 /// overloaded function based on the pointer type of its first argument.
6095 /// The main BuildCallExpr routines have already promoted the types of
6096 /// arguments because all of these calls are prototyped as void(...).
6097 ///
6098 /// This function goes through and does final semantic checking for these
6099 /// builtins, as well as generating any warnings.
6100 ExprResult
6101 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
6102   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
6103   Expr *Callee = TheCall->getCallee();
6104   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
6105   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6106 
6107   // Ensure that we have at least one argument to do type inference from.
6108   if (TheCall->getNumArgs() < 1) {
6109     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6110         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
6111     return ExprError();
6112   }
6113 
6114   // Inspect the first argument of the atomic builtin.  This should always be
6115   // a pointer type, whose element is an integral scalar or pointer type.
6116   // Because it is a pointer type, we don't have to worry about any implicit
6117   // casts here.
6118   // FIXME: We don't allow floating point scalars as input.
6119   Expr *FirstArg = TheCall->getArg(0);
6120   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
6121   if (FirstArgResult.isInvalid())
6122     return ExprError();
6123   FirstArg = FirstArgResult.get();
6124   TheCall->setArg(0, FirstArg);
6125 
6126   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
6127   if (!pointerType) {
6128     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
6129         << FirstArg->getType() << FirstArg->getSourceRange();
6130     return ExprError();
6131   }
6132 
6133   QualType ValType = pointerType->getPointeeType();
6134   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6135       !ValType->isBlockPointerType()) {
6136     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
6137         << FirstArg->getType() << FirstArg->getSourceRange();
6138     return ExprError();
6139   }
6140 
6141   if (ValType.isConstQualified()) {
6142     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
6143         << FirstArg->getType() << FirstArg->getSourceRange();
6144     return ExprError();
6145   }
6146 
6147   switch (ValType.getObjCLifetime()) {
6148   case Qualifiers::OCL_None:
6149   case Qualifiers::OCL_ExplicitNone:
6150     // okay
6151     break;
6152 
6153   case Qualifiers::OCL_Weak:
6154   case Qualifiers::OCL_Strong:
6155   case Qualifiers::OCL_Autoreleasing:
6156     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
6157         << ValType << FirstArg->getSourceRange();
6158     return ExprError();
6159   }
6160 
6161   // Strip any qualifiers off ValType.
6162   ValType = ValType.getUnqualifiedType();
6163 
6164   // The majority of builtins return a value, but a few have special return
6165   // types, so allow them to override appropriately below.
6166   QualType ResultType = ValType;
6167 
6168   // We need to figure out which concrete builtin this maps onto.  For example,
6169   // __sync_fetch_and_add with a 2 byte object turns into
6170   // __sync_fetch_and_add_2.
6171 #define BUILTIN_ROW(x) \
6172   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
6173     Builtin::BI##x##_8, Builtin::BI##x##_16 }
6174 
6175   static const unsigned BuiltinIndices[][5] = {
6176     BUILTIN_ROW(__sync_fetch_and_add),
6177     BUILTIN_ROW(__sync_fetch_and_sub),
6178     BUILTIN_ROW(__sync_fetch_and_or),
6179     BUILTIN_ROW(__sync_fetch_and_and),
6180     BUILTIN_ROW(__sync_fetch_and_xor),
6181     BUILTIN_ROW(__sync_fetch_and_nand),
6182 
6183     BUILTIN_ROW(__sync_add_and_fetch),
6184     BUILTIN_ROW(__sync_sub_and_fetch),
6185     BUILTIN_ROW(__sync_and_and_fetch),
6186     BUILTIN_ROW(__sync_or_and_fetch),
6187     BUILTIN_ROW(__sync_xor_and_fetch),
6188     BUILTIN_ROW(__sync_nand_and_fetch),
6189 
6190     BUILTIN_ROW(__sync_val_compare_and_swap),
6191     BUILTIN_ROW(__sync_bool_compare_and_swap),
6192     BUILTIN_ROW(__sync_lock_test_and_set),
6193     BUILTIN_ROW(__sync_lock_release),
6194     BUILTIN_ROW(__sync_swap)
6195   };
6196 #undef BUILTIN_ROW
6197 
6198   // Determine the index of the size.
6199   unsigned SizeIndex;
6200   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
6201   case 1: SizeIndex = 0; break;
6202   case 2: SizeIndex = 1; break;
6203   case 4: SizeIndex = 2; break;
6204   case 8: SizeIndex = 3; break;
6205   case 16: SizeIndex = 4; break;
6206   default:
6207     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
6208         << FirstArg->getType() << FirstArg->getSourceRange();
6209     return ExprError();
6210   }
6211 
6212   // Each of these builtins has one pointer argument, followed by some number of
6213   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
6214   // that we ignore.  Find out which row of BuiltinIndices to read from as well
6215   // as the number of fixed args.
6216   unsigned BuiltinID = FDecl->getBuiltinID();
6217   unsigned BuiltinIndex, NumFixed = 1;
6218   bool WarnAboutSemanticsChange = false;
6219   switch (BuiltinID) {
6220   default: llvm_unreachable("Unknown overloaded atomic builtin!");
6221   case Builtin::BI__sync_fetch_and_add:
6222   case Builtin::BI__sync_fetch_and_add_1:
6223   case Builtin::BI__sync_fetch_and_add_2:
6224   case Builtin::BI__sync_fetch_and_add_4:
6225   case Builtin::BI__sync_fetch_and_add_8:
6226   case Builtin::BI__sync_fetch_and_add_16:
6227     BuiltinIndex = 0;
6228     break;
6229 
6230   case Builtin::BI__sync_fetch_and_sub:
6231   case Builtin::BI__sync_fetch_and_sub_1:
6232   case Builtin::BI__sync_fetch_and_sub_2:
6233   case Builtin::BI__sync_fetch_and_sub_4:
6234   case Builtin::BI__sync_fetch_and_sub_8:
6235   case Builtin::BI__sync_fetch_and_sub_16:
6236     BuiltinIndex = 1;
6237     break;
6238 
6239   case Builtin::BI__sync_fetch_and_or:
6240   case Builtin::BI__sync_fetch_and_or_1:
6241   case Builtin::BI__sync_fetch_and_or_2:
6242   case Builtin::BI__sync_fetch_and_or_4:
6243   case Builtin::BI__sync_fetch_and_or_8:
6244   case Builtin::BI__sync_fetch_and_or_16:
6245     BuiltinIndex = 2;
6246     break;
6247 
6248   case Builtin::BI__sync_fetch_and_and:
6249   case Builtin::BI__sync_fetch_and_and_1:
6250   case Builtin::BI__sync_fetch_and_and_2:
6251   case Builtin::BI__sync_fetch_and_and_4:
6252   case Builtin::BI__sync_fetch_and_and_8:
6253   case Builtin::BI__sync_fetch_and_and_16:
6254     BuiltinIndex = 3;
6255     break;
6256 
6257   case Builtin::BI__sync_fetch_and_xor:
6258   case Builtin::BI__sync_fetch_and_xor_1:
6259   case Builtin::BI__sync_fetch_and_xor_2:
6260   case Builtin::BI__sync_fetch_and_xor_4:
6261   case Builtin::BI__sync_fetch_and_xor_8:
6262   case Builtin::BI__sync_fetch_and_xor_16:
6263     BuiltinIndex = 4;
6264     break;
6265 
6266   case Builtin::BI__sync_fetch_and_nand:
6267   case Builtin::BI__sync_fetch_and_nand_1:
6268   case Builtin::BI__sync_fetch_and_nand_2:
6269   case Builtin::BI__sync_fetch_and_nand_4:
6270   case Builtin::BI__sync_fetch_and_nand_8:
6271   case Builtin::BI__sync_fetch_and_nand_16:
6272     BuiltinIndex = 5;
6273     WarnAboutSemanticsChange = true;
6274     break;
6275 
6276   case Builtin::BI__sync_add_and_fetch:
6277   case Builtin::BI__sync_add_and_fetch_1:
6278   case Builtin::BI__sync_add_and_fetch_2:
6279   case Builtin::BI__sync_add_and_fetch_4:
6280   case Builtin::BI__sync_add_and_fetch_8:
6281   case Builtin::BI__sync_add_and_fetch_16:
6282     BuiltinIndex = 6;
6283     break;
6284 
6285   case Builtin::BI__sync_sub_and_fetch:
6286   case Builtin::BI__sync_sub_and_fetch_1:
6287   case Builtin::BI__sync_sub_and_fetch_2:
6288   case Builtin::BI__sync_sub_and_fetch_4:
6289   case Builtin::BI__sync_sub_and_fetch_8:
6290   case Builtin::BI__sync_sub_and_fetch_16:
6291     BuiltinIndex = 7;
6292     break;
6293 
6294   case Builtin::BI__sync_and_and_fetch:
6295   case Builtin::BI__sync_and_and_fetch_1:
6296   case Builtin::BI__sync_and_and_fetch_2:
6297   case Builtin::BI__sync_and_and_fetch_4:
6298   case Builtin::BI__sync_and_and_fetch_8:
6299   case Builtin::BI__sync_and_and_fetch_16:
6300     BuiltinIndex = 8;
6301     break;
6302 
6303   case Builtin::BI__sync_or_and_fetch:
6304   case Builtin::BI__sync_or_and_fetch_1:
6305   case Builtin::BI__sync_or_and_fetch_2:
6306   case Builtin::BI__sync_or_and_fetch_4:
6307   case Builtin::BI__sync_or_and_fetch_8:
6308   case Builtin::BI__sync_or_and_fetch_16:
6309     BuiltinIndex = 9;
6310     break;
6311 
6312   case Builtin::BI__sync_xor_and_fetch:
6313   case Builtin::BI__sync_xor_and_fetch_1:
6314   case Builtin::BI__sync_xor_and_fetch_2:
6315   case Builtin::BI__sync_xor_and_fetch_4:
6316   case Builtin::BI__sync_xor_and_fetch_8:
6317   case Builtin::BI__sync_xor_and_fetch_16:
6318     BuiltinIndex = 10;
6319     break;
6320 
6321   case Builtin::BI__sync_nand_and_fetch:
6322   case Builtin::BI__sync_nand_and_fetch_1:
6323   case Builtin::BI__sync_nand_and_fetch_2:
6324   case Builtin::BI__sync_nand_and_fetch_4:
6325   case Builtin::BI__sync_nand_and_fetch_8:
6326   case Builtin::BI__sync_nand_and_fetch_16:
6327     BuiltinIndex = 11;
6328     WarnAboutSemanticsChange = true;
6329     break;
6330 
6331   case Builtin::BI__sync_val_compare_and_swap:
6332   case Builtin::BI__sync_val_compare_and_swap_1:
6333   case Builtin::BI__sync_val_compare_and_swap_2:
6334   case Builtin::BI__sync_val_compare_and_swap_4:
6335   case Builtin::BI__sync_val_compare_and_swap_8:
6336   case Builtin::BI__sync_val_compare_and_swap_16:
6337     BuiltinIndex = 12;
6338     NumFixed = 2;
6339     break;
6340 
6341   case Builtin::BI__sync_bool_compare_and_swap:
6342   case Builtin::BI__sync_bool_compare_and_swap_1:
6343   case Builtin::BI__sync_bool_compare_and_swap_2:
6344   case Builtin::BI__sync_bool_compare_and_swap_4:
6345   case Builtin::BI__sync_bool_compare_and_swap_8:
6346   case Builtin::BI__sync_bool_compare_and_swap_16:
6347     BuiltinIndex = 13;
6348     NumFixed = 2;
6349     ResultType = Context.BoolTy;
6350     break;
6351 
6352   case Builtin::BI__sync_lock_test_and_set:
6353   case Builtin::BI__sync_lock_test_and_set_1:
6354   case Builtin::BI__sync_lock_test_and_set_2:
6355   case Builtin::BI__sync_lock_test_and_set_4:
6356   case Builtin::BI__sync_lock_test_and_set_8:
6357   case Builtin::BI__sync_lock_test_and_set_16:
6358     BuiltinIndex = 14;
6359     break;
6360 
6361   case Builtin::BI__sync_lock_release:
6362   case Builtin::BI__sync_lock_release_1:
6363   case Builtin::BI__sync_lock_release_2:
6364   case Builtin::BI__sync_lock_release_4:
6365   case Builtin::BI__sync_lock_release_8:
6366   case Builtin::BI__sync_lock_release_16:
6367     BuiltinIndex = 15;
6368     NumFixed = 0;
6369     ResultType = Context.VoidTy;
6370     break;
6371 
6372   case Builtin::BI__sync_swap:
6373   case Builtin::BI__sync_swap_1:
6374   case Builtin::BI__sync_swap_2:
6375   case Builtin::BI__sync_swap_4:
6376   case Builtin::BI__sync_swap_8:
6377   case Builtin::BI__sync_swap_16:
6378     BuiltinIndex = 16;
6379     break;
6380   }
6381 
6382   // Now that we know how many fixed arguments we expect, first check that we
6383   // have at least that many.
6384   if (TheCall->getNumArgs() < 1+NumFixed) {
6385     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6386         << 0 << 1 + NumFixed << TheCall->getNumArgs()
6387         << Callee->getSourceRange();
6388     return ExprError();
6389   }
6390 
6391   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6392       << Callee->getSourceRange();
6393 
6394   if (WarnAboutSemanticsChange) {
6395     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6396         << Callee->getSourceRange();
6397   }
6398 
6399   // Get the decl for the concrete builtin from this, we can tell what the
6400   // concrete integer type we should convert to is.
6401   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6402   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6403   FunctionDecl *NewBuiltinDecl;
6404   if (NewBuiltinID == BuiltinID)
6405     NewBuiltinDecl = FDecl;
6406   else {
6407     // Perform builtin lookup to avoid redeclaring it.
6408     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6409     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6410     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6411     assert(Res.getFoundDecl());
6412     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6413     if (!NewBuiltinDecl)
6414       return ExprError();
6415   }
6416 
6417   // The first argument --- the pointer --- has a fixed type; we
6418   // deduce the types of the rest of the arguments accordingly.  Walk
6419   // the remaining arguments, converting them to the deduced value type.
6420   for (unsigned i = 0; i != NumFixed; ++i) {
6421     ExprResult Arg = TheCall->getArg(i+1);
6422 
6423     // GCC does an implicit conversion to the pointer or integer ValType.  This
6424     // can fail in some cases (1i -> int**), check for this error case now.
6425     // Initialize the argument.
6426     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6427                                                    ValType, /*consume*/ false);
6428     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6429     if (Arg.isInvalid())
6430       return ExprError();
6431 
6432     // Okay, we have something that *can* be converted to the right type.  Check
6433     // to see if there is a potentially weird extension going on here.  This can
6434     // happen when you do an atomic operation on something like an char* and
6435     // pass in 42.  The 42 gets converted to char.  This is even more strange
6436     // for things like 45.123 -> char, etc.
6437     // FIXME: Do this check.
6438     TheCall->setArg(i+1, Arg.get());
6439   }
6440 
6441   // Create a new DeclRefExpr to refer to the new decl.
6442   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6443       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6444       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6445       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6446 
6447   // Set the callee in the CallExpr.
6448   // FIXME: This loses syntactic information.
6449   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6450   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6451                                               CK_BuiltinFnToFnPtr);
6452   TheCall->setCallee(PromotedCall.get());
6453 
6454   // Change the result type of the call to match the original value type. This
6455   // is arbitrary, but the codegen for these builtins ins design to handle it
6456   // gracefully.
6457   TheCall->setType(ResultType);
6458 
6459   // Prohibit problematic uses of bit-precise integer types with atomic
6460   // builtins. The arguments would have already been converted to the first
6461   // argument's type, so only need to check the first argument.
6462   const auto *BitIntValType = ValType->getAs<BitIntType>();
6463   if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
6464     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6465     return ExprError();
6466   }
6467 
6468   return TheCallResult;
6469 }
6470 
6471 /// SemaBuiltinNontemporalOverloaded - We have a call to
6472 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6473 /// overloaded function based on the pointer type of its last argument.
6474 ///
6475 /// This function goes through and does final semantic checking for these
6476 /// builtins.
6477 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6478   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6479   DeclRefExpr *DRE =
6480       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6481   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6482   unsigned BuiltinID = FDecl->getBuiltinID();
6483   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6484           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6485          "Unexpected nontemporal load/store builtin!");
6486   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6487   unsigned numArgs = isStore ? 2 : 1;
6488 
6489   // Ensure that we have the proper number of arguments.
6490   if (checkArgCount(*this, TheCall, numArgs))
6491     return ExprError();
6492 
6493   // Inspect the last argument of the nontemporal builtin.  This should always
6494   // be a pointer type, from which we imply the type of the memory access.
6495   // Because it is a pointer type, we don't have to worry about any implicit
6496   // casts here.
6497   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6498   ExprResult PointerArgResult =
6499       DefaultFunctionArrayLvalueConversion(PointerArg);
6500 
6501   if (PointerArgResult.isInvalid())
6502     return ExprError();
6503   PointerArg = PointerArgResult.get();
6504   TheCall->setArg(numArgs - 1, PointerArg);
6505 
6506   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6507   if (!pointerType) {
6508     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6509         << PointerArg->getType() << PointerArg->getSourceRange();
6510     return ExprError();
6511   }
6512 
6513   QualType ValType = pointerType->getPointeeType();
6514 
6515   // Strip any qualifiers off ValType.
6516   ValType = ValType.getUnqualifiedType();
6517   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6518       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6519       !ValType->isVectorType()) {
6520     Diag(DRE->getBeginLoc(),
6521          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6522         << PointerArg->getType() << PointerArg->getSourceRange();
6523     return ExprError();
6524   }
6525 
6526   if (!isStore) {
6527     TheCall->setType(ValType);
6528     return TheCallResult;
6529   }
6530 
6531   ExprResult ValArg = TheCall->getArg(0);
6532   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6533       Context, ValType, /*consume*/ false);
6534   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6535   if (ValArg.isInvalid())
6536     return ExprError();
6537 
6538   TheCall->setArg(0, ValArg.get());
6539   TheCall->setType(Context.VoidTy);
6540   return TheCallResult;
6541 }
6542 
6543 /// CheckObjCString - Checks that the argument to the builtin
6544 /// CFString constructor is correct
6545 /// Note: It might also make sense to do the UTF-16 conversion here (would
6546 /// simplify the backend).
6547 bool Sema::CheckObjCString(Expr *Arg) {
6548   Arg = Arg->IgnoreParenCasts();
6549   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6550 
6551   if (!Literal || !Literal->isAscii()) {
6552     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6553         << Arg->getSourceRange();
6554     return true;
6555   }
6556 
6557   if (Literal->containsNonAsciiOrNull()) {
6558     StringRef String = Literal->getString();
6559     unsigned NumBytes = String.size();
6560     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6561     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6562     llvm::UTF16 *ToPtr = &ToBuf[0];
6563 
6564     llvm::ConversionResult Result =
6565         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6566                                  ToPtr + NumBytes, llvm::strictConversion);
6567     // Check for conversion failure.
6568     if (Result != llvm::conversionOK)
6569       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6570           << Arg->getSourceRange();
6571   }
6572   return false;
6573 }
6574 
6575 /// CheckObjCString - Checks that the format string argument to the os_log()
6576 /// and os_trace() functions is correct, and converts it to const char *.
6577 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6578   Arg = Arg->IgnoreParenCasts();
6579   auto *Literal = dyn_cast<StringLiteral>(Arg);
6580   if (!Literal) {
6581     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6582       Literal = ObjcLiteral->getString();
6583     }
6584   }
6585 
6586   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6587     return ExprError(
6588         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6589         << Arg->getSourceRange());
6590   }
6591 
6592   ExprResult Result(Literal);
6593   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6594   InitializedEntity Entity =
6595       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6596   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6597   return Result;
6598 }
6599 
6600 /// Check that the user is calling the appropriate va_start builtin for the
6601 /// target and calling convention.
6602 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6603   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6604   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6605   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6606                     TT.getArch() == llvm::Triple::aarch64_32);
6607   bool IsWindows = TT.isOSWindows();
6608   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6609   if (IsX64 || IsAArch64) {
6610     CallingConv CC = CC_C;
6611     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6612       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6613     if (IsMSVAStart) {
6614       // Don't allow this in System V ABI functions.
6615       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6616         return S.Diag(Fn->getBeginLoc(),
6617                       diag::err_ms_va_start_used_in_sysv_function);
6618     } else {
6619       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6620       // On x64 Windows, don't allow this in System V ABI functions.
6621       // (Yes, that means there's no corresponding way to support variadic
6622       // System V ABI functions on Windows.)
6623       if ((IsWindows && CC == CC_X86_64SysV) ||
6624           (!IsWindows && CC == CC_Win64))
6625         return S.Diag(Fn->getBeginLoc(),
6626                       diag::err_va_start_used_in_wrong_abi_function)
6627                << !IsWindows;
6628     }
6629     return false;
6630   }
6631 
6632   if (IsMSVAStart)
6633     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6634   return false;
6635 }
6636 
6637 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6638                                              ParmVarDecl **LastParam = nullptr) {
6639   // Determine whether the current function, block, or obj-c method is variadic
6640   // and get its parameter list.
6641   bool IsVariadic = false;
6642   ArrayRef<ParmVarDecl *> Params;
6643   DeclContext *Caller = S.CurContext;
6644   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6645     IsVariadic = Block->isVariadic();
6646     Params = Block->parameters();
6647   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6648     IsVariadic = FD->isVariadic();
6649     Params = FD->parameters();
6650   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6651     IsVariadic = MD->isVariadic();
6652     // FIXME: This isn't correct for methods (results in bogus warning).
6653     Params = MD->parameters();
6654   } else if (isa<CapturedDecl>(Caller)) {
6655     // We don't support va_start in a CapturedDecl.
6656     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6657     return true;
6658   } else {
6659     // This must be some other declcontext that parses exprs.
6660     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6661     return true;
6662   }
6663 
6664   if (!IsVariadic) {
6665     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6666     return true;
6667   }
6668 
6669   if (LastParam)
6670     *LastParam = Params.empty() ? nullptr : Params.back();
6671 
6672   return false;
6673 }
6674 
6675 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6676 /// for validity.  Emit an error and return true on failure; return false
6677 /// on success.
6678 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6679   Expr *Fn = TheCall->getCallee();
6680 
6681   if (checkVAStartABI(*this, BuiltinID, Fn))
6682     return true;
6683 
6684   if (checkArgCount(*this, TheCall, 2))
6685     return true;
6686 
6687   // Type-check the first argument normally.
6688   if (checkBuiltinArgument(*this, TheCall, 0))
6689     return true;
6690 
6691   // Check that the current function is variadic, and get its last parameter.
6692   ParmVarDecl *LastParam;
6693   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6694     return true;
6695 
6696   // Verify that the second argument to the builtin is the last argument of the
6697   // current function or method.
6698   bool SecondArgIsLastNamedArgument = false;
6699   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6700 
6701   // These are valid if SecondArgIsLastNamedArgument is false after the next
6702   // block.
6703   QualType Type;
6704   SourceLocation ParamLoc;
6705   bool IsCRegister = false;
6706 
6707   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6708     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6709       SecondArgIsLastNamedArgument = PV == LastParam;
6710 
6711       Type = PV->getType();
6712       ParamLoc = PV->getLocation();
6713       IsCRegister =
6714           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6715     }
6716   }
6717 
6718   if (!SecondArgIsLastNamedArgument)
6719     Diag(TheCall->getArg(1)->getBeginLoc(),
6720          diag::warn_second_arg_of_va_start_not_last_named_param);
6721   else if (IsCRegister || Type->isReferenceType() ||
6722            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6723              // Promotable integers are UB, but enumerations need a bit of
6724              // extra checking to see what their promotable type actually is.
6725              if (!Type->isPromotableIntegerType())
6726                return false;
6727              if (!Type->isEnumeralType())
6728                return true;
6729              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6730              return !(ED &&
6731                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6732            }()) {
6733     unsigned Reason = 0;
6734     if (Type->isReferenceType())  Reason = 1;
6735     else if (IsCRegister)         Reason = 2;
6736     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6737     Diag(ParamLoc, diag::note_parameter_type) << Type;
6738   }
6739 
6740   TheCall->setType(Context.VoidTy);
6741   return false;
6742 }
6743 
6744 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6745   auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6746     const LangOptions &LO = getLangOpts();
6747 
6748     if (LO.CPlusPlus)
6749       return Arg->getType()
6750                  .getCanonicalType()
6751                  .getTypePtr()
6752                  ->getPointeeType()
6753                  .withoutLocalFastQualifiers() == Context.CharTy;
6754 
6755     // In C, allow aliasing through `char *`, this is required for AArch64 at
6756     // least.
6757     return true;
6758   };
6759 
6760   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6761   //                 const char *named_addr);
6762 
6763   Expr *Func = Call->getCallee();
6764 
6765   if (Call->getNumArgs() < 3)
6766     return Diag(Call->getEndLoc(),
6767                 diag::err_typecheck_call_too_few_args_at_least)
6768            << 0 /*function call*/ << 3 << Call->getNumArgs();
6769 
6770   // Type-check the first argument normally.
6771   if (checkBuiltinArgument(*this, Call, 0))
6772     return true;
6773 
6774   // Check that the current function is variadic.
6775   if (checkVAStartIsInVariadicFunction(*this, Func))
6776     return true;
6777 
6778   // __va_start on Windows does not validate the parameter qualifiers
6779 
6780   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6781   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6782 
6783   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6784   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6785 
6786   const QualType &ConstCharPtrTy =
6787       Context.getPointerType(Context.CharTy.withConst());
6788   if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6789     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6790         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6791         << 0                                      /* qualifier difference */
6792         << 3                                      /* parameter mismatch */
6793         << 2 << Arg1->getType() << ConstCharPtrTy;
6794 
6795   const QualType SizeTy = Context.getSizeType();
6796   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6797     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6798         << Arg2->getType() << SizeTy << 1 /* different class */
6799         << 0                              /* qualifier difference */
6800         << 3                              /* parameter mismatch */
6801         << 3 << Arg2->getType() << SizeTy;
6802 
6803   return false;
6804 }
6805 
6806 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6807 /// friends.  This is declared to take (...), so we have to check everything.
6808 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6809   if (checkArgCount(*this, TheCall, 2))
6810     return true;
6811 
6812   ExprResult OrigArg0 = TheCall->getArg(0);
6813   ExprResult OrigArg1 = TheCall->getArg(1);
6814 
6815   // Do standard promotions between the two arguments, returning their common
6816   // type.
6817   QualType Res = UsualArithmeticConversions(
6818       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6819   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6820     return true;
6821 
6822   // Make sure any conversions are pushed back into the call; this is
6823   // type safe since unordered compare builtins are declared as "_Bool
6824   // foo(...)".
6825   TheCall->setArg(0, OrigArg0.get());
6826   TheCall->setArg(1, OrigArg1.get());
6827 
6828   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6829     return false;
6830 
6831   // If the common type isn't a real floating type, then the arguments were
6832   // invalid for this operation.
6833   if (Res.isNull() || !Res->isRealFloatingType())
6834     return Diag(OrigArg0.get()->getBeginLoc(),
6835                 diag::err_typecheck_call_invalid_ordered_compare)
6836            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6837            << SourceRange(OrigArg0.get()->getBeginLoc(),
6838                           OrigArg1.get()->getEndLoc());
6839 
6840   return false;
6841 }
6842 
6843 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6844 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6845 /// to check everything. We expect the last argument to be a floating point
6846 /// value.
6847 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6848   if (checkArgCount(*this, TheCall, NumArgs))
6849     return true;
6850 
6851   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6852   // on all preceding parameters just being int.  Try all of those.
6853   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6854     Expr *Arg = TheCall->getArg(i);
6855 
6856     if (Arg->isTypeDependent())
6857       return false;
6858 
6859     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6860 
6861     if (Res.isInvalid())
6862       return true;
6863     TheCall->setArg(i, Res.get());
6864   }
6865 
6866   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6867 
6868   if (OrigArg->isTypeDependent())
6869     return false;
6870 
6871   // Usual Unary Conversions will convert half to float, which we want for
6872   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6873   // type how it is, but do normal L->Rvalue conversions.
6874   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6875     OrigArg = UsualUnaryConversions(OrigArg).get();
6876   else
6877     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6878   TheCall->setArg(NumArgs - 1, OrigArg);
6879 
6880   // This operation requires a non-_Complex floating-point number.
6881   if (!OrigArg->getType()->isRealFloatingType())
6882     return Diag(OrigArg->getBeginLoc(),
6883                 diag::err_typecheck_call_invalid_unary_fp)
6884            << OrigArg->getType() << OrigArg->getSourceRange();
6885 
6886   return false;
6887 }
6888 
6889 /// Perform semantic analysis for a call to __builtin_complex.
6890 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6891   if (checkArgCount(*this, TheCall, 2))
6892     return true;
6893 
6894   bool Dependent = false;
6895   for (unsigned I = 0; I != 2; ++I) {
6896     Expr *Arg = TheCall->getArg(I);
6897     QualType T = Arg->getType();
6898     if (T->isDependentType()) {
6899       Dependent = true;
6900       continue;
6901     }
6902 
6903     // Despite supporting _Complex int, GCC requires a real floating point type
6904     // for the operands of __builtin_complex.
6905     if (!T->isRealFloatingType()) {
6906       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6907              << Arg->getType() << Arg->getSourceRange();
6908     }
6909 
6910     ExprResult Converted = DefaultLvalueConversion(Arg);
6911     if (Converted.isInvalid())
6912       return true;
6913     TheCall->setArg(I, Converted.get());
6914   }
6915 
6916   if (Dependent) {
6917     TheCall->setType(Context.DependentTy);
6918     return false;
6919   }
6920 
6921   Expr *Real = TheCall->getArg(0);
6922   Expr *Imag = TheCall->getArg(1);
6923   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6924     return Diag(Real->getBeginLoc(),
6925                 diag::err_typecheck_call_different_arg_types)
6926            << Real->getType() << Imag->getType()
6927            << Real->getSourceRange() << Imag->getSourceRange();
6928   }
6929 
6930   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6931   // don't allow this builtin to form those types either.
6932   // FIXME: Should we allow these types?
6933   if (Real->getType()->isFloat16Type())
6934     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6935            << "_Float16";
6936   if (Real->getType()->isHalfType())
6937     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6938            << "half";
6939 
6940   TheCall->setType(Context.getComplexType(Real->getType()));
6941   return false;
6942 }
6943 
6944 // Customized Sema Checking for VSX builtins that have the following signature:
6945 // vector [...] builtinName(vector [...], vector [...], const int);
6946 // Which takes the same type of vectors (any legal vector type) for the first
6947 // two arguments and takes compile time constant for the third argument.
6948 // Example builtins are :
6949 // vector double vec_xxpermdi(vector double, vector double, int);
6950 // vector short vec_xxsldwi(vector short, vector short, int);
6951 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6952   unsigned ExpectedNumArgs = 3;
6953   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6954     return true;
6955 
6956   // Check the third argument is a compile time constant
6957   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6958     return Diag(TheCall->getBeginLoc(),
6959                 diag::err_vsx_builtin_nonconstant_argument)
6960            << 3 /* argument index */ << TheCall->getDirectCallee()
6961            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6962                           TheCall->getArg(2)->getEndLoc());
6963 
6964   QualType Arg1Ty = TheCall->getArg(0)->getType();
6965   QualType Arg2Ty = TheCall->getArg(1)->getType();
6966 
6967   // Check the type of argument 1 and argument 2 are vectors.
6968   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6969   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6970       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6971     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6972            << TheCall->getDirectCallee()
6973            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6974                           TheCall->getArg(1)->getEndLoc());
6975   }
6976 
6977   // Check the first two arguments are the same type.
6978   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6979     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6980            << TheCall->getDirectCallee()
6981            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6982                           TheCall->getArg(1)->getEndLoc());
6983   }
6984 
6985   // When default clang type checking is turned off and the customized type
6986   // checking is used, the returning type of the function must be explicitly
6987   // set. Otherwise it is _Bool by default.
6988   TheCall->setType(Arg1Ty);
6989 
6990   return false;
6991 }
6992 
6993 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6994 // This is declared to take (...), so we have to check everything.
6995 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6996   if (TheCall->getNumArgs() < 2)
6997     return ExprError(Diag(TheCall->getEndLoc(),
6998                           diag::err_typecheck_call_too_few_args_at_least)
6999                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
7000                      << TheCall->getSourceRange());
7001 
7002   // Determine which of the following types of shufflevector we're checking:
7003   // 1) unary, vector mask: (lhs, mask)
7004   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
7005   QualType resType = TheCall->getArg(0)->getType();
7006   unsigned numElements = 0;
7007 
7008   if (!TheCall->getArg(0)->isTypeDependent() &&
7009       !TheCall->getArg(1)->isTypeDependent()) {
7010     QualType LHSType = TheCall->getArg(0)->getType();
7011     QualType RHSType = TheCall->getArg(1)->getType();
7012 
7013     if (!LHSType->isVectorType() || !RHSType->isVectorType())
7014       return ExprError(
7015           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
7016           << TheCall->getDirectCallee()
7017           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7018                          TheCall->getArg(1)->getEndLoc()));
7019 
7020     numElements = LHSType->castAs<VectorType>()->getNumElements();
7021     unsigned numResElements = TheCall->getNumArgs() - 2;
7022 
7023     // Check to see if we have a call with 2 vector arguments, the unary shuffle
7024     // with mask.  If so, verify that RHS is an integer vector type with the
7025     // same number of elts as lhs.
7026     if (TheCall->getNumArgs() == 2) {
7027       if (!RHSType->hasIntegerRepresentation() ||
7028           RHSType->castAs<VectorType>()->getNumElements() != numElements)
7029         return ExprError(Diag(TheCall->getBeginLoc(),
7030                               diag::err_vec_builtin_incompatible_vector)
7031                          << TheCall->getDirectCallee()
7032                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
7033                                         TheCall->getArg(1)->getEndLoc()));
7034     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
7035       return ExprError(Diag(TheCall->getBeginLoc(),
7036                             diag::err_vec_builtin_incompatible_vector)
7037                        << TheCall->getDirectCallee()
7038                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7039                                       TheCall->getArg(1)->getEndLoc()));
7040     } else if (numElements != numResElements) {
7041       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
7042       resType = Context.getVectorType(eltType, numResElements,
7043                                       VectorType::GenericVector);
7044     }
7045   }
7046 
7047   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
7048     if (TheCall->getArg(i)->isTypeDependent() ||
7049         TheCall->getArg(i)->isValueDependent())
7050       continue;
7051 
7052     Optional<llvm::APSInt> Result;
7053     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
7054       return ExprError(Diag(TheCall->getBeginLoc(),
7055                             diag::err_shufflevector_nonconstant_argument)
7056                        << TheCall->getArg(i)->getSourceRange());
7057 
7058     // Allow -1 which will be translated to undef in the IR.
7059     if (Result->isSigned() && Result->isAllOnes())
7060       continue;
7061 
7062     if (Result->getActiveBits() > 64 ||
7063         Result->getZExtValue() >= numElements * 2)
7064       return ExprError(Diag(TheCall->getBeginLoc(),
7065                             diag::err_shufflevector_argument_too_large)
7066                        << TheCall->getArg(i)->getSourceRange());
7067   }
7068 
7069   SmallVector<Expr*, 32> exprs;
7070 
7071   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
7072     exprs.push_back(TheCall->getArg(i));
7073     TheCall->setArg(i, nullptr);
7074   }
7075 
7076   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
7077                                          TheCall->getCallee()->getBeginLoc(),
7078                                          TheCall->getRParenLoc());
7079 }
7080 
7081 /// SemaConvertVectorExpr - Handle __builtin_convertvector
7082 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
7083                                        SourceLocation BuiltinLoc,
7084                                        SourceLocation RParenLoc) {
7085   ExprValueKind VK = VK_PRValue;
7086   ExprObjectKind OK = OK_Ordinary;
7087   QualType DstTy = TInfo->getType();
7088   QualType SrcTy = E->getType();
7089 
7090   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
7091     return ExprError(Diag(BuiltinLoc,
7092                           diag::err_convertvector_non_vector)
7093                      << E->getSourceRange());
7094   if (!DstTy->isVectorType() && !DstTy->isDependentType())
7095     return ExprError(Diag(BuiltinLoc,
7096                           diag::err_convertvector_non_vector_type));
7097 
7098   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
7099     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
7100     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
7101     if (SrcElts != DstElts)
7102       return ExprError(Diag(BuiltinLoc,
7103                             diag::err_convertvector_incompatible_vector)
7104                        << E->getSourceRange());
7105   }
7106 
7107   return new (Context)
7108       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
7109 }
7110 
7111 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
7112 // This is declared to take (const void*, ...) and can take two
7113 // optional constant int args.
7114 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
7115   unsigned NumArgs = TheCall->getNumArgs();
7116 
7117   if (NumArgs > 3)
7118     return Diag(TheCall->getEndLoc(),
7119                 diag::err_typecheck_call_too_many_args_at_most)
7120            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7121 
7122   // Argument 0 is checked for us and the remaining arguments must be
7123   // constant integers.
7124   for (unsigned i = 1; i != NumArgs; ++i)
7125     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
7126       return true;
7127 
7128   return false;
7129 }
7130 
7131 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
7132 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
7133   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
7134     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
7135            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7136   if (checkArgCount(*this, TheCall, 1))
7137     return true;
7138   Expr *Arg = TheCall->getArg(0);
7139   if (Arg->isInstantiationDependent())
7140     return false;
7141 
7142   QualType ArgTy = Arg->getType();
7143   if (!ArgTy->hasFloatingRepresentation())
7144     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
7145            << ArgTy;
7146   if (Arg->isLValue()) {
7147     ExprResult FirstArg = DefaultLvalueConversion(Arg);
7148     TheCall->setArg(0, FirstArg.get());
7149   }
7150   TheCall->setType(TheCall->getArg(0)->getType());
7151   return false;
7152 }
7153 
7154 /// SemaBuiltinAssume - Handle __assume (MS Extension).
7155 // __assume does not evaluate its arguments, and should warn if its argument
7156 // has side effects.
7157 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
7158   Expr *Arg = TheCall->getArg(0);
7159   if (Arg->isInstantiationDependent()) return false;
7160 
7161   if (Arg->HasSideEffects(Context))
7162     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
7163         << Arg->getSourceRange()
7164         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
7165 
7166   return false;
7167 }
7168 
7169 /// Handle __builtin_alloca_with_align. This is declared
7170 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
7171 /// than 8.
7172 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
7173   // The alignment must be a constant integer.
7174   Expr *Arg = TheCall->getArg(1);
7175 
7176   // We can't check the value of a dependent argument.
7177   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7178     if (const auto *UE =
7179             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
7180       if (UE->getKind() == UETT_AlignOf ||
7181           UE->getKind() == UETT_PreferredAlignOf)
7182         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
7183             << Arg->getSourceRange();
7184 
7185     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
7186 
7187     if (!Result.isPowerOf2())
7188       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7189              << Arg->getSourceRange();
7190 
7191     if (Result < Context.getCharWidth())
7192       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
7193              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
7194 
7195     if (Result > std::numeric_limits<int32_t>::max())
7196       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
7197              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
7198   }
7199 
7200   return false;
7201 }
7202 
7203 /// Handle __builtin_assume_aligned. This is declared
7204 /// as (const void*, size_t, ...) and can take one optional constant int arg.
7205 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
7206   unsigned NumArgs = TheCall->getNumArgs();
7207 
7208   if (NumArgs > 3)
7209     return Diag(TheCall->getEndLoc(),
7210                 diag::err_typecheck_call_too_many_args_at_most)
7211            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7212 
7213   // The alignment must be a constant integer.
7214   Expr *Arg = TheCall->getArg(1);
7215 
7216   // We can't check the value of a dependent argument.
7217   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7218     llvm::APSInt Result;
7219     if (SemaBuiltinConstantArg(TheCall, 1, Result))
7220       return true;
7221 
7222     if (!Result.isPowerOf2())
7223       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7224              << Arg->getSourceRange();
7225 
7226     if (Result > Sema::MaximumAlignment)
7227       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
7228           << Arg->getSourceRange() << Sema::MaximumAlignment;
7229   }
7230 
7231   if (NumArgs > 2) {
7232     ExprResult Arg(TheCall->getArg(2));
7233     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
7234       Context.getSizeType(), false);
7235     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7236     if (Arg.isInvalid()) return true;
7237     TheCall->setArg(2, Arg.get());
7238   }
7239 
7240   return false;
7241 }
7242 
7243 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
7244   unsigned BuiltinID =
7245       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
7246   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
7247 
7248   unsigned NumArgs = TheCall->getNumArgs();
7249   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
7250   if (NumArgs < NumRequiredArgs) {
7251     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
7252            << 0 /* function call */ << NumRequiredArgs << NumArgs
7253            << TheCall->getSourceRange();
7254   }
7255   if (NumArgs >= NumRequiredArgs + 0x100) {
7256     return Diag(TheCall->getEndLoc(),
7257                 diag::err_typecheck_call_too_many_args_at_most)
7258            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
7259            << TheCall->getSourceRange();
7260   }
7261   unsigned i = 0;
7262 
7263   // For formatting call, check buffer arg.
7264   if (!IsSizeCall) {
7265     ExprResult Arg(TheCall->getArg(i));
7266     InitializedEntity Entity = InitializedEntity::InitializeParameter(
7267         Context, Context.VoidPtrTy, false);
7268     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7269     if (Arg.isInvalid())
7270       return true;
7271     TheCall->setArg(i, Arg.get());
7272     i++;
7273   }
7274 
7275   // Check string literal arg.
7276   unsigned FormatIdx = i;
7277   {
7278     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
7279     if (Arg.isInvalid())
7280       return true;
7281     TheCall->setArg(i, Arg.get());
7282     i++;
7283   }
7284 
7285   // Make sure variadic args are scalar.
7286   unsigned FirstDataArg = i;
7287   while (i < NumArgs) {
7288     ExprResult Arg = DefaultVariadicArgumentPromotion(
7289         TheCall->getArg(i), VariadicFunction, nullptr);
7290     if (Arg.isInvalid())
7291       return true;
7292     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
7293     if (ArgSize.getQuantity() >= 0x100) {
7294       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
7295              << i << (int)ArgSize.getQuantity() << 0xff
7296              << TheCall->getSourceRange();
7297     }
7298     TheCall->setArg(i, Arg.get());
7299     i++;
7300   }
7301 
7302   // Check formatting specifiers. NOTE: We're only doing this for the non-size
7303   // call to avoid duplicate diagnostics.
7304   if (!IsSizeCall) {
7305     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
7306     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
7307     bool Success = CheckFormatArguments(
7308         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
7309         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
7310         CheckedVarArgs);
7311     if (!Success)
7312       return true;
7313   }
7314 
7315   if (IsSizeCall) {
7316     TheCall->setType(Context.getSizeType());
7317   } else {
7318     TheCall->setType(Context.VoidPtrTy);
7319   }
7320   return false;
7321 }
7322 
7323 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
7324 /// TheCall is a constant expression.
7325 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7326                                   llvm::APSInt &Result) {
7327   Expr *Arg = TheCall->getArg(ArgNum);
7328   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
7329   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
7330 
7331   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
7332 
7333   Optional<llvm::APSInt> R;
7334   if (!(R = Arg->getIntegerConstantExpr(Context)))
7335     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
7336            << FDecl->getDeclName() << Arg->getSourceRange();
7337   Result = *R;
7338   return false;
7339 }
7340 
7341 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
7342 /// TheCall is a constant expression in the range [Low, High].
7343 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
7344                                        int Low, int High, bool RangeIsError) {
7345   if (isConstantEvaluated())
7346     return false;
7347   llvm::APSInt Result;
7348 
7349   // We can't check the value of a dependent argument.
7350   Expr *Arg = TheCall->getArg(ArgNum);
7351   if (Arg->isTypeDependent() || Arg->isValueDependent())
7352     return false;
7353 
7354   // Check constant-ness first.
7355   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7356     return true;
7357 
7358   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7359     if (RangeIsError)
7360       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
7361              << toString(Result, 10) << Low << High << Arg->getSourceRange();
7362     else
7363       // Defer the warning until we know if the code will be emitted so that
7364       // dead code can ignore this.
7365       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
7366                           PDiag(diag::warn_argument_invalid_range)
7367                               << toString(Result, 10) << Low << High
7368                               << Arg->getSourceRange());
7369   }
7370 
7371   return false;
7372 }
7373 
7374 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
7375 /// TheCall is a constant expression is a multiple of Num..
7376 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
7377                                           unsigned Num) {
7378   llvm::APSInt Result;
7379 
7380   // We can't check the value of a dependent argument.
7381   Expr *Arg = TheCall->getArg(ArgNum);
7382   if (Arg->isTypeDependent() || Arg->isValueDependent())
7383     return false;
7384 
7385   // Check constant-ness first.
7386   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7387     return true;
7388 
7389   if (Result.getSExtValue() % Num != 0)
7390     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7391            << Num << Arg->getSourceRange();
7392 
7393   return false;
7394 }
7395 
7396 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7397 /// constant expression representing a power of 2.
7398 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7399   llvm::APSInt Result;
7400 
7401   // We can't check the value of a dependent argument.
7402   Expr *Arg = TheCall->getArg(ArgNum);
7403   if (Arg->isTypeDependent() || Arg->isValueDependent())
7404     return false;
7405 
7406   // Check constant-ness first.
7407   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7408     return true;
7409 
7410   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7411   // and only if x is a power of 2.
7412   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7413     return false;
7414 
7415   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7416          << Arg->getSourceRange();
7417 }
7418 
7419 static bool IsShiftedByte(llvm::APSInt Value) {
7420   if (Value.isNegative())
7421     return false;
7422 
7423   // Check if it's a shifted byte, by shifting it down
7424   while (true) {
7425     // If the value fits in the bottom byte, the check passes.
7426     if (Value < 0x100)
7427       return true;
7428 
7429     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7430     // fails.
7431     if ((Value & 0xFF) != 0)
7432       return false;
7433 
7434     // If the bottom 8 bits are all 0, but something above that is nonzero,
7435     // then shifting the value right by 8 bits won't affect whether it's a
7436     // shifted byte or not. So do that, and go round again.
7437     Value >>= 8;
7438   }
7439 }
7440 
7441 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7442 /// a constant expression representing an arbitrary byte value shifted left by
7443 /// a multiple of 8 bits.
7444 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7445                                              unsigned ArgBits) {
7446   llvm::APSInt Result;
7447 
7448   // We can't check the value of a dependent argument.
7449   Expr *Arg = TheCall->getArg(ArgNum);
7450   if (Arg->isTypeDependent() || Arg->isValueDependent())
7451     return false;
7452 
7453   // Check constant-ness first.
7454   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7455     return true;
7456 
7457   // Truncate to the given size.
7458   Result = Result.getLoBits(ArgBits);
7459   Result.setIsUnsigned(true);
7460 
7461   if (IsShiftedByte(Result))
7462     return false;
7463 
7464   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7465          << Arg->getSourceRange();
7466 }
7467 
7468 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7469 /// TheCall is a constant expression representing either a shifted byte value,
7470 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7471 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7472 /// Arm MVE intrinsics.
7473 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7474                                                    int ArgNum,
7475                                                    unsigned ArgBits) {
7476   llvm::APSInt Result;
7477 
7478   // We can't check the value of a dependent argument.
7479   Expr *Arg = TheCall->getArg(ArgNum);
7480   if (Arg->isTypeDependent() || Arg->isValueDependent())
7481     return false;
7482 
7483   // Check constant-ness first.
7484   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7485     return true;
7486 
7487   // Truncate to the given size.
7488   Result = Result.getLoBits(ArgBits);
7489   Result.setIsUnsigned(true);
7490 
7491   // Check to see if it's in either of the required forms.
7492   if (IsShiftedByte(Result) ||
7493       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7494     return false;
7495 
7496   return Diag(TheCall->getBeginLoc(),
7497               diag::err_argument_not_shifted_byte_or_xxff)
7498          << Arg->getSourceRange();
7499 }
7500 
7501 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7502 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7503   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7504     if (checkArgCount(*this, TheCall, 2))
7505       return true;
7506     Expr *Arg0 = TheCall->getArg(0);
7507     Expr *Arg1 = TheCall->getArg(1);
7508 
7509     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7510     if (FirstArg.isInvalid())
7511       return true;
7512     QualType FirstArgType = FirstArg.get()->getType();
7513     if (!FirstArgType->isAnyPointerType())
7514       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7515                << "first" << FirstArgType << Arg0->getSourceRange();
7516     TheCall->setArg(0, FirstArg.get());
7517 
7518     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7519     if (SecArg.isInvalid())
7520       return true;
7521     QualType SecArgType = SecArg.get()->getType();
7522     if (!SecArgType->isIntegerType())
7523       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7524                << "second" << SecArgType << Arg1->getSourceRange();
7525 
7526     // Derive the return type from the pointer argument.
7527     TheCall->setType(FirstArgType);
7528     return false;
7529   }
7530 
7531   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7532     if (checkArgCount(*this, TheCall, 2))
7533       return true;
7534 
7535     Expr *Arg0 = TheCall->getArg(0);
7536     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7537     if (FirstArg.isInvalid())
7538       return true;
7539     QualType FirstArgType = FirstArg.get()->getType();
7540     if (!FirstArgType->isAnyPointerType())
7541       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7542                << "first" << FirstArgType << Arg0->getSourceRange();
7543     TheCall->setArg(0, FirstArg.get());
7544 
7545     // Derive the return type from the pointer argument.
7546     TheCall->setType(FirstArgType);
7547 
7548     // Second arg must be an constant in range [0,15]
7549     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7550   }
7551 
7552   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7553     if (checkArgCount(*this, TheCall, 2))
7554       return true;
7555     Expr *Arg0 = TheCall->getArg(0);
7556     Expr *Arg1 = TheCall->getArg(1);
7557 
7558     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7559     if (FirstArg.isInvalid())
7560       return true;
7561     QualType FirstArgType = FirstArg.get()->getType();
7562     if (!FirstArgType->isAnyPointerType())
7563       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7564                << "first" << FirstArgType << Arg0->getSourceRange();
7565 
7566     QualType SecArgType = Arg1->getType();
7567     if (!SecArgType->isIntegerType())
7568       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7569                << "second" << SecArgType << Arg1->getSourceRange();
7570     TheCall->setType(Context.IntTy);
7571     return false;
7572   }
7573 
7574   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7575       BuiltinID == AArch64::BI__builtin_arm_stg) {
7576     if (checkArgCount(*this, TheCall, 1))
7577       return true;
7578     Expr *Arg0 = TheCall->getArg(0);
7579     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7580     if (FirstArg.isInvalid())
7581       return true;
7582 
7583     QualType FirstArgType = FirstArg.get()->getType();
7584     if (!FirstArgType->isAnyPointerType())
7585       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7586                << "first" << FirstArgType << Arg0->getSourceRange();
7587     TheCall->setArg(0, FirstArg.get());
7588 
7589     // Derive the return type from the pointer argument.
7590     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7591       TheCall->setType(FirstArgType);
7592     return false;
7593   }
7594 
7595   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7596     Expr *ArgA = TheCall->getArg(0);
7597     Expr *ArgB = TheCall->getArg(1);
7598 
7599     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7600     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7601 
7602     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7603       return true;
7604 
7605     QualType ArgTypeA = ArgExprA.get()->getType();
7606     QualType ArgTypeB = ArgExprB.get()->getType();
7607 
7608     auto isNull = [&] (Expr *E) -> bool {
7609       return E->isNullPointerConstant(
7610                         Context, Expr::NPC_ValueDependentIsNotNull); };
7611 
7612     // argument should be either a pointer or null
7613     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7614       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7615         << "first" << ArgTypeA << ArgA->getSourceRange();
7616 
7617     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7618       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7619         << "second" << ArgTypeB << ArgB->getSourceRange();
7620 
7621     // Ensure Pointee types are compatible
7622     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7623         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7624       QualType pointeeA = ArgTypeA->getPointeeType();
7625       QualType pointeeB = ArgTypeB->getPointeeType();
7626       if (!Context.typesAreCompatible(
7627              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7628              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7629         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7630           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7631           << ArgB->getSourceRange();
7632       }
7633     }
7634 
7635     // at least one argument should be pointer type
7636     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7637       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7638         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7639 
7640     if (isNull(ArgA)) // adopt type of the other pointer
7641       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7642 
7643     if (isNull(ArgB))
7644       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7645 
7646     TheCall->setArg(0, ArgExprA.get());
7647     TheCall->setArg(1, ArgExprB.get());
7648     TheCall->setType(Context.LongLongTy);
7649     return false;
7650   }
7651   assert(false && "Unhandled ARM MTE intrinsic");
7652   return true;
7653 }
7654 
7655 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7656 /// TheCall is an ARM/AArch64 special register string literal.
7657 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7658                                     int ArgNum, unsigned ExpectedFieldNum,
7659                                     bool AllowName) {
7660   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7661                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7662                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7663                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7664                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7665                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7666   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7667                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7668                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7669                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7670                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7671                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7672   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7673 
7674   // We can't check the value of a dependent argument.
7675   Expr *Arg = TheCall->getArg(ArgNum);
7676   if (Arg->isTypeDependent() || Arg->isValueDependent())
7677     return false;
7678 
7679   // Check if the argument is a string literal.
7680   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7681     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7682            << Arg->getSourceRange();
7683 
7684   // Check the type of special register given.
7685   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7686   SmallVector<StringRef, 6> Fields;
7687   Reg.split(Fields, ":");
7688 
7689   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7690     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7691            << Arg->getSourceRange();
7692 
7693   // If the string is the name of a register then we cannot check that it is
7694   // valid here but if the string is of one the forms described in ACLE then we
7695   // can check that the supplied fields are integers and within the valid
7696   // ranges.
7697   if (Fields.size() > 1) {
7698     bool FiveFields = Fields.size() == 5;
7699 
7700     bool ValidString = true;
7701     if (IsARMBuiltin) {
7702       ValidString &= Fields[0].startswith_insensitive("cp") ||
7703                      Fields[0].startswith_insensitive("p");
7704       if (ValidString)
7705         Fields[0] = Fields[0].drop_front(
7706             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7707 
7708       ValidString &= Fields[2].startswith_insensitive("c");
7709       if (ValidString)
7710         Fields[2] = Fields[2].drop_front(1);
7711 
7712       if (FiveFields) {
7713         ValidString &= Fields[3].startswith_insensitive("c");
7714         if (ValidString)
7715           Fields[3] = Fields[3].drop_front(1);
7716       }
7717     }
7718 
7719     SmallVector<int, 5> Ranges;
7720     if (FiveFields)
7721       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7722     else
7723       Ranges.append({15, 7, 15});
7724 
7725     for (unsigned i=0; i<Fields.size(); ++i) {
7726       int IntField;
7727       ValidString &= !Fields[i].getAsInteger(10, IntField);
7728       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7729     }
7730 
7731     if (!ValidString)
7732       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7733              << Arg->getSourceRange();
7734   } else if (IsAArch64Builtin && Fields.size() == 1) {
7735     // If the register name is one of those that appear in the condition below
7736     // and the special register builtin being used is one of the write builtins,
7737     // then we require that the argument provided for writing to the register
7738     // is an integer constant expression. This is because it will be lowered to
7739     // an MSR (immediate) instruction, so we need to know the immediate at
7740     // compile time.
7741     if (TheCall->getNumArgs() != 2)
7742       return false;
7743 
7744     std::string RegLower = Reg.lower();
7745     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7746         RegLower != "pan" && RegLower != "uao")
7747       return false;
7748 
7749     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7750   }
7751 
7752   return false;
7753 }
7754 
7755 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7756 /// Emit an error and return true on failure; return false on success.
7757 /// TypeStr is a string containing the type descriptor of the value returned by
7758 /// the builtin and the descriptors of the expected type of the arguments.
7759 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
7760                                  const char *TypeStr) {
7761 
7762   assert((TypeStr[0] != '\0') &&
7763          "Invalid types in PPC MMA builtin declaration");
7764 
7765   switch (BuiltinID) {
7766   default:
7767     // This function is called in CheckPPCBuiltinFunctionCall where the
7768     // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here
7769     // we are isolating the pair vector memop builtins that can be used with mma
7770     // off so the default case is every builtin that requires mma and paired
7771     // vector memops.
7772     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7773                          diag::err_ppc_builtin_only_on_arch, "10") ||
7774         SemaFeatureCheck(*this, TheCall, "mma",
7775                          diag::err_ppc_builtin_only_on_arch, "10"))
7776       return true;
7777     break;
7778   case PPC::BI__builtin_vsx_lxvp:
7779   case PPC::BI__builtin_vsx_stxvp:
7780   case PPC::BI__builtin_vsx_assemble_pair:
7781   case PPC::BI__builtin_vsx_disassemble_pair:
7782     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7783                          diag::err_ppc_builtin_only_on_arch, "10"))
7784       return true;
7785     break;
7786   }
7787 
7788   unsigned Mask = 0;
7789   unsigned ArgNum = 0;
7790 
7791   // The first type in TypeStr is the type of the value returned by the
7792   // builtin. So we first read that type and change the type of TheCall.
7793   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7794   TheCall->setType(type);
7795 
7796   while (*TypeStr != '\0') {
7797     Mask = 0;
7798     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7799     if (ArgNum >= TheCall->getNumArgs()) {
7800       ArgNum++;
7801       break;
7802     }
7803 
7804     Expr *Arg = TheCall->getArg(ArgNum);
7805     QualType PassedType = Arg->getType();
7806     QualType StrippedRVType = PassedType.getCanonicalType();
7807 
7808     // Strip Restrict/Volatile qualifiers.
7809     if (StrippedRVType.isRestrictQualified() ||
7810         StrippedRVType.isVolatileQualified())
7811       StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
7812 
7813     // The only case where the argument type and expected type are allowed to
7814     // mismatch is if the argument type is a non-void pointer (or array) and
7815     // expected type is a void pointer.
7816     if (StrippedRVType != ExpectedType)
7817       if (!(ExpectedType->isVoidPointerType() &&
7818             (StrippedRVType->isPointerType() || StrippedRVType->isArrayType())))
7819         return Diag(Arg->getBeginLoc(),
7820                     diag::err_typecheck_convert_incompatible)
7821                << PassedType << ExpectedType << 1 << 0 << 0;
7822 
7823     // If the value of the Mask is not 0, we have a constraint in the size of
7824     // the integer argument so here we ensure the argument is a constant that
7825     // is in the valid range.
7826     if (Mask != 0 &&
7827         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7828       return true;
7829 
7830     ArgNum++;
7831   }
7832 
7833   // In case we exited early from the previous loop, there are other types to
7834   // read from TypeStr. So we need to read them all to ensure we have the right
7835   // number of arguments in TheCall and if it is not the case, to display a
7836   // better error message.
7837   while (*TypeStr != '\0') {
7838     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7839     ArgNum++;
7840   }
7841   if (checkArgCount(*this, TheCall, ArgNum))
7842     return true;
7843 
7844   return false;
7845 }
7846 
7847 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7848 /// This checks that the target supports __builtin_longjmp and
7849 /// that val is a constant 1.
7850 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7851   if (!Context.getTargetInfo().hasSjLjLowering())
7852     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7853            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7854 
7855   Expr *Arg = TheCall->getArg(1);
7856   llvm::APSInt Result;
7857 
7858   // TODO: This is less than ideal. Overload this to take a value.
7859   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7860     return true;
7861 
7862   if (Result != 1)
7863     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7864            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7865 
7866   return false;
7867 }
7868 
7869 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7870 /// This checks that the target supports __builtin_setjmp.
7871 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7872   if (!Context.getTargetInfo().hasSjLjLowering())
7873     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7874            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7875   return false;
7876 }
7877 
7878 namespace {
7879 
7880 class UncoveredArgHandler {
7881   enum { Unknown = -1, AllCovered = -2 };
7882 
7883   signed FirstUncoveredArg = Unknown;
7884   SmallVector<const Expr *, 4> DiagnosticExprs;
7885 
7886 public:
7887   UncoveredArgHandler() = default;
7888 
7889   bool hasUncoveredArg() const {
7890     return (FirstUncoveredArg >= 0);
7891   }
7892 
7893   unsigned getUncoveredArg() const {
7894     assert(hasUncoveredArg() && "no uncovered argument");
7895     return FirstUncoveredArg;
7896   }
7897 
7898   void setAllCovered() {
7899     // A string has been found with all arguments covered, so clear out
7900     // the diagnostics.
7901     DiagnosticExprs.clear();
7902     FirstUncoveredArg = AllCovered;
7903   }
7904 
7905   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7906     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7907 
7908     // Don't update if a previous string covers all arguments.
7909     if (FirstUncoveredArg == AllCovered)
7910       return;
7911 
7912     // UncoveredArgHandler tracks the highest uncovered argument index
7913     // and with it all the strings that match this index.
7914     if (NewFirstUncoveredArg == FirstUncoveredArg)
7915       DiagnosticExprs.push_back(StrExpr);
7916     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7917       DiagnosticExprs.clear();
7918       DiagnosticExprs.push_back(StrExpr);
7919       FirstUncoveredArg = NewFirstUncoveredArg;
7920     }
7921   }
7922 
7923   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7924 };
7925 
7926 enum StringLiteralCheckType {
7927   SLCT_NotALiteral,
7928   SLCT_UncheckedLiteral,
7929   SLCT_CheckedLiteral
7930 };
7931 
7932 } // namespace
7933 
7934 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7935                                      BinaryOperatorKind BinOpKind,
7936                                      bool AddendIsRight) {
7937   unsigned BitWidth = Offset.getBitWidth();
7938   unsigned AddendBitWidth = Addend.getBitWidth();
7939   // There might be negative interim results.
7940   if (Addend.isUnsigned()) {
7941     Addend = Addend.zext(++AddendBitWidth);
7942     Addend.setIsSigned(true);
7943   }
7944   // Adjust the bit width of the APSInts.
7945   if (AddendBitWidth > BitWidth) {
7946     Offset = Offset.sext(AddendBitWidth);
7947     BitWidth = AddendBitWidth;
7948   } else if (BitWidth > AddendBitWidth) {
7949     Addend = Addend.sext(BitWidth);
7950   }
7951 
7952   bool Ov = false;
7953   llvm::APSInt ResOffset = Offset;
7954   if (BinOpKind == BO_Add)
7955     ResOffset = Offset.sadd_ov(Addend, Ov);
7956   else {
7957     assert(AddendIsRight && BinOpKind == BO_Sub &&
7958            "operator must be add or sub with addend on the right");
7959     ResOffset = Offset.ssub_ov(Addend, Ov);
7960   }
7961 
7962   // We add an offset to a pointer here so we should support an offset as big as
7963   // possible.
7964   if (Ov) {
7965     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7966            "index (intermediate) result too big");
7967     Offset = Offset.sext(2 * BitWidth);
7968     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7969     return;
7970   }
7971 
7972   Offset = ResOffset;
7973 }
7974 
7975 namespace {
7976 
7977 // This is a wrapper class around StringLiteral to support offsetted string
7978 // literals as format strings. It takes the offset into account when returning
7979 // the string and its length or the source locations to display notes correctly.
7980 class FormatStringLiteral {
7981   const StringLiteral *FExpr;
7982   int64_t Offset;
7983 
7984  public:
7985   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7986       : FExpr(fexpr), Offset(Offset) {}
7987 
7988   StringRef getString() const {
7989     return FExpr->getString().drop_front(Offset);
7990   }
7991 
7992   unsigned getByteLength() const {
7993     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7994   }
7995 
7996   unsigned getLength() const { return FExpr->getLength() - Offset; }
7997   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7998 
7999   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
8000 
8001   QualType getType() const { return FExpr->getType(); }
8002 
8003   bool isAscii() const { return FExpr->isAscii(); }
8004   bool isWide() const { return FExpr->isWide(); }
8005   bool isUTF8() const { return FExpr->isUTF8(); }
8006   bool isUTF16() const { return FExpr->isUTF16(); }
8007   bool isUTF32() const { return FExpr->isUTF32(); }
8008   bool isPascal() const { return FExpr->isPascal(); }
8009 
8010   SourceLocation getLocationOfByte(
8011       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
8012       const TargetInfo &Target, unsigned *StartToken = nullptr,
8013       unsigned *StartTokenByteOffset = nullptr) const {
8014     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
8015                                     StartToken, StartTokenByteOffset);
8016   }
8017 
8018   SourceLocation getBeginLoc() const LLVM_READONLY {
8019     return FExpr->getBeginLoc().getLocWithOffset(Offset);
8020   }
8021 
8022   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
8023 };
8024 
8025 }  // namespace
8026 
8027 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8028                               const Expr *OrigFormatExpr,
8029                               ArrayRef<const Expr *> Args,
8030                               bool HasVAListArg, unsigned format_idx,
8031                               unsigned firstDataArg,
8032                               Sema::FormatStringType Type,
8033                               bool inFunctionCall,
8034                               Sema::VariadicCallType CallType,
8035                               llvm::SmallBitVector &CheckedVarArgs,
8036                               UncoveredArgHandler &UncoveredArg,
8037                               bool IgnoreStringsWithoutSpecifiers);
8038 
8039 // Determine if an expression is a string literal or constant string.
8040 // If this function returns false on the arguments to a function expecting a
8041 // format string, we will usually need to emit a warning.
8042 // True string literals are then checked by CheckFormatString.
8043 static StringLiteralCheckType
8044 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
8045                       bool HasVAListArg, unsigned format_idx,
8046                       unsigned firstDataArg, Sema::FormatStringType Type,
8047                       Sema::VariadicCallType CallType, bool InFunctionCall,
8048                       llvm::SmallBitVector &CheckedVarArgs,
8049                       UncoveredArgHandler &UncoveredArg,
8050                       llvm::APSInt Offset,
8051                       bool IgnoreStringsWithoutSpecifiers = false) {
8052   if (S.isConstantEvaluated())
8053     return SLCT_NotALiteral;
8054  tryAgain:
8055   assert(Offset.isSigned() && "invalid offset");
8056 
8057   if (E->isTypeDependent() || E->isValueDependent())
8058     return SLCT_NotALiteral;
8059 
8060   E = E->IgnoreParenCasts();
8061 
8062   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
8063     // Technically -Wformat-nonliteral does not warn about this case.
8064     // The behavior of printf and friends in this case is implementation
8065     // dependent.  Ideally if the format string cannot be null then
8066     // it should have a 'nonnull' attribute in the function prototype.
8067     return SLCT_UncheckedLiteral;
8068 
8069   switch (E->getStmtClass()) {
8070   case Stmt::BinaryConditionalOperatorClass:
8071   case Stmt::ConditionalOperatorClass: {
8072     // The expression is a literal if both sub-expressions were, and it was
8073     // completely checked only if both sub-expressions were checked.
8074     const AbstractConditionalOperator *C =
8075         cast<AbstractConditionalOperator>(E);
8076 
8077     // Determine whether it is necessary to check both sub-expressions, for
8078     // example, because the condition expression is a constant that can be
8079     // evaluated at compile time.
8080     bool CheckLeft = true, CheckRight = true;
8081 
8082     bool Cond;
8083     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
8084                                                  S.isConstantEvaluated())) {
8085       if (Cond)
8086         CheckRight = false;
8087       else
8088         CheckLeft = false;
8089     }
8090 
8091     // We need to maintain the offsets for the right and the left hand side
8092     // separately to check if every possible indexed expression is a valid
8093     // string literal. They might have different offsets for different string
8094     // literals in the end.
8095     StringLiteralCheckType Left;
8096     if (!CheckLeft)
8097       Left = SLCT_UncheckedLiteral;
8098     else {
8099       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
8100                                    HasVAListArg, format_idx, firstDataArg,
8101                                    Type, CallType, InFunctionCall,
8102                                    CheckedVarArgs, UncoveredArg, Offset,
8103                                    IgnoreStringsWithoutSpecifiers);
8104       if (Left == SLCT_NotALiteral || !CheckRight) {
8105         return Left;
8106       }
8107     }
8108 
8109     StringLiteralCheckType Right = checkFormatStringExpr(
8110         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
8111         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8112         IgnoreStringsWithoutSpecifiers);
8113 
8114     return (CheckLeft && Left < Right) ? Left : Right;
8115   }
8116 
8117   case Stmt::ImplicitCastExprClass:
8118     E = cast<ImplicitCastExpr>(E)->getSubExpr();
8119     goto tryAgain;
8120 
8121   case Stmt::OpaqueValueExprClass:
8122     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
8123       E = src;
8124       goto tryAgain;
8125     }
8126     return SLCT_NotALiteral;
8127 
8128   case Stmt::PredefinedExprClass:
8129     // While __func__, etc., are technically not string literals, they
8130     // cannot contain format specifiers and thus are not a security
8131     // liability.
8132     return SLCT_UncheckedLiteral;
8133 
8134   case Stmt::DeclRefExprClass: {
8135     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8136 
8137     // As an exception, do not flag errors for variables binding to
8138     // const string literals.
8139     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
8140       bool isConstant = false;
8141       QualType T = DR->getType();
8142 
8143       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
8144         isConstant = AT->getElementType().isConstant(S.Context);
8145       } else if (const PointerType *PT = T->getAs<PointerType>()) {
8146         isConstant = T.isConstant(S.Context) &&
8147                      PT->getPointeeType().isConstant(S.Context);
8148       } else if (T->isObjCObjectPointerType()) {
8149         // In ObjC, there is usually no "const ObjectPointer" type,
8150         // so don't check if the pointee type is constant.
8151         isConstant = T.isConstant(S.Context);
8152       }
8153 
8154       if (isConstant) {
8155         if (const Expr *Init = VD->getAnyInitializer()) {
8156           // Look through initializers like const char c[] = { "foo" }
8157           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
8158             if (InitList->isStringLiteralInit())
8159               Init = InitList->getInit(0)->IgnoreParenImpCasts();
8160           }
8161           return checkFormatStringExpr(S, Init, Args,
8162                                        HasVAListArg, format_idx,
8163                                        firstDataArg, Type, CallType,
8164                                        /*InFunctionCall*/ false, CheckedVarArgs,
8165                                        UncoveredArg, Offset);
8166         }
8167       }
8168 
8169       // For vprintf* functions (i.e., HasVAListArg==true), we add a
8170       // special check to see if the format string is a function parameter
8171       // of the function calling the printf function.  If the function
8172       // has an attribute indicating it is a printf-like function, then we
8173       // should suppress warnings concerning non-literals being used in a call
8174       // to a vprintf function.  For example:
8175       //
8176       // void
8177       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
8178       //      va_list ap;
8179       //      va_start(ap, fmt);
8180       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
8181       //      ...
8182       // }
8183       if (HasVAListArg) {
8184         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
8185           if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) {
8186             int PVIndex = PV->getFunctionScopeIndex() + 1;
8187             for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
8188               // adjust for implicit parameter
8189               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
8190                 if (MD->isInstance())
8191                   ++PVIndex;
8192               // We also check if the formats are compatible.
8193               // We can't pass a 'scanf' string to a 'printf' function.
8194               if (PVIndex == PVFormat->getFormatIdx() &&
8195                   Type == S.GetFormatStringType(PVFormat))
8196                 return SLCT_UncheckedLiteral;
8197             }
8198           }
8199         }
8200       }
8201     }
8202 
8203     return SLCT_NotALiteral;
8204   }
8205 
8206   case Stmt::CallExprClass:
8207   case Stmt::CXXMemberCallExprClass: {
8208     const CallExpr *CE = cast<CallExpr>(E);
8209     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
8210       bool IsFirst = true;
8211       StringLiteralCheckType CommonResult;
8212       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
8213         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
8214         StringLiteralCheckType Result = checkFormatStringExpr(
8215             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8216             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8217             IgnoreStringsWithoutSpecifiers);
8218         if (IsFirst) {
8219           CommonResult = Result;
8220           IsFirst = false;
8221         }
8222       }
8223       if (!IsFirst)
8224         return CommonResult;
8225 
8226       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
8227         unsigned BuiltinID = FD->getBuiltinID();
8228         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
8229             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
8230           const Expr *Arg = CE->getArg(0);
8231           return checkFormatStringExpr(S, Arg, Args,
8232                                        HasVAListArg, format_idx,
8233                                        firstDataArg, Type, CallType,
8234                                        InFunctionCall, CheckedVarArgs,
8235                                        UncoveredArg, Offset,
8236                                        IgnoreStringsWithoutSpecifiers);
8237         }
8238       }
8239     }
8240 
8241     return SLCT_NotALiteral;
8242   }
8243   case Stmt::ObjCMessageExprClass: {
8244     const auto *ME = cast<ObjCMessageExpr>(E);
8245     if (const auto *MD = ME->getMethodDecl()) {
8246       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
8247         // As a special case heuristic, if we're using the method -[NSBundle
8248         // localizedStringForKey:value:table:], ignore any key strings that lack
8249         // format specifiers. The idea is that if the key doesn't have any
8250         // format specifiers then its probably just a key to map to the
8251         // localized strings. If it does have format specifiers though, then its
8252         // likely that the text of the key is the format string in the
8253         // programmer's language, and should be checked.
8254         const ObjCInterfaceDecl *IFace;
8255         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
8256             IFace->getIdentifier()->isStr("NSBundle") &&
8257             MD->getSelector().isKeywordSelector(
8258                 {"localizedStringForKey", "value", "table"})) {
8259           IgnoreStringsWithoutSpecifiers = true;
8260         }
8261 
8262         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
8263         return checkFormatStringExpr(
8264             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8265             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8266             IgnoreStringsWithoutSpecifiers);
8267       }
8268     }
8269 
8270     return SLCT_NotALiteral;
8271   }
8272   case Stmt::ObjCStringLiteralClass:
8273   case Stmt::StringLiteralClass: {
8274     const StringLiteral *StrE = nullptr;
8275 
8276     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
8277       StrE = ObjCFExpr->getString();
8278     else
8279       StrE = cast<StringLiteral>(E);
8280 
8281     if (StrE) {
8282       if (Offset.isNegative() || Offset > StrE->getLength()) {
8283         // TODO: It would be better to have an explicit warning for out of
8284         // bounds literals.
8285         return SLCT_NotALiteral;
8286       }
8287       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
8288       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
8289                         firstDataArg, Type, InFunctionCall, CallType,
8290                         CheckedVarArgs, UncoveredArg,
8291                         IgnoreStringsWithoutSpecifiers);
8292       return SLCT_CheckedLiteral;
8293     }
8294 
8295     return SLCT_NotALiteral;
8296   }
8297   case Stmt::BinaryOperatorClass: {
8298     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
8299 
8300     // A string literal + an int offset is still a string literal.
8301     if (BinOp->isAdditiveOp()) {
8302       Expr::EvalResult LResult, RResult;
8303 
8304       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
8305           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8306       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
8307           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8308 
8309       if (LIsInt != RIsInt) {
8310         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
8311 
8312         if (LIsInt) {
8313           if (BinOpKind == BO_Add) {
8314             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
8315             E = BinOp->getRHS();
8316             goto tryAgain;
8317           }
8318         } else {
8319           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
8320           E = BinOp->getLHS();
8321           goto tryAgain;
8322         }
8323       }
8324     }
8325 
8326     return SLCT_NotALiteral;
8327   }
8328   case Stmt::UnaryOperatorClass: {
8329     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
8330     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
8331     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
8332       Expr::EvalResult IndexResult;
8333       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
8334                                        Expr::SE_NoSideEffects,
8335                                        S.isConstantEvaluated())) {
8336         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
8337                    /*RHS is int*/ true);
8338         E = ASE->getBase();
8339         goto tryAgain;
8340       }
8341     }
8342 
8343     return SLCT_NotALiteral;
8344   }
8345 
8346   default:
8347     return SLCT_NotALiteral;
8348   }
8349 }
8350 
8351 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
8352   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
8353       .Case("scanf", FST_Scanf)
8354       .Cases("printf", "printf0", FST_Printf)
8355       .Cases("NSString", "CFString", FST_NSString)
8356       .Case("strftime", FST_Strftime)
8357       .Case("strfmon", FST_Strfmon)
8358       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
8359       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
8360       .Case("os_trace", FST_OSLog)
8361       .Case("os_log", FST_OSLog)
8362       .Default(FST_Unknown);
8363 }
8364 
8365 /// CheckFormatArguments - Check calls to printf and scanf (and similar
8366 /// functions) for correct use of format strings.
8367 /// Returns true if a format string has been fully checked.
8368 bool Sema::CheckFormatArguments(const FormatAttr *Format,
8369                                 ArrayRef<const Expr *> Args,
8370                                 bool IsCXXMember,
8371                                 VariadicCallType CallType,
8372                                 SourceLocation Loc, SourceRange Range,
8373                                 llvm::SmallBitVector &CheckedVarArgs) {
8374   FormatStringInfo FSI;
8375   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
8376     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
8377                                 FSI.FirstDataArg, GetFormatStringType(Format),
8378                                 CallType, Loc, Range, CheckedVarArgs);
8379   return false;
8380 }
8381 
8382 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8383                                 bool HasVAListArg, unsigned format_idx,
8384                                 unsigned firstDataArg, FormatStringType Type,
8385                                 VariadicCallType CallType,
8386                                 SourceLocation Loc, SourceRange Range,
8387                                 llvm::SmallBitVector &CheckedVarArgs) {
8388   // CHECK: printf/scanf-like function is called with no format string.
8389   if (format_idx >= Args.size()) {
8390     Diag(Loc, diag::warn_missing_format_string) << Range;
8391     return false;
8392   }
8393 
8394   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8395 
8396   // CHECK: format string is not a string literal.
8397   //
8398   // Dynamically generated format strings are difficult to
8399   // automatically vet at compile time.  Requiring that format strings
8400   // are string literals: (1) permits the checking of format strings by
8401   // the compiler and thereby (2) can practically remove the source of
8402   // many format string exploits.
8403 
8404   // Format string can be either ObjC string (e.g. @"%d") or
8405   // C string (e.g. "%d")
8406   // ObjC string uses the same format specifiers as C string, so we can use
8407   // the same format string checking logic for both ObjC and C strings.
8408   UncoveredArgHandler UncoveredArg;
8409   StringLiteralCheckType CT =
8410       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8411                             format_idx, firstDataArg, Type, CallType,
8412                             /*IsFunctionCall*/ true, CheckedVarArgs,
8413                             UncoveredArg,
8414                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8415 
8416   // Generate a diagnostic where an uncovered argument is detected.
8417   if (UncoveredArg.hasUncoveredArg()) {
8418     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8419     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8420     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8421   }
8422 
8423   if (CT != SLCT_NotALiteral)
8424     // Literal format string found, check done!
8425     return CT == SLCT_CheckedLiteral;
8426 
8427   // Strftime is particular as it always uses a single 'time' argument,
8428   // so it is safe to pass a non-literal string.
8429   if (Type == FST_Strftime)
8430     return false;
8431 
8432   // Do not emit diag when the string param is a macro expansion and the
8433   // format is either NSString or CFString. This is a hack to prevent
8434   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8435   // which are usually used in place of NS and CF string literals.
8436   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8437   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8438     return false;
8439 
8440   // If there are no arguments specified, warn with -Wformat-security, otherwise
8441   // warn only with -Wformat-nonliteral.
8442   if (Args.size() == firstDataArg) {
8443     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8444       << OrigFormatExpr->getSourceRange();
8445     switch (Type) {
8446     default:
8447       break;
8448     case FST_Kprintf:
8449     case FST_FreeBSDKPrintf:
8450     case FST_Printf:
8451       Diag(FormatLoc, diag::note_format_security_fixit)
8452         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8453       break;
8454     case FST_NSString:
8455       Diag(FormatLoc, diag::note_format_security_fixit)
8456         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8457       break;
8458     }
8459   } else {
8460     Diag(FormatLoc, diag::warn_format_nonliteral)
8461       << OrigFormatExpr->getSourceRange();
8462   }
8463   return false;
8464 }
8465 
8466 namespace {
8467 
8468 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8469 protected:
8470   Sema &S;
8471   const FormatStringLiteral *FExpr;
8472   const Expr *OrigFormatExpr;
8473   const Sema::FormatStringType FSType;
8474   const unsigned FirstDataArg;
8475   const unsigned NumDataArgs;
8476   const char *Beg; // Start of format string.
8477   const bool HasVAListArg;
8478   ArrayRef<const Expr *> Args;
8479   unsigned FormatIdx;
8480   llvm::SmallBitVector CoveredArgs;
8481   bool usesPositionalArgs = false;
8482   bool atFirstArg = true;
8483   bool inFunctionCall;
8484   Sema::VariadicCallType CallType;
8485   llvm::SmallBitVector &CheckedVarArgs;
8486   UncoveredArgHandler &UncoveredArg;
8487 
8488 public:
8489   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8490                      const Expr *origFormatExpr,
8491                      const Sema::FormatStringType type, unsigned firstDataArg,
8492                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8493                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8494                      bool inFunctionCall, Sema::VariadicCallType callType,
8495                      llvm::SmallBitVector &CheckedVarArgs,
8496                      UncoveredArgHandler &UncoveredArg)
8497       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8498         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8499         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8500         inFunctionCall(inFunctionCall), CallType(callType),
8501         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8502     CoveredArgs.resize(numDataArgs);
8503     CoveredArgs.reset();
8504   }
8505 
8506   void DoneProcessing();
8507 
8508   void HandleIncompleteSpecifier(const char *startSpecifier,
8509                                  unsigned specifierLen) override;
8510 
8511   void HandleInvalidLengthModifier(
8512                            const analyze_format_string::FormatSpecifier &FS,
8513                            const analyze_format_string::ConversionSpecifier &CS,
8514                            const char *startSpecifier, unsigned specifierLen,
8515                            unsigned DiagID);
8516 
8517   void HandleNonStandardLengthModifier(
8518                     const analyze_format_string::FormatSpecifier &FS,
8519                     const char *startSpecifier, unsigned specifierLen);
8520 
8521   void HandleNonStandardConversionSpecifier(
8522                     const analyze_format_string::ConversionSpecifier &CS,
8523                     const char *startSpecifier, unsigned specifierLen);
8524 
8525   void HandlePosition(const char *startPos, unsigned posLen) override;
8526 
8527   void HandleInvalidPosition(const char *startSpecifier,
8528                              unsigned specifierLen,
8529                              analyze_format_string::PositionContext p) override;
8530 
8531   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8532 
8533   void HandleNullChar(const char *nullCharacter) override;
8534 
8535   template <typename Range>
8536   static void
8537   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8538                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8539                        bool IsStringLocation, Range StringRange,
8540                        ArrayRef<FixItHint> Fixit = None);
8541 
8542 protected:
8543   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8544                                         const char *startSpec,
8545                                         unsigned specifierLen,
8546                                         const char *csStart, unsigned csLen);
8547 
8548   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8549                                          const char *startSpec,
8550                                          unsigned specifierLen);
8551 
8552   SourceRange getFormatStringRange();
8553   CharSourceRange getSpecifierRange(const char *startSpecifier,
8554                                     unsigned specifierLen);
8555   SourceLocation getLocationOfByte(const char *x);
8556 
8557   const Expr *getDataArg(unsigned i) const;
8558 
8559   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8560                     const analyze_format_string::ConversionSpecifier &CS,
8561                     const char *startSpecifier, unsigned specifierLen,
8562                     unsigned argIndex);
8563 
8564   template <typename Range>
8565   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8566                             bool IsStringLocation, Range StringRange,
8567                             ArrayRef<FixItHint> Fixit = None);
8568 };
8569 
8570 } // namespace
8571 
8572 SourceRange CheckFormatHandler::getFormatStringRange() {
8573   return OrigFormatExpr->getSourceRange();
8574 }
8575 
8576 CharSourceRange CheckFormatHandler::
8577 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8578   SourceLocation Start = getLocationOfByte(startSpecifier);
8579   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8580 
8581   // Advance the end SourceLocation by one due to half-open ranges.
8582   End = End.getLocWithOffset(1);
8583 
8584   return CharSourceRange::getCharRange(Start, End);
8585 }
8586 
8587 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8588   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8589                                   S.getLangOpts(), S.Context.getTargetInfo());
8590 }
8591 
8592 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8593                                                    unsigned specifierLen){
8594   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8595                        getLocationOfByte(startSpecifier),
8596                        /*IsStringLocation*/true,
8597                        getSpecifierRange(startSpecifier, specifierLen));
8598 }
8599 
8600 void CheckFormatHandler::HandleInvalidLengthModifier(
8601     const analyze_format_string::FormatSpecifier &FS,
8602     const analyze_format_string::ConversionSpecifier &CS,
8603     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8604   using namespace analyze_format_string;
8605 
8606   const LengthModifier &LM = FS.getLengthModifier();
8607   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8608 
8609   // See if we know how to fix this length modifier.
8610   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8611   if (FixedLM) {
8612     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8613                          getLocationOfByte(LM.getStart()),
8614                          /*IsStringLocation*/true,
8615                          getSpecifierRange(startSpecifier, specifierLen));
8616 
8617     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8618       << FixedLM->toString()
8619       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8620 
8621   } else {
8622     FixItHint Hint;
8623     if (DiagID == diag::warn_format_nonsensical_length)
8624       Hint = FixItHint::CreateRemoval(LMRange);
8625 
8626     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8627                          getLocationOfByte(LM.getStart()),
8628                          /*IsStringLocation*/true,
8629                          getSpecifierRange(startSpecifier, specifierLen),
8630                          Hint);
8631   }
8632 }
8633 
8634 void CheckFormatHandler::HandleNonStandardLengthModifier(
8635     const analyze_format_string::FormatSpecifier &FS,
8636     const char *startSpecifier, unsigned specifierLen) {
8637   using namespace analyze_format_string;
8638 
8639   const LengthModifier &LM = FS.getLengthModifier();
8640   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8641 
8642   // See if we know how to fix this length modifier.
8643   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8644   if (FixedLM) {
8645     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8646                            << LM.toString() << 0,
8647                          getLocationOfByte(LM.getStart()),
8648                          /*IsStringLocation*/true,
8649                          getSpecifierRange(startSpecifier, specifierLen));
8650 
8651     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8652       << FixedLM->toString()
8653       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8654 
8655   } else {
8656     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8657                            << LM.toString() << 0,
8658                          getLocationOfByte(LM.getStart()),
8659                          /*IsStringLocation*/true,
8660                          getSpecifierRange(startSpecifier, specifierLen));
8661   }
8662 }
8663 
8664 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8665     const analyze_format_string::ConversionSpecifier &CS,
8666     const char *startSpecifier, unsigned specifierLen) {
8667   using namespace analyze_format_string;
8668 
8669   // See if we know how to fix this conversion specifier.
8670   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8671   if (FixedCS) {
8672     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8673                           << CS.toString() << /*conversion specifier*/1,
8674                          getLocationOfByte(CS.getStart()),
8675                          /*IsStringLocation*/true,
8676                          getSpecifierRange(startSpecifier, specifierLen));
8677 
8678     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8679     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8680       << FixedCS->toString()
8681       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8682   } else {
8683     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8684                           << CS.toString() << /*conversion specifier*/1,
8685                          getLocationOfByte(CS.getStart()),
8686                          /*IsStringLocation*/true,
8687                          getSpecifierRange(startSpecifier, specifierLen));
8688   }
8689 }
8690 
8691 void CheckFormatHandler::HandlePosition(const char *startPos,
8692                                         unsigned posLen) {
8693   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8694                                getLocationOfByte(startPos),
8695                                /*IsStringLocation*/true,
8696                                getSpecifierRange(startPos, posLen));
8697 }
8698 
8699 void
8700 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8701                                      analyze_format_string::PositionContext p) {
8702   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8703                          << (unsigned) p,
8704                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8705                        getSpecifierRange(startPos, posLen));
8706 }
8707 
8708 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8709                                             unsigned posLen) {
8710   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8711                                getLocationOfByte(startPos),
8712                                /*IsStringLocation*/true,
8713                                getSpecifierRange(startPos, posLen));
8714 }
8715 
8716 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8717   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8718     // The presence of a null character is likely an error.
8719     EmitFormatDiagnostic(
8720       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8721       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8722       getFormatStringRange());
8723   }
8724 }
8725 
8726 // Note that this may return NULL if there was an error parsing or building
8727 // one of the argument expressions.
8728 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8729   return Args[FirstDataArg + i];
8730 }
8731 
8732 void CheckFormatHandler::DoneProcessing() {
8733   // Does the number of data arguments exceed the number of
8734   // format conversions in the format string?
8735   if (!HasVAListArg) {
8736       // Find any arguments that weren't covered.
8737     CoveredArgs.flip();
8738     signed notCoveredArg = CoveredArgs.find_first();
8739     if (notCoveredArg >= 0) {
8740       assert((unsigned)notCoveredArg < NumDataArgs);
8741       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8742     } else {
8743       UncoveredArg.setAllCovered();
8744     }
8745   }
8746 }
8747 
8748 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8749                                    const Expr *ArgExpr) {
8750   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8751          "Invalid state");
8752 
8753   if (!ArgExpr)
8754     return;
8755 
8756   SourceLocation Loc = ArgExpr->getBeginLoc();
8757 
8758   if (S.getSourceManager().isInSystemMacro(Loc))
8759     return;
8760 
8761   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8762   for (auto E : DiagnosticExprs)
8763     PDiag << E->getSourceRange();
8764 
8765   CheckFormatHandler::EmitFormatDiagnostic(
8766                                   S, IsFunctionCall, DiagnosticExprs[0],
8767                                   PDiag, Loc, /*IsStringLocation*/false,
8768                                   DiagnosticExprs[0]->getSourceRange());
8769 }
8770 
8771 bool
8772 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8773                                                      SourceLocation Loc,
8774                                                      const char *startSpec,
8775                                                      unsigned specifierLen,
8776                                                      const char *csStart,
8777                                                      unsigned csLen) {
8778   bool keepGoing = true;
8779   if (argIndex < NumDataArgs) {
8780     // Consider the argument coverered, even though the specifier doesn't
8781     // make sense.
8782     CoveredArgs.set(argIndex);
8783   }
8784   else {
8785     // If argIndex exceeds the number of data arguments we
8786     // don't issue a warning because that is just a cascade of warnings (and
8787     // they may have intended '%%' anyway). We don't want to continue processing
8788     // the format string after this point, however, as we will like just get
8789     // gibberish when trying to match arguments.
8790     keepGoing = false;
8791   }
8792 
8793   StringRef Specifier(csStart, csLen);
8794 
8795   // If the specifier in non-printable, it could be the first byte of a UTF-8
8796   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8797   // hex value.
8798   std::string CodePointStr;
8799   if (!llvm::sys::locale::isPrint(*csStart)) {
8800     llvm::UTF32 CodePoint;
8801     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8802     const llvm::UTF8 *E =
8803         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8804     llvm::ConversionResult Result =
8805         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8806 
8807     if (Result != llvm::conversionOK) {
8808       unsigned char FirstChar = *csStart;
8809       CodePoint = (llvm::UTF32)FirstChar;
8810     }
8811 
8812     llvm::raw_string_ostream OS(CodePointStr);
8813     if (CodePoint < 256)
8814       OS << "\\x" << llvm::format("%02x", CodePoint);
8815     else if (CodePoint <= 0xFFFF)
8816       OS << "\\u" << llvm::format("%04x", CodePoint);
8817     else
8818       OS << "\\U" << llvm::format("%08x", CodePoint);
8819     OS.flush();
8820     Specifier = CodePointStr;
8821   }
8822 
8823   EmitFormatDiagnostic(
8824       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8825       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8826 
8827   return keepGoing;
8828 }
8829 
8830 void
8831 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8832                                                       const char *startSpec,
8833                                                       unsigned specifierLen) {
8834   EmitFormatDiagnostic(
8835     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8836     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8837 }
8838 
8839 bool
8840 CheckFormatHandler::CheckNumArgs(
8841   const analyze_format_string::FormatSpecifier &FS,
8842   const analyze_format_string::ConversionSpecifier &CS,
8843   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8844 
8845   if (argIndex >= NumDataArgs) {
8846     PartialDiagnostic PDiag = FS.usesPositionalArg()
8847       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8848            << (argIndex+1) << NumDataArgs)
8849       : S.PDiag(diag::warn_printf_insufficient_data_args);
8850     EmitFormatDiagnostic(
8851       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8852       getSpecifierRange(startSpecifier, specifierLen));
8853 
8854     // Since more arguments than conversion tokens are given, by extension
8855     // all arguments are covered, so mark this as so.
8856     UncoveredArg.setAllCovered();
8857     return false;
8858   }
8859   return true;
8860 }
8861 
8862 template<typename Range>
8863 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8864                                               SourceLocation Loc,
8865                                               bool IsStringLocation,
8866                                               Range StringRange,
8867                                               ArrayRef<FixItHint> FixIt) {
8868   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8869                        Loc, IsStringLocation, StringRange, FixIt);
8870 }
8871 
8872 /// If the format string is not within the function call, emit a note
8873 /// so that the function call and string are in diagnostic messages.
8874 ///
8875 /// \param InFunctionCall if true, the format string is within the function
8876 /// call and only one diagnostic message will be produced.  Otherwise, an
8877 /// extra note will be emitted pointing to location of the format string.
8878 ///
8879 /// \param ArgumentExpr the expression that is passed as the format string
8880 /// argument in the function call.  Used for getting locations when two
8881 /// diagnostics are emitted.
8882 ///
8883 /// \param PDiag the callee should already have provided any strings for the
8884 /// diagnostic message.  This function only adds locations and fixits
8885 /// to diagnostics.
8886 ///
8887 /// \param Loc primary location for diagnostic.  If two diagnostics are
8888 /// required, one will be at Loc and a new SourceLocation will be created for
8889 /// the other one.
8890 ///
8891 /// \param IsStringLocation if true, Loc points to the format string should be
8892 /// used for the note.  Otherwise, Loc points to the argument list and will
8893 /// be used with PDiag.
8894 ///
8895 /// \param StringRange some or all of the string to highlight.  This is
8896 /// templated so it can accept either a CharSourceRange or a SourceRange.
8897 ///
8898 /// \param FixIt optional fix it hint for the format string.
8899 template <typename Range>
8900 void CheckFormatHandler::EmitFormatDiagnostic(
8901     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8902     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8903     Range StringRange, ArrayRef<FixItHint> FixIt) {
8904   if (InFunctionCall) {
8905     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8906     D << StringRange;
8907     D << FixIt;
8908   } else {
8909     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8910       << ArgumentExpr->getSourceRange();
8911 
8912     const Sema::SemaDiagnosticBuilder &Note =
8913       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8914              diag::note_format_string_defined);
8915 
8916     Note << StringRange;
8917     Note << FixIt;
8918   }
8919 }
8920 
8921 //===--- CHECK: Printf format string checking ------------------------------===//
8922 
8923 namespace {
8924 
8925 class CheckPrintfHandler : public CheckFormatHandler {
8926 public:
8927   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8928                      const Expr *origFormatExpr,
8929                      const Sema::FormatStringType type, unsigned firstDataArg,
8930                      unsigned numDataArgs, bool isObjC, const char *beg,
8931                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8932                      unsigned formatIdx, bool inFunctionCall,
8933                      Sema::VariadicCallType CallType,
8934                      llvm::SmallBitVector &CheckedVarArgs,
8935                      UncoveredArgHandler &UncoveredArg)
8936       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8937                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8938                            inFunctionCall, CallType, CheckedVarArgs,
8939                            UncoveredArg) {}
8940 
8941   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8942 
8943   /// Returns true if '%@' specifiers are allowed in the format string.
8944   bool allowsObjCArg() const {
8945     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8946            FSType == Sema::FST_OSTrace;
8947   }
8948 
8949   bool HandleInvalidPrintfConversionSpecifier(
8950                                       const analyze_printf::PrintfSpecifier &FS,
8951                                       const char *startSpecifier,
8952                                       unsigned specifierLen) override;
8953 
8954   void handleInvalidMaskType(StringRef MaskType) override;
8955 
8956   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8957                              const char *startSpecifier, unsigned specifierLen,
8958                              const TargetInfo &Target) override;
8959   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8960                        const char *StartSpecifier,
8961                        unsigned SpecifierLen,
8962                        const Expr *E);
8963 
8964   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8965                     const char *startSpecifier, unsigned specifierLen);
8966   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8967                            const analyze_printf::OptionalAmount &Amt,
8968                            unsigned type,
8969                            const char *startSpecifier, unsigned specifierLen);
8970   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8971                   const analyze_printf::OptionalFlag &flag,
8972                   const char *startSpecifier, unsigned specifierLen);
8973   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8974                          const analyze_printf::OptionalFlag &ignoredFlag,
8975                          const analyze_printf::OptionalFlag &flag,
8976                          const char *startSpecifier, unsigned specifierLen);
8977   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8978                            const Expr *E);
8979 
8980   void HandleEmptyObjCModifierFlag(const char *startFlag,
8981                                    unsigned flagLen) override;
8982 
8983   void HandleInvalidObjCModifierFlag(const char *startFlag,
8984                                             unsigned flagLen) override;
8985 
8986   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8987                                            const char *flagsEnd,
8988                                            const char *conversionPosition)
8989                                              override;
8990 };
8991 
8992 } // namespace
8993 
8994 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8995                                       const analyze_printf::PrintfSpecifier &FS,
8996                                       const char *startSpecifier,
8997                                       unsigned specifierLen) {
8998   const analyze_printf::PrintfConversionSpecifier &CS =
8999     FS.getConversionSpecifier();
9000 
9001   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9002                                           getLocationOfByte(CS.getStart()),
9003                                           startSpecifier, specifierLen,
9004                                           CS.getStart(), CS.getLength());
9005 }
9006 
9007 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
9008   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
9009 }
9010 
9011 bool CheckPrintfHandler::HandleAmount(
9012                                const analyze_format_string::OptionalAmount &Amt,
9013                                unsigned k, const char *startSpecifier,
9014                                unsigned specifierLen) {
9015   if (Amt.hasDataArgument()) {
9016     if (!HasVAListArg) {
9017       unsigned argIndex = Amt.getArgIndex();
9018       if (argIndex >= NumDataArgs) {
9019         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
9020                                << k,
9021                              getLocationOfByte(Amt.getStart()),
9022                              /*IsStringLocation*/true,
9023                              getSpecifierRange(startSpecifier, specifierLen));
9024         // Don't do any more checking.  We will just emit
9025         // spurious errors.
9026         return false;
9027       }
9028 
9029       // Type check the data argument.  It should be an 'int'.
9030       // Although not in conformance with C99, we also allow the argument to be
9031       // an 'unsigned int' as that is a reasonably safe case.  GCC also
9032       // doesn't emit a warning for that case.
9033       CoveredArgs.set(argIndex);
9034       const Expr *Arg = getDataArg(argIndex);
9035       if (!Arg)
9036         return false;
9037 
9038       QualType T = Arg->getType();
9039 
9040       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
9041       assert(AT.isValid());
9042 
9043       if (!AT.matchesType(S.Context, T)) {
9044         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
9045                                << k << AT.getRepresentativeTypeName(S.Context)
9046                                << T << Arg->getSourceRange(),
9047                              getLocationOfByte(Amt.getStart()),
9048                              /*IsStringLocation*/true,
9049                              getSpecifierRange(startSpecifier, specifierLen));
9050         // Don't do any more checking.  We will just emit
9051         // spurious errors.
9052         return false;
9053       }
9054     }
9055   }
9056   return true;
9057 }
9058 
9059 void CheckPrintfHandler::HandleInvalidAmount(
9060                                       const analyze_printf::PrintfSpecifier &FS,
9061                                       const analyze_printf::OptionalAmount &Amt,
9062                                       unsigned type,
9063                                       const char *startSpecifier,
9064                                       unsigned specifierLen) {
9065   const analyze_printf::PrintfConversionSpecifier &CS =
9066     FS.getConversionSpecifier();
9067 
9068   FixItHint fixit =
9069     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
9070       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
9071                                  Amt.getConstantLength()))
9072       : FixItHint();
9073 
9074   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
9075                          << type << CS.toString(),
9076                        getLocationOfByte(Amt.getStart()),
9077                        /*IsStringLocation*/true,
9078                        getSpecifierRange(startSpecifier, specifierLen),
9079                        fixit);
9080 }
9081 
9082 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
9083                                     const analyze_printf::OptionalFlag &flag,
9084                                     const char *startSpecifier,
9085                                     unsigned specifierLen) {
9086   // Warn about pointless flag with a fixit removal.
9087   const analyze_printf::PrintfConversionSpecifier &CS =
9088     FS.getConversionSpecifier();
9089   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
9090                          << flag.toString() << CS.toString(),
9091                        getLocationOfByte(flag.getPosition()),
9092                        /*IsStringLocation*/true,
9093                        getSpecifierRange(startSpecifier, specifierLen),
9094                        FixItHint::CreateRemoval(
9095                          getSpecifierRange(flag.getPosition(), 1)));
9096 }
9097 
9098 void CheckPrintfHandler::HandleIgnoredFlag(
9099                                 const analyze_printf::PrintfSpecifier &FS,
9100                                 const analyze_printf::OptionalFlag &ignoredFlag,
9101                                 const analyze_printf::OptionalFlag &flag,
9102                                 const char *startSpecifier,
9103                                 unsigned specifierLen) {
9104   // Warn about ignored flag with a fixit removal.
9105   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
9106                          << ignoredFlag.toString() << flag.toString(),
9107                        getLocationOfByte(ignoredFlag.getPosition()),
9108                        /*IsStringLocation*/true,
9109                        getSpecifierRange(startSpecifier, specifierLen),
9110                        FixItHint::CreateRemoval(
9111                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
9112 }
9113 
9114 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
9115                                                      unsigned flagLen) {
9116   // Warn about an empty flag.
9117   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
9118                        getLocationOfByte(startFlag),
9119                        /*IsStringLocation*/true,
9120                        getSpecifierRange(startFlag, flagLen));
9121 }
9122 
9123 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
9124                                                        unsigned flagLen) {
9125   // Warn about an invalid flag.
9126   auto Range = getSpecifierRange(startFlag, flagLen);
9127   StringRef flag(startFlag, flagLen);
9128   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
9129                       getLocationOfByte(startFlag),
9130                       /*IsStringLocation*/true,
9131                       Range, FixItHint::CreateRemoval(Range));
9132 }
9133 
9134 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
9135     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
9136     // Warn about using '[...]' without a '@' conversion.
9137     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
9138     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
9139     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
9140                          getLocationOfByte(conversionPosition),
9141                          /*IsStringLocation*/true,
9142                          Range, FixItHint::CreateRemoval(Range));
9143 }
9144 
9145 // Determines if the specified is a C++ class or struct containing
9146 // a member with the specified name and kind (e.g. a CXXMethodDecl named
9147 // "c_str()").
9148 template<typename MemberKind>
9149 static llvm::SmallPtrSet<MemberKind*, 1>
9150 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9151   const RecordType *RT = Ty->getAs<RecordType>();
9152   llvm::SmallPtrSet<MemberKind*, 1> Results;
9153 
9154   if (!RT)
9155     return Results;
9156   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
9157   if (!RD || !RD->getDefinition())
9158     return Results;
9159 
9160   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9161                  Sema::LookupMemberName);
9162   R.suppressDiagnostics();
9163 
9164   // We just need to include all members of the right kind turned up by the
9165   // filter, at this point.
9166   if (S.LookupQualifiedName(R, RT->getDecl()))
9167     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9168       NamedDecl *decl = (*I)->getUnderlyingDecl();
9169       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9170         Results.insert(FK);
9171     }
9172   return Results;
9173 }
9174 
9175 /// Check if we could call '.c_str()' on an object.
9176 ///
9177 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9178 /// allow the call, or if it would be ambiguous).
9179 bool Sema::hasCStrMethod(const Expr *E) {
9180   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9181 
9182   MethodSet Results =
9183       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
9184   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9185        MI != ME; ++MI)
9186     if ((*MI)->getMinRequiredArguments() == 0)
9187       return true;
9188   return false;
9189 }
9190 
9191 // Check if a (w)string was passed when a (w)char* was needed, and offer a
9192 // better diagnostic if so. AT is assumed to be valid.
9193 // Returns true when a c_str() conversion method is found.
9194 bool CheckPrintfHandler::checkForCStrMembers(
9195     const analyze_printf::ArgType &AT, const Expr *E) {
9196   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9197 
9198   MethodSet Results =
9199       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
9200 
9201   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9202        MI != ME; ++MI) {
9203     const CXXMethodDecl *Method = *MI;
9204     if (Method->getMinRequiredArguments() == 0 &&
9205         AT.matchesType(S.Context, Method->getReturnType())) {
9206       // FIXME: Suggest parens if the expression needs them.
9207       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
9208       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
9209           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
9210       return true;
9211     }
9212   }
9213 
9214   return false;
9215 }
9216 
9217 bool CheckPrintfHandler::HandlePrintfSpecifier(
9218     const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9219     unsigned specifierLen, const TargetInfo &Target) {
9220   using namespace analyze_format_string;
9221   using namespace analyze_printf;
9222 
9223   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9224 
9225   if (FS.consumesDataArgument()) {
9226     if (atFirstArg) {
9227         atFirstArg = false;
9228         usesPositionalArgs = FS.usesPositionalArg();
9229     }
9230     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9231       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9232                                         startSpecifier, specifierLen);
9233       return false;
9234     }
9235   }
9236 
9237   // First check if the field width, precision, and conversion specifier
9238   // have matching data arguments.
9239   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
9240                     startSpecifier, specifierLen)) {
9241     return false;
9242   }
9243 
9244   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
9245                     startSpecifier, specifierLen)) {
9246     return false;
9247   }
9248 
9249   if (!CS.consumesDataArgument()) {
9250     // FIXME: Technically specifying a precision or field width here
9251     // makes no sense.  Worth issuing a warning at some point.
9252     return true;
9253   }
9254 
9255   // Consume the argument.
9256   unsigned argIndex = FS.getArgIndex();
9257   if (argIndex < NumDataArgs) {
9258     // The check to see if the argIndex is valid will come later.
9259     // We set the bit here because we may exit early from this
9260     // function if we encounter some other error.
9261     CoveredArgs.set(argIndex);
9262   }
9263 
9264   // FreeBSD kernel extensions.
9265   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9266       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9267     // We need at least two arguments.
9268     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9269       return false;
9270 
9271     // Claim the second argument.
9272     CoveredArgs.set(argIndex + 1);
9273 
9274     // Type check the first argument (int for %b, pointer for %D)
9275     const Expr *Ex = getDataArg(argIndex);
9276     const analyze_printf::ArgType &AT =
9277       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
9278         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
9279     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9280       EmitFormatDiagnostic(
9281           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9282               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9283               << false << Ex->getSourceRange(),
9284           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9285           getSpecifierRange(startSpecifier, specifierLen));
9286 
9287     // Type check the second argument (char * for both %b and %D)
9288     Ex = getDataArg(argIndex + 1);
9289     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
9290     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9291       EmitFormatDiagnostic(
9292           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9293               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9294               << false << Ex->getSourceRange(),
9295           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9296           getSpecifierRange(startSpecifier, specifierLen));
9297 
9298      return true;
9299   }
9300 
9301   // Check for using an Objective-C specific conversion specifier
9302   // in a non-ObjC literal.
9303   if (!allowsObjCArg() && CS.isObjCArg()) {
9304     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9305                                                   specifierLen);
9306   }
9307 
9308   // %P can only be used with os_log.
9309   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
9310     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9311                                                   specifierLen);
9312   }
9313 
9314   // %n is not allowed with os_log.
9315   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
9316     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9317                          getLocationOfByte(CS.getStart()),
9318                          /*IsStringLocation*/ false,
9319                          getSpecifierRange(startSpecifier, specifierLen));
9320 
9321     return true;
9322   }
9323 
9324   // Only scalars are allowed for os_trace.
9325   if (FSType == Sema::FST_OSTrace &&
9326       (CS.getKind() == ConversionSpecifier::PArg ||
9327        CS.getKind() == ConversionSpecifier::sArg ||
9328        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9329     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9330                                                   specifierLen);
9331   }
9332 
9333   // Check for use of public/private annotation outside of os_log().
9334   if (FSType != Sema::FST_OSLog) {
9335     if (FS.isPublic().isSet()) {
9336       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9337                                << "public",
9338                            getLocationOfByte(FS.isPublic().getPosition()),
9339                            /*IsStringLocation*/ false,
9340                            getSpecifierRange(startSpecifier, specifierLen));
9341     }
9342     if (FS.isPrivate().isSet()) {
9343       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9344                                << "private",
9345                            getLocationOfByte(FS.isPrivate().getPosition()),
9346                            /*IsStringLocation*/ false,
9347                            getSpecifierRange(startSpecifier, specifierLen));
9348     }
9349   }
9350 
9351   const llvm::Triple &Triple = Target.getTriple();
9352   if (CS.getKind() == ConversionSpecifier::nArg &&
9353       (Triple.isAndroid() || Triple.isOSFuchsia())) {
9354     EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
9355                          getLocationOfByte(CS.getStart()),
9356                          /*IsStringLocation*/ false,
9357                          getSpecifierRange(startSpecifier, specifierLen));
9358   }
9359 
9360   // Check for invalid use of field width
9361   if (!FS.hasValidFieldWidth()) {
9362     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9363         startSpecifier, specifierLen);
9364   }
9365 
9366   // Check for invalid use of precision
9367   if (!FS.hasValidPrecision()) {
9368     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9369         startSpecifier, specifierLen);
9370   }
9371 
9372   // Precision is mandatory for %P specifier.
9373   if (CS.getKind() == ConversionSpecifier::PArg &&
9374       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9375     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9376                          getLocationOfByte(startSpecifier),
9377                          /*IsStringLocation*/ false,
9378                          getSpecifierRange(startSpecifier, specifierLen));
9379   }
9380 
9381   // Check each flag does not conflict with any other component.
9382   if (!FS.hasValidThousandsGroupingPrefix())
9383     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9384   if (!FS.hasValidLeadingZeros())
9385     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9386   if (!FS.hasValidPlusPrefix())
9387     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9388   if (!FS.hasValidSpacePrefix())
9389     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9390   if (!FS.hasValidAlternativeForm())
9391     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9392   if (!FS.hasValidLeftJustified())
9393     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9394 
9395   // Check that flags are not ignored by another flag
9396   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9397     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9398         startSpecifier, specifierLen);
9399   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9400     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9401             startSpecifier, specifierLen);
9402 
9403   // Check the length modifier is valid with the given conversion specifier.
9404   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9405                                  S.getLangOpts()))
9406     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9407                                 diag::warn_format_nonsensical_length);
9408   else if (!FS.hasStandardLengthModifier())
9409     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9410   else if (!FS.hasStandardLengthConversionCombination())
9411     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9412                                 diag::warn_format_non_standard_conversion_spec);
9413 
9414   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9415     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9416 
9417   // The remaining checks depend on the data arguments.
9418   if (HasVAListArg)
9419     return true;
9420 
9421   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9422     return false;
9423 
9424   const Expr *Arg = getDataArg(argIndex);
9425   if (!Arg)
9426     return true;
9427 
9428   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9429 }
9430 
9431 static bool requiresParensToAddCast(const Expr *E) {
9432   // FIXME: We should have a general way to reason about operator
9433   // precedence and whether parens are actually needed here.
9434   // Take care of a few common cases where they aren't.
9435   const Expr *Inside = E->IgnoreImpCasts();
9436   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9437     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9438 
9439   switch (Inside->getStmtClass()) {
9440   case Stmt::ArraySubscriptExprClass:
9441   case Stmt::CallExprClass:
9442   case Stmt::CharacterLiteralClass:
9443   case Stmt::CXXBoolLiteralExprClass:
9444   case Stmt::DeclRefExprClass:
9445   case Stmt::FloatingLiteralClass:
9446   case Stmt::IntegerLiteralClass:
9447   case Stmt::MemberExprClass:
9448   case Stmt::ObjCArrayLiteralClass:
9449   case Stmt::ObjCBoolLiteralExprClass:
9450   case Stmt::ObjCBoxedExprClass:
9451   case Stmt::ObjCDictionaryLiteralClass:
9452   case Stmt::ObjCEncodeExprClass:
9453   case Stmt::ObjCIvarRefExprClass:
9454   case Stmt::ObjCMessageExprClass:
9455   case Stmt::ObjCPropertyRefExprClass:
9456   case Stmt::ObjCStringLiteralClass:
9457   case Stmt::ObjCSubscriptRefExprClass:
9458   case Stmt::ParenExprClass:
9459   case Stmt::StringLiteralClass:
9460   case Stmt::UnaryOperatorClass:
9461     return false;
9462   default:
9463     return true;
9464   }
9465 }
9466 
9467 static std::pair<QualType, StringRef>
9468 shouldNotPrintDirectly(const ASTContext &Context,
9469                        QualType IntendedTy,
9470                        const Expr *E) {
9471   // Use a 'while' to peel off layers of typedefs.
9472   QualType TyTy = IntendedTy;
9473   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9474     StringRef Name = UserTy->getDecl()->getName();
9475     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9476       .Case("CFIndex", Context.getNSIntegerType())
9477       .Case("NSInteger", Context.getNSIntegerType())
9478       .Case("NSUInteger", Context.getNSUIntegerType())
9479       .Case("SInt32", Context.IntTy)
9480       .Case("UInt32", Context.UnsignedIntTy)
9481       .Default(QualType());
9482 
9483     if (!CastTy.isNull())
9484       return std::make_pair(CastTy, Name);
9485 
9486     TyTy = UserTy->desugar();
9487   }
9488 
9489   // Strip parens if necessary.
9490   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9491     return shouldNotPrintDirectly(Context,
9492                                   PE->getSubExpr()->getType(),
9493                                   PE->getSubExpr());
9494 
9495   // If this is a conditional expression, then its result type is constructed
9496   // via usual arithmetic conversions and thus there might be no necessary
9497   // typedef sugar there.  Recurse to operands to check for NSInteger &
9498   // Co. usage condition.
9499   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9500     QualType TrueTy, FalseTy;
9501     StringRef TrueName, FalseName;
9502 
9503     std::tie(TrueTy, TrueName) =
9504       shouldNotPrintDirectly(Context,
9505                              CO->getTrueExpr()->getType(),
9506                              CO->getTrueExpr());
9507     std::tie(FalseTy, FalseName) =
9508       shouldNotPrintDirectly(Context,
9509                              CO->getFalseExpr()->getType(),
9510                              CO->getFalseExpr());
9511 
9512     if (TrueTy == FalseTy)
9513       return std::make_pair(TrueTy, TrueName);
9514     else if (TrueTy.isNull())
9515       return std::make_pair(FalseTy, FalseName);
9516     else if (FalseTy.isNull())
9517       return std::make_pair(TrueTy, TrueName);
9518   }
9519 
9520   return std::make_pair(QualType(), StringRef());
9521 }
9522 
9523 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9524 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9525 /// type do not count.
9526 static bool
9527 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9528   QualType From = ICE->getSubExpr()->getType();
9529   QualType To = ICE->getType();
9530   // It's an integer promotion if the destination type is the promoted
9531   // source type.
9532   if (ICE->getCastKind() == CK_IntegralCast &&
9533       From->isPromotableIntegerType() &&
9534       S.Context.getPromotedIntegerType(From) == To)
9535     return true;
9536   // Look through vector types, since we do default argument promotion for
9537   // those in OpenCL.
9538   if (const auto *VecTy = From->getAs<ExtVectorType>())
9539     From = VecTy->getElementType();
9540   if (const auto *VecTy = To->getAs<ExtVectorType>())
9541     To = VecTy->getElementType();
9542   // It's a floating promotion if the source type is a lower rank.
9543   return ICE->getCastKind() == CK_FloatingCast &&
9544          S.Context.getFloatingTypeOrder(From, To) < 0;
9545 }
9546 
9547 bool
9548 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9549                                     const char *StartSpecifier,
9550                                     unsigned SpecifierLen,
9551                                     const Expr *E) {
9552   using namespace analyze_format_string;
9553   using namespace analyze_printf;
9554 
9555   // Now type check the data expression that matches the
9556   // format specifier.
9557   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9558   if (!AT.isValid())
9559     return true;
9560 
9561   QualType ExprTy = E->getType();
9562   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9563     ExprTy = TET->getUnderlyingExpr()->getType();
9564   }
9565 
9566   // Diagnose attempts to print a boolean value as a character. Unlike other
9567   // -Wformat diagnostics, this is fine from a type perspective, but it still
9568   // doesn't make sense.
9569   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9570       E->isKnownToHaveBooleanValue()) {
9571     const CharSourceRange &CSR =
9572         getSpecifierRange(StartSpecifier, SpecifierLen);
9573     SmallString<4> FSString;
9574     llvm::raw_svector_ostream os(FSString);
9575     FS.toString(os);
9576     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9577                              << FSString,
9578                          E->getExprLoc(), false, CSR);
9579     return true;
9580   }
9581 
9582   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9583   if (Match == analyze_printf::ArgType::Match)
9584     return true;
9585 
9586   // Look through argument promotions for our error message's reported type.
9587   // This includes the integral and floating promotions, but excludes array
9588   // and function pointer decay (seeing that an argument intended to be a
9589   // string has type 'char [6]' is probably more confusing than 'char *') and
9590   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9591   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9592     if (isArithmeticArgumentPromotion(S, ICE)) {
9593       E = ICE->getSubExpr();
9594       ExprTy = E->getType();
9595 
9596       // Check if we didn't match because of an implicit cast from a 'char'
9597       // or 'short' to an 'int'.  This is done because printf is a varargs
9598       // function.
9599       if (ICE->getType() == S.Context.IntTy ||
9600           ICE->getType() == S.Context.UnsignedIntTy) {
9601         // All further checking is done on the subexpression
9602         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9603             AT.matchesType(S.Context, ExprTy);
9604         if (ImplicitMatch == analyze_printf::ArgType::Match)
9605           return true;
9606         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9607             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9608           Match = ImplicitMatch;
9609       }
9610     }
9611   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9612     // Special case for 'a', which has type 'int' in C.
9613     // Note, however, that we do /not/ want to treat multibyte constants like
9614     // 'MooV' as characters! This form is deprecated but still exists. In
9615     // addition, don't treat expressions as of type 'char' if one byte length
9616     // modifier is provided.
9617     if (ExprTy == S.Context.IntTy &&
9618         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9619       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9620         ExprTy = S.Context.CharTy;
9621   }
9622 
9623   // Look through enums to their underlying type.
9624   bool IsEnum = false;
9625   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9626     ExprTy = EnumTy->getDecl()->getIntegerType();
9627     IsEnum = true;
9628   }
9629 
9630   // %C in an Objective-C context prints a unichar, not a wchar_t.
9631   // If the argument is an integer of some kind, believe the %C and suggest
9632   // a cast instead of changing the conversion specifier.
9633   QualType IntendedTy = ExprTy;
9634   if (isObjCContext() &&
9635       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9636     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9637         !ExprTy->isCharType()) {
9638       // 'unichar' is defined as a typedef of unsigned short, but we should
9639       // prefer using the typedef if it is visible.
9640       IntendedTy = S.Context.UnsignedShortTy;
9641 
9642       // While we are here, check if the value is an IntegerLiteral that happens
9643       // to be within the valid range.
9644       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9645         const llvm::APInt &V = IL->getValue();
9646         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9647           return true;
9648       }
9649 
9650       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9651                           Sema::LookupOrdinaryName);
9652       if (S.LookupName(Result, S.getCurScope())) {
9653         NamedDecl *ND = Result.getFoundDecl();
9654         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9655           if (TD->getUnderlyingType() == IntendedTy)
9656             IntendedTy = S.Context.getTypedefType(TD);
9657       }
9658     }
9659   }
9660 
9661   // Special-case some of Darwin's platform-independence types by suggesting
9662   // casts to primitive types that are known to be large enough.
9663   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9664   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9665     QualType CastTy;
9666     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9667     if (!CastTy.isNull()) {
9668       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9669       // (long in ASTContext). Only complain to pedants.
9670       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9671           (AT.isSizeT() || AT.isPtrdiffT()) &&
9672           AT.matchesType(S.Context, CastTy))
9673         Match = ArgType::NoMatchPedantic;
9674       IntendedTy = CastTy;
9675       ShouldNotPrintDirectly = true;
9676     }
9677   }
9678 
9679   // We may be able to offer a FixItHint if it is a supported type.
9680   PrintfSpecifier fixedFS = FS;
9681   bool Success =
9682       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9683 
9684   if (Success) {
9685     // Get the fix string from the fixed format specifier
9686     SmallString<16> buf;
9687     llvm::raw_svector_ostream os(buf);
9688     fixedFS.toString(os);
9689 
9690     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9691 
9692     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9693       unsigned Diag;
9694       switch (Match) {
9695       case ArgType::Match: llvm_unreachable("expected non-matching");
9696       case ArgType::NoMatchPedantic:
9697         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9698         break;
9699       case ArgType::NoMatchTypeConfusion:
9700         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9701         break;
9702       case ArgType::NoMatch:
9703         Diag = diag::warn_format_conversion_argument_type_mismatch;
9704         break;
9705       }
9706 
9707       // In this case, the specifier is wrong and should be changed to match
9708       // the argument.
9709       EmitFormatDiagnostic(S.PDiag(Diag)
9710                                << AT.getRepresentativeTypeName(S.Context)
9711                                << IntendedTy << IsEnum << E->getSourceRange(),
9712                            E->getBeginLoc(),
9713                            /*IsStringLocation*/ false, SpecRange,
9714                            FixItHint::CreateReplacement(SpecRange, os.str()));
9715     } else {
9716       // The canonical type for formatting this value is different from the
9717       // actual type of the expression. (This occurs, for example, with Darwin's
9718       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9719       // should be printed as 'long' for 64-bit compatibility.)
9720       // Rather than emitting a normal format/argument mismatch, we want to
9721       // add a cast to the recommended type (and correct the format string
9722       // if necessary).
9723       SmallString<16> CastBuf;
9724       llvm::raw_svector_ostream CastFix(CastBuf);
9725       CastFix << "(";
9726       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9727       CastFix << ")";
9728 
9729       SmallVector<FixItHint,4> Hints;
9730       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9731         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9732 
9733       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9734         // If there's already a cast present, just replace it.
9735         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9736         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9737 
9738       } else if (!requiresParensToAddCast(E)) {
9739         // If the expression has high enough precedence,
9740         // just write the C-style cast.
9741         Hints.push_back(
9742             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9743       } else {
9744         // Otherwise, add parens around the expression as well as the cast.
9745         CastFix << "(";
9746         Hints.push_back(
9747             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9748 
9749         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9750         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9751       }
9752 
9753       if (ShouldNotPrintDirectly) {
9754         // The expression has a type that should not be printed directly.
9755         // We extract the name from the typedef because we don't want to show
9756         // the underlying type in the diagnostic.
9757         StringRef Name;
9758         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9759           Name = TypedefTy->getDecl()->getName();
9760         else
9761           Name = CastTyName;
9762         unsigned Diag = Match == ArgType::NoMatchPedantic
9763                             ? diag::warn_format_argument_needs_cast_pedantic
9764                             : diag::warn_format_argument_needs_cast;
9765         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9766                                            << E->getSourceRange(),
9767                              E->getBeginLoc(), /*IsStringLocation=*/false,
9768                              SpecRange, Hints);
9769       } else {
9770         // In this case, the expression could be printed using a different
9771         // specifier, but we've decided that the specifier is probably correct
9772         // and we should cast instead. Just use the normal warning message.
9773         EmitFormatDiagnostic(
9774             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9775                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9776                 << E->getSourceRange(),
9777             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9778       }
9779     }
9780   } else {
9781     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9782                                                    SpecifierLen);
9783     // Since the warning for passing non-POD types to variadic functions
9784     // was deferred until now, we emit a warning for non-POD
9785     // arguments here.
9786     switch (S.isValidVarArgType(ExprTy)) {
9787     case Sema::VAK_Valid:
9788     case Sema::VAK_ValidInCXX11: {
9789       unsigned Diag;
9790       switch (Match) {
9791       case ArgType::Match: llvm_unreachable("expected non-matching");
9792       case ArgType::NoMatchPedantic:
9793         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9794         break;
9795       case ArgType::NoMatchTypeConfusion:
9796         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9797         break;
9798       case ArgType::NoMatch:
9799         Diag = diag::warn_format_conversion_argument_type_mismatch;
9800         break;
9801       }
9802 
9803       EmitFormatDiagnostic(
9804           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9805                         << IsEnum << CSR << E->getSourceRange(),
9806           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9807       break;
9808     }
9809     case Sema::VAK_Undefined:
9810     case Sema::VAK_MSVCUndefined:
9811       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9812                                << S.getLangOpts().CPlusPlus11 << ExprTy
9813                                << CallType
9814                                << AT.getRepresentativeTypeName(S.Context) << CSR
9815                                << E->getSourceRange(),
9816                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9817       checkForCStrMembers(AT, E);
9818       break;
9819 
9820     case Sema::VAK_Invalid:
9821       if (ExprTy->isObjCObjectType())
9822         EmitFormatDiagnostic(
9823             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9824                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9825                 << AT.getRepresentativeTypeName(S.Context) << CSR
9826                 << E->getSourceRange(),
9827             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9828       else
9829         // FIXME: If this is an initializer list, suggest removing the braces
9830         // or inserting a cast to the target type.
9831         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9832             << isa<InitListExpr>(E) << ExprTy << CallType
9833             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9834       break;
9835     }
9836 
9837     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9838            "format string specifier index out of range");
9839     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9840   }
9841 
9842   return true;
9843 }
9844 
9845 //===--- CHECK: Scanf format string checking ------------------------------===//
9846 
9847 namespace {
9848 
9849 class CheckScanfHandler : public CheckFormatHandler {
9850 public:
9851   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9852                     const Expr *origFormatExpr, Sema::FormatStringType type,
9853                     unsigned firstDataArg, unsigned numDataArgs,
9854                     const char *beg, bool hasVAListArg,
9855                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9856                     bool inFunctionCall, Sema::VariadicCallType CallType,
9857                     llvm::SmallBitVector &CheckedVarArgs,
9858                     UncoveredArgHandler &UncoveredArg)
9859       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9860                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9861                            inFunctionCall, CallType, CheckedVarArgs,
9862                            UncoveredArg) {}
9863 
9864   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9865                             const char *startSpecifier,
9866                             unsigned specifierLen) override;
9867 
9868   bool HandleInvalidScanfConversionSpecifier(
9869           const analyze_scanf::ScanfSpecifier &FS,
9870           const char *startSpecifier,
9871           unsigned specifierLen) override;
9872 
9873   void HandleIncompleteScanList(const char *start, const char *end) override;
9874 };
9875 
9876 } // namespace
9877 
9878 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9879                                                  const char *end) {
9880   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9881                        getLocationOfByte(end), /*IsStringLocation*/true,
9882                        getSpecifierRange(start, end - start));
9883 }
9884 
9885 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9886                                         const analyze_scanf::ScanfSpecifier &FS,
9887                                         const char *startSpecifier,
9888                                         unsigned specifierLen) {
9889   const analyze_scanf::ScanfConversionSpecifier &CS =
9890     FS.getConversionSpecifier();
9891 
9892   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9893                                           getLocationOfByte(CS.getStart()),
9894                                           startSpecifier, specifierLen,
9895                                           CS.getStart(), CS.getLength());
9896 }
9897 
9898 bool CheckScanfHandler::HandleScanfSpecifier(
9899                                        const analyze_scanf::ScanfSpecifier &FS,
9900                                        const char *startSpecifier,
9901                                        unsigned specifierLen) {
9902   using namespace analyze_scanf;
9903   using namespace analyze_format_string;
9904 
9905   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9906 
9907   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9908   // be used to decide if we are using positional arguments consistently.
9909   if (FS.consumesDataArgument()) {
9910     if (atFirstArg) {
9911       atFirstArg = false;
9912       usesPositionalArgs = FS.usesPositionalArg();
9913     }
9914     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9915       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9916                                         startSpecifier, specifierLen);
9917       return false;
9918     }
9919   }
9920 
9921   // Check if the field with is non-zero.
9922   const OptionalAmount &Amt = FS.getFieldWidth();
9923   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9924     if (Amt.getConstantAmount() == 0) {
9925       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9926                                                    Amt.getConstantLength());
9927       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9928                            getLocationOfByte(Amt.getStart()),
9929                            /*IsStringLocation*/true, R,
9930                            FixItHint::CreateRemoval(R));
9931     }
9932   }
9933 
9934   if (!FS.consumesDataArgument()) {
9935     // FIXME: Technically specifying a precision or field width here
9936     // makes no sense.  Worth issuing a warning at some point.
9937     return true;
9938   }
9939 
9940   // Consume the argument.
9941   unsigned argIndex = FS.getArgIndex();
9942   if (argIndex < NumDataArgs) {
9943       // The check to see if the argIndex is valid will come later.
9944       // We set the bit here because we may exit early from this
9945       // function if we encounter some other error.
9946     CoveredArgs.set(argIndex);
9947   }
9948 
9949   // Check the length modifier is valid with the given conversion specifier.
9950   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9951                                  S.getLangOpts()))
9952     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9953                                 diag::warn_format_nonsensical_length);
9954   else if (!FS.hasStandardLengthModifier())
9955     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9956   else if (!FS.hasStandardLengthConversionCombination())
9957     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9958                                 diag::warn_format_non_standard_conversion_spec);
9959 
9960   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9961     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9962 
9963   // The remaining checks depend on the data arguments.
9964   if (HasVAListArg)
9965     return true;
9966 
9967   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9968     return false;
9969 
9970   // Check that the argument type matches the format specifier.
9971   const Expr *Ex = getDataArg(argIndex);
9972   if (!Ex)
9973     return true;
9974 
9975   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9976 
9977   if (!AT.isValid()) {
9978     return true;
9979   }
9980 
9981   analyze_format_string::ArgType::MatchKind Match =
9982       AT.matchesType(S.Context, Ex->getType());
9983   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9984   if (Match == analyze_format_string::ArgType::Match)
9985     return true;
9986 
9987   ScanfSpecifier fixedFS = FS;
9988   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9989                                  S.getLangOpts(), S.Context);
9990 
9991   unsigned Diag =
9992       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9993                : diag::warn_format_conversion_argument_type_mismatch;
9994 
9995   if (Success) {
9996     // Get the fix string from the fixed format specifier.
9997     SmallString<128> buf;
9998     llvm::raw_svector_ostream os(buf);
9999     fixedFS.toString(os);
10000 
10001     EmitFormatDiagnostic(
10002         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
10003                       << Ex->getType() << false << Ex->getSourceRange(),
10004         Ex->getBeginLoc(),
10005         /*IsStringLocation*/ false,
10006         getSpecifierRange(startSpecifier, specifierLen),
10007         FixItHint::CreateReplacement(
10008             getSpecifierRange(startSpecifier, specifierLen), os.str()));
10009   } else {
10010     EmitFormatDiagnostic(S.PDiag(Diag)
10011                              << AT.getRepresentativeTypeName(S.Context)
10012                              << Ex->getType() << false << Ex->getSourceRange(),
10013                          Ex->getBeginLoc(),
10014                          /*IsStringLocation*/ false,
10015                          getSpecifierRange(startSpecifier, specifierLen));
10016   }
10017 
10018   return true;
10019 }
10020 
10021 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
10022                               const Expr *OrigFormatExpr,
10023                               ArrayRef<const Expr *> Args,
10024                               bool HasVAListArg, unsigned format_idx,
10025                               unsigned firstDataArg,
10026                               Sema::FormatStringType Type,
10027                               bool inFunctionCall,
10028                               Sema::VariadicCallType CallType,
10029                               llvm::SmallBitVector &CheckedVarArgs,
10030                               UncoveredArgHandler &UncoveredArg,
10031                               bool IgnoreStringsWithoutSpecifiers) {
10032   // CHECK: is the format string a wide literal?
10033   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
10034     CheckFormatHandler::EmitFormatDiagnostic(
10035         S, inFunctionCall, Args[format_idx],
10036         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
10037         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10038     return;
10039   }
10040 
10041   // Str - The format string.  NOTE: this is NOT null-terminated!
10042   StringRef StrRef = FExpr->getString();
10043   const char *Str = StrRef.data();
10044   // Account for cases where the string literal is truncated in a declaration.
10045   const ConstantArrayType *T =
10046     S.Context.getAsConstantArrayType(FExpr->getType());
10047   assert(T && "String literal not of constant array type!");
10048   size_t TypeSize = T->getSize().getZExtValue();
10049   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10050   const unsigned numDataArgs = Args.size() - firstDataArg;
10051 
10052   if (IgnoreStringsWithoutSpecifiers &&
10053       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
10054           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10055     return;
10056 
10057   // Emit a warning if the string literal is truncated and does not contain an
10058   // embedded null character.
10059   if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
10060     CheckFormatHandler::EmitFormatDiagnostic(
10061         S, inFunctionCall, Args[format_idx],
10062         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
10063         FExpr->getBeginLoc(),
10064         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
10065     return;
10066   }
10067 
10068   // CHECK: empty format string?
10069   if (StrLen == 0 && numDataArgs > 0) {
10070     CheckFormatHandler::EmitFormatDiagnostic(
10071         S, inFunctionCall, Args[format_idx],
10072         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
10073         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10074     return;
10075   }
10076 
10077   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
10078       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
10079       Type == Sema::FST_OSTrace) {
10080     CheckPrintfHandler H(
10081         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
10082         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
10083         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
10084         CheckedVarArgs, UncoveredArg);
10085 
10086     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
10087                                                   S.getLangOpts(),
10088                                                   S.Context.getTargetInfo(),
10089                                             Type == Sema::FST_FreeBSDKPrintf))
10090       H.DoneProcessing();
10091   } else if (Type == Sema::FST_Scanf) {
10092     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10093                         numDataArgs, Str, HasVAListArg, Args, format_idx,
10094                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
10095 
10096     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
10097                                                  S.getLangOpts(),
10098                                                  S.Context.getTargetInfo()))
10099       H.DoneProcessing();
10100   } // TODO: handle other formats
10101 }
10102 
10103 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
10104   // Str - The format string.  NOTE: this is NOT null-terminated!
10105   StringRef StrRef = FExpr->getString();
10106   const char *Str = StrRef.data();
10107   // Account for cases where the string literal is truncated in a declaration.
10108   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
10109   assert(T && "String literal not of constant array type!");
10110   size_t TypeSize = T->getSize().getZExtValue();
10111   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10112   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
10113                                                          getLangOpts(),
10114                                                          Context.getTargetInfo());
10115 }
10116 
10117 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10118 
10119 // Returns the related absolute value function that is larger, of 0 if one
10120 // does not exist.
10121 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10122   switch (AbsFunction) {
10123   default:
10124     return 0;
10125 
10126   case Builtin::BI__builtin_abs:
10127     return Builtin::BI__builtin_labs;
10128   case Builtin::BI__builtin_labs:
10129     return Builtin::BI__builtin_llabs;
10130   case Builtin::BI__builtin_llabs:
10131     return 0;
10132 
10133   case Builtin::BI__builtin_fabsf:
10134     return Builtin::BI__builtin_fabs;
10135   case Builtin::BI__builtin_fabs:
10136     return Builtin::BI__builtin_fabsl;
10137   case Builtin::BI__builtin_fabsl:
10138     return 0;
10139 
10140   case Builtin::BI__builtin_cabsf:
10141     return Builtin::BI__builtin_cabs;
10142   case Builtin::BI__builtin_cabs:
10143     return Builtin::BI__builtin_cabsl;
10144   case Builtin::BI__builtin_cabsl:
10145     return 0;
10146 
10147   case Builtin::BIabs:
10148     return Builtin::BIlabs;
10149   case Builtin::BIlabs:
10150     return Builtin::BIllabs;
10151   case Builtin::BIllabs:
10152     return 0;
10153 
10154   case Builtin::BIfabsf:
10155     return Builtin::BIfabs;
10156   case Builtin::BIfabs:
10157     return Builtin::BIfabsl;
10158   case Builtin::BIfabsl:
10159     return 0;
10160 
10161   case Builtin::BIcabsf:
10162    return Builtin::BIcabs;
10163   case Builtin::BIcabs:
10164     return Builtin::BIcabsl;
10165   case Builtin::BIcabsl:
10166     return 0;
10167   }
10168 }
10169 
10170 // Returns the argument type of the absolute value function.
10171 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
10172                                              unsigned AbsType) {
10173   if (AbsType == 0)
10174     return QualType();
10175 
10176   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
10177   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10178   if (Error != ASTContext::GE_None)
10179     return QualType();
10180 
10181   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
10182   if (!FT)
10183     return QualType();
10184 
10185   if (FT->getNumParams() != 1)
10186     return QualType();
10187 
10188   return FT->getParamType(0);
10189 }
10190 
10191 // Returns the best absolute value function, or zero, based on type and
10192 // current absolute value function.
10193 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10194                                    unsigned AbsFunctionKind) {
10195   unsigned BestKind = 0;
10196   uint64_t ArgSize = Context.getTypeSize(ArgType);
10197   for (unsigned Kind = AbsFunctionKind; Kind != 0;
10198        Kind = getLargerAbsoluteValueFunction(Kind)) {
10199     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10200     if (Context.getTypeSize(ParamType) >= ArgSize) {
10201       if (BestKind == 0)
10202         BestKind = Kind;
10203       else if (Context.hasSameType(ParamType, ArgType)) {
10204         BestKind = Kind;
10205         break;
10206       }
10207     }
10208   }
10209   return BestKind;
10210 }
10211 
10212 enum AbsoluteValueKind {
10213   AVK_Integer,
10214   AVK_Floating,
10215   AVK_Complex
10216 };
10217 
10218 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
10219   if (T->isIntegralOrEnumerationType())
10220     return AVK_Integer;
10221   if (T->isRealFloatingType())
10222     return AVK_Floating;
10223   if (T->isAnyComplexType())
10224     return AVK_Complex;
10225 
10226   llvm_unreachable("Type not integer, floating, or complex");
10227 }
10228 
10229 // Changes the absolute value function to a different type.  Preserves whether
10230 // the function is a builtin.
10231 static unsigned changeAbsFunction(unsigned AbsKind,
10232                                   AbsoluteValueKind ValueKind) {
10233   switch (ValueKind) {
10234   case AVK_Integer:
10235     switch (AbsKind) {
10236     default:
10237       return 0;
10238     case Builtin::BI__builtin_fabsf:
10239     case Builtin::BI__builtin_fabs:
10240     case Builtin::BI__builtin_fabsl:
10241     case Builtin::BI__builtin_cabsf:
10242     case Builtin::BI__builtin_cabs:
10243     case Builtin::BI__builtin_cabsl:
10244       return Builtin::BI__builtin_abs;
10245     case Builtin::BIfabsf:
10246     case Builtin::BIfabs:
10247     case Builtin::BIfabsl:
10248     case Builtin::BIcabsf:
10249     case Builtin::BIcabs:
10250     case Builtin::BIcabsl:
10251       return Builtin::BIabs;
10252     }
10253   case AVK_Floating:
10254     switch (AbsKind) {
10255     default:
10256       return 0;
10257     case Builtin::BI__builtin_abs:
10258     case Builtin::BI__builtin_labs:
10259     case Builtin::BI__builtin_llabs:
10260     case Builtin::BI__builtin_cabsf:
10261     case Builtin::BI__builtin_cabs:
10262     case Builtin::BI__builtin_cabsl:
10263       return Builtin::BI__builtin_fabsf;
10264     case Builtin::BIabs:
10265     case Builtin::BIlabs:
10266     case Builtin::BIllabs:
10267     case Builtin::BIcabsf:
10268     case Builtin::BIcabs:
10269     case Builtin::BIcabsl:
10270       return Builtin::BIfabsf;
10271     }
10272   case AVK_Complex:
10273     switch (AbsKind) {
10274     default:
10275       return 0;
10276     case Builtin::BI__builtin_abs:
10277     case Builtin::BI__builtin_labs:
10278     case Builtin::BI__builtin_llabs:
10279     case Builtin::BI__builtin_fabsf:
10280     case Builtin::BI__builtin_fabs:
10281     case Builtin::BI__builtin_fabsl:
10282       return Builtin::BI__builtin_cabsf;
10283     case Builtin::BIabs:
10284     case Builtin::BIlabs:
10285     case Builtin::BIllabs:
10286     case Builtin::BIfabsf:
10287     case Builtin::BIfabs:
10288     case Builtin::BIfabsl:
10289       return Builtin::BIcabsf;
10290     }
10291   }
10292   llvm_unreachable("Unable to convert function");
10293 }
10294 
10295 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10296   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10297   if (!FnInfo)
10298     return 0;
10299 
10300   switch (FDecl->getBuiltinID()) {
10301   default:
10302     return 0;
10303   case Builtin::BI__builtin_abs:
10304   case Builtin::BI__builtin_fabs:
10305   case Builtin::BI__builtin_fabsf:
10306   case Builtin::BI__builtin_fabsl:
10307   case Builtin::BI__builtin_labs:
10308   case Builtin::BI__builtin_llabs:
10309   case Builtin::BI__builtin_cabs:
10310   case Builtin::BI__builtin_cabsf:
10311   case Builtin::BI__builtin_cabsl:
10312   case Builtin::BIabs:
10313   case Builtin::BIlabs:
10314   case Builtin::BIllabs:
10315   case Builtin::BIfabs:
10316   case Builtin::BIfabsf:
10317   case Builtin::BIfabsl:
10318   case Builtin::BIcabs:
10319   case Builtin::BIcabsf:
10320   case Builtin::BIcabsl:
10321     return FDecl->getBuiltinID();
10322   }
10323   llvm_unreachable("Unknown Builtin type");
10324 }
10325 
10326 // If the replacement is valid, emit a note with replacement function.
10327 // Additionally, suggest including the proper header if not already included.
10328 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10329                             unsigned AbsKind, QualType ArgType) {
10330   bool EmitHeaderHint = true;
10331   const char *HeaderName = nullptr;
10332   const char *FunctionName = nullptr;
10333   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10334     FunctionName = "std::abs";
10335     if (ArgType->isIntegralOrEnumerationType()) {
10336       HeaderName = "cstdlib";
10337     } else if (ArgType->isRealFloatingType()) {
10338       HeaderName = "cmath";
10339     } else {
10340       llvm_unreachable("Invalid Type");
10341     }
10342 
10343     // Lookup all std::abs
10344     if (NamespaceDecl *Std = S.getStdNamespace()) {
10345       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10346       R.suppressDiagnostics();
10347       S.LookupQualifiedName(R, Std);
10348 
10349       for (const auto *I : R) {
10350         const FunctionDecl *FDecl = nullptr;
10351         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10352           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10353         } else {
10354           FDecl = dyn_cast<FunctionDecl>(I);
10355         }
10356         if (!FDecl)
10357           continue;
10358 
10359         // Found std::abs(), check that they are the right ones.
10360         if (FDecl->getNumParams() != 1)
10361           continue;
10362 
10363         // Check that the parameter type can handle the argument.
10364         QualType ParamType = FDecl->getParamDecl(0)->getType();
10365         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10366             S.Context.getTypeSize(ArgType) <=
10367                 S.Context.getTypeSize(ParamType)) {
10368           // Found a function, don't need the header hint.
10369           EmitHeaderHint = false;
10370           break;
10371         }
10372       }
10373     }
10374   } else {
10375     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10376     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10377 
10378     if (HeaderName) {
10379       DeclarationName DN(&S.Context.Idents.get(FunctionName));
10380       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10381       R.suppressDiagnostics();
10382       S.LookupName(R, S.getCurScope());
10383 
10384       if (R.isSingleResult()) {
10385         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10386         if (FD && FD->getBuiltinID() == AbsKind) {
10387           EmitHeaderHint = false;
10388         } else {
10389           return;
10390         }
10391       } else if (!R.empty()) {
10392         return;
10393       }
10394     }
10395   }
10396 
10397   S.Diag(Loc, diag::note_replace_abs_function)
10398       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10399 
10400   if (!HeaderName)
10401     return;
10402 
10403   if (!EmitHeaderHint)
10404     return;
10405 
10406   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10407                                                     << FunctionName;
10408 }
10409 
10410 template <std::size_t StrLen>
10411 static bool IsStdFunction(const FunctionDecl *FDecl,
10412                           const char (&Str)[StrLen]) {
10413   if (!FDecl)
10414     return false;
10415   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10416     return false;
10417   if (!FDecl->isInStdNamespace())
10418     return false;
10419 
10420   return true;
10421 }
10422 
10423 // Warn when using the wrong abs() function.
10424 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10425                                       const FunctionDecl *FDecl) {
10426   if (Call->getNumArgs() != 1)
10427     return;
10428 
10429   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10430   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10431   if (AbsKind == 0 && !IsStdAbs)
10432     return;
10433 
10434   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10435   QualType ParamType = Call->getArg(0)->getType();
10436 
10437   // Unsigned types cannot be negative.  Suggest removing the absolute value
10438   // function call.
10439   if (ArgType->isUnsignedIntegerType()) {
10440     const char *FunctionName =
10441         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10442     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10443     Diag(Call->getExprLoc(), diag::note_remove_abs)
10444         << FunctionName
10445         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10446     return;
10447   }
10448 
10449   // Taking the absolute value of a pointer is very suspicious, they probably
10450   // wanted to index into an array, dereference a pointer, call a function, etc.
10451   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10452     unsigned DiagType = 0;
10453     if (ArgType->isFunctionType())
10454       DiagType = 1;
10455     else if (ArgType->isArrayType())
10456       DiagType = 2;
10457 
10458     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10459     return;
10460   }
10461 
10462   // std::abs has overloads which prevent most of the absolute value problems
10463   // from occurring.
10464   if (IsStdAbs)
10465     return;
10466 
10467   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10468   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10469 
10470   // The argument and parameter are the same kind.  Check if they are the right
10471   // size.
10472   if (ArgValueKind == ParamValueKind) {
10473     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10474       return;
10475 
10476     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10477     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10478         << FDecl << ArgType << ParamType;
10479 
10480     if (NewAbsKind == 0)
10481       return;
10482 
10483     emitReplacement(*this, Call->getExprLoc(),
10484                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10485     return;
10486   }
10487 
10488   // ArgValueKind != ParamValueKind
10489   // The wrong type of absolute value function was used.  Attempt to find the
10490   // proper one.
10491   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10492   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10493   if (NewAbsKind == 0)
10494     return;
10495 
10496   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10497       << FDecl << ParamValueKind << ArgValueKind;
10498 
10499   emitReplacement(*this, Call->getExprLoc(),
10500                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10501 }
10502 
10503 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10504 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10505                                 const FunctionDecl *FDecl) {
10506   if (!Call || !FDecl) return;
10507 
10508   // Ignore template specializations and macros.
10509   if (inTemplateInstantiation()) return;
10510   if (Call->getExprLoc().isMacroID()) return;
10511 
10512   // Only care about the one template argument, two function parameter std::max
10513   if (Call->getNumArgs() != 2) return;
10514   if (!IsStdFunction(FDecl, "max")) return;
10515   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10516   if (!ArgList) return;
10517   if (ArgList->size() != 1) return;
10518 
10519   // Check that template type argument is unsigned integer.
10520   const auto& TA = ArgList->get(0);
10521   if (TA.getKind() != TemplateArgument::Type) return;
10522   QualType ArgType = TA.getAsType();
10523   if (!ArgType->isUnsignedIntegerType()) return;
10524 
10525   // See if either argument is a literal zero.
10526   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10527     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10528     if (!MTE) return false;
10529     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10530     if (!Num) return false;
10531     if (Num->getValue() != 0) return false;
10532     return true;
10533   };
10534 
10535   const Expr *FirstArg = Call->getArg(0);
10536   const Expr *SecondArg = Call->getArg(1);
10537   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10538   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10539 
10540   // Only warn when exactly one argument is zero.
10541   if (IsFirstArgZero == IsSecondArgZero) return;
10542 
10543   SourceRange FirstRange = FirstArg->getSourceRange();
10544   SourceRange SecondRange = SecondArg->getSourceRange();
10545 
10546   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10547 
10548   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10549       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10550 
10551   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10552   SourceRange RemovalRange;
10553   if (IsFirstArgZero) {
10554     RemovalRange = SourceRange(FirstRange.getBegin(),
10555                                SecondRange.getBegin().getLocWithOffset(-1));
10556   } else {
10557     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10558                                SecondRange.getEnd());
10559   }
10560 
10561   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10562         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10563         << FixItHint::CreateRemoval(RemovalRange);
10564 }
10565 
10566 //===--- CHECK: Standard memory functions ---------------------------------===//
10567 
10568 /// Takes the expression passed to the size_t parameter of functions
10569 /// such as memcmp, strncat, etc and warns if it's a comparison.
10570 ///
10571 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10572 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10573                                            IdentifierInfo *FnName,
10574                                            SourceLocation FnLoc,
10575                                            SourceLocation RParenLoc) {
10576   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10577   if (!Size)
10578     return false;
10579 
10580   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10581   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10582     return false;
10583 
10584   SourceRange SizeRange = Size->getSourceRange();
10585   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10586       << SizeRange << FnName;
10587   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10588       << FnName
10589       << FixItHint::CreateInsertion(
10590              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10591       << FixItHint::CreateRemoval(RParenLoc);
10592   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10593       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10594       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10595                                     ")");
10596 
10597   return true;
10598 }
10599 
10600 /// Determine whether the given type is or contains a dynamic class type
10601 /// (e.g., whether it has a vtable).
10602 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10603                                                      bool &IsContained) {
10604   // Look through array types while ignoring qualifiers.
10605   const Type *Ty = T->getBaseElementTypeUnsafe();
10606   IsContained = false;
10607 
10608   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10609   RD = RD ? RD->getDefinition() : nullptr;
10610   if (!RD || RD->isInvalidDecl())
10611     return nullptr;
10612 
10613   if (RD->isDynamicClass())
10614     return RD;
10615 
10616   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10617   // It's impossible for a class to transitively contain itself by value, so
10618   // infinite recursion is impossible.
10619   for (auto *FD : RD->fields()) {
10620     bool SubContained;
10621     if (const CXXRecordDecl *ContainedRD =
10622             getContainedDynamicClass(FD->getType(), SubContained)) {
10623       IsContained = true;
10624       return ContainedRD;
10625     }
10626   }
10627 
10628   return nullptr;
10629 }
10630 
10631 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10632   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10633     if (Unary->getKind() == UETT_SizeOf)
10634       return Unary;
10635   return nullptr;
10636 }
10637 
10638 /// If E is a sizeof expression, returns its argument expression,
10639 /// otherwise returns NULL.
10640 static const Expr *getSizeOfExprArg(const Expr *E) {
10641   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10642     if (!SizeOf->isArgumentType())
10643       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10644   return nullptr;
10645 }
10646 
10647 /// If E is a sizeof expression, returns its argument type.
10648 static QualType getSizeOfArgType(const Expr *E) {
10649   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10650     return SizeOf->getTypeOfArgument();
10651   return QualType();
10652 }
10653 
10654 namespace {
10655 
10656 struct SearchNonTrivialToInitializeField
10657     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10658   using Super =
10659       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10660 
10661   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10662 
10663   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10664                      SourceLocation SL) {
10665     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10666       asDerived().visitArray(PDIK, AT, SL);
10667       return;
10668     }
10669 
10670     Super::visitWithKind(PDIK, FT, SL);
10671   }
10672 
10673   void visitARCStrong(QualType FT, SourceLocation SL) {
10674     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10675   }
10676   void visitARCWeak(QualType FT, SourceLocation SL) {
10677     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10678   }
10679   void visitStruct(QualType FT, SourceLocation SL) {
10680     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10681       visit(FD->getType(), FD->getLocation());
10682   }
10683   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10684                   const ArrayType *AT, SourceLocation SL) {
10685     visit(getContext().getBaseElementType(AT), SL);
10686   }
10687   void visitTrivial(QualType FT, SourceLocation SL) {}
10688 
10689   static void diag(QualType RT, const Expr *E, Sema &S) {
10690     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10691   }
10692 
10693   ASTContext &getContext() { return S.getASTContext(); }
10694 
10695   const Expr *E;
10696   Sema &S;
10697 };
10698 
10699 struct SearchNonTrivialToCopyField
10700     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10701   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10702 
10703   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10704 
10705   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10706                      SourceLocation SL) {
10707     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10708       asDerived().visitArray(PCK, AT, SL);
10709       return;
10710     }
10711 
10712     Super::visitWithKind(PCK, FT, SL);
10713   }
10714 
10715   void visitARCStrong(QualType FT, SourceLocation SL) {
10716     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10717   }
10718   void visitARCWeak(QualType FT, SourceLocation SL) {
10719     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10720   }
10721   void visitStruct(QualType FT, SourceLocation SL) {
10722     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10723       visit(FD->getType(), FD->getLocation());
10724   }
10725   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10726                   SourceLocation SL) {
10727     visit(getContext().getBaseElementType(AT), SL);
10728   }
10729   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10730                 SourceLocation SL) {}
10731   void visitTrivial(QualType FT, SourceLocation SL) {}
10732   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10733 
10734   static void diag(QualType RT, const Expr *E, Sema &S) {
10735     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10736   }
10737 
10738   ASTContext &getContext() { return S.getASTContext(); }
10739 
10740   const Expr *E;
10741   Sema &S;
10742 };
10743 
10744 }
10745 
10746 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10747 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10748   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10749 
10750   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10751     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10752       return false;
10753 
10754     return doesExprLikelyComputeSize(BO->getLHS()) ||
10755            doesExprLikelyComputeSize(BO->getRHS());
10756   }
10757 
10758   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10759 }
10760 
10761 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10762 ///
10763 /// \code
10764 ///   #define MACRO 0
10765 ///   foo(MACRO);
10766 ///   foo(0);
10767 /// \endcode
10768 ///
10769 /// This should return true for the first call to foo, but not for the second
10770 /// (regardless of whether foo is a macro or function).
10771 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10772                                         SourceLocation CallLoc,
10773                                         SourceLocation ArgLoc) {
10774   if (!CallLoc.isMacroID())
10775     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10776 
10777   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10778          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10779 }
10780 
10781 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10782 /// last two arguments transposed.
10783 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10784   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10785     return;
10786 
10787   const Expr *SizeArg =
10788     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10789 
10790   auto isLiteralZero = [](const Expr *E) {
10791     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10792   };
10793 
10794   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10795   SourceLocation CallLoc = Call->getRParenLoc();
10796   SourceManager &SM = S.getSourceManager();
10797   if (isLiteralZero(SizeArg) &&
10798       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10799 
10800     SourceLocation DiagLoc = SizeArg->getExprLoc();
10801 
10802     // Some platforms #define bzero to __builtin_memset. See if this is the
10803     // case, and if so, emit a better diagnostic.
10804     if (BId == Builtin::BIbzero ||
10805         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10806                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10807       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10808       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10809     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10810       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10811       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10812     }
10813     return;
10814   }
10815 
10816   // If the second argument to a memset is a sizeof expression and the third
10817   // isn't, this is also likely an error. This should catch
10818   // 'memset(buf, sizeof(buf), 0xff)'.
10819   if (BId == Builtin::BImemset &&
10820       doesExprLikelyComputeSize(Call->getArg(1)) &&
10821       !doesExprLikelyComputeSize(Call->getArg(2))) {
10822     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10823     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10824     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10825     return;
10826   }
10827 }
10828 
10829 /// Check for dangerous or invalid arguments to memset().
10830 ///
10831 /// This issues warnings on known problematic, dangerous or unspecified
10832 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10833 /// function calls.
10834 ///
10835 /// \param Call The call expression to diagnose.
10836 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10837                                    unsigned BId,
10838                                    IdentifierInfo *FnName) {
10839   assert(BId != 0);
10840 
10841   // It is possible to have a non-standard definition of memset.  Validate
10842   // we have enough arguments, and if not, abort further checking.
10843   unsigned ExpectedNumArgs =
10844       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10845   if (Call->getNumArgs() < ExpectedNumArgs)
10846     return;
10847 
10848   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10849                       BId == Builtin::BIstrndup ? 1 : 2);
10850   unsigned LenArg =
10851       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10852   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10853 
10854   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10855                                      Call->getBeginLoc(), Call->getRParenLoc()))
10856     return;
10857 
10858   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10859   CheckMemaccessSize(*this, BId, Call);
10860 
10861   // We have special checking when the length is a sizeof expression.
10862   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10863   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10864   llvm::FoldingSetNodeID SizeOfArgID;
10865 
10866   // Although widely used, 'bzero' is not a standard function. Be more strict
10867   // with the argument types before allowing diagnostics and only allow the
10868   // form bzero(ptr, sizeof(...)).
10869   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10870   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10871     return;
10872 
10873   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10874     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10875     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10876 
10877     QualType DestTy = Dest->getType();
10878     QualType PointeeTy;
10879     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10880       PointeeTy = DestPtrTy->getPointeeType();
10881 
10882       // Never warn about void type pointers. This can be used to suppress
10883       // false positives.
10884       if (PointeeTy->isVoidType())
10885         continue;
10886 
10887       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10888       // actually comparing the expressions for equality. Because computing the
10889       // expression IDs can be expensive, we only do this if the diagnostic is
10890       // enabled.
10891       if (SizeOfArg &&
10892           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10893                            SizeOfArg->getExprLoc())) {
10894         // We only compute IDs for expressions if the warning is enabled, and
10895         // cache the sizeof arg's ID.
10896         if (SizeOfArgID == llvm::FoldingSetNodeID())
10897           SizeOfArg->Profile(SizeOfArgID, Context, true);
10898         llvm::FoldingSetNodeID DestID;
10899         Dest->Profile(DestID, Context, true);
10900         if (DestID == SizeOfArgID) {
10901           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10902           //       over sizeof(src) as well.
10903           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10904           StringRef ReadableName = FnName->getName();
10905 
10906           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10907             if (UnaryOp->getOpcode() == UO_AddrOf)
10908               ActionIdx = 1; // If its an address-of operator, just remove it.
10909           if (!PointeeTy->isIncompleteType() &&
10910               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10911             ActionIdx = 2; // If the pointee's size is sizeof(char),
10912                            // suggest an explicit length.
10913 
10914           // If the function is defined as a builtin macro, do not show macro
10915           // expansion.
10916           SourceLocation SL = SizeOfArg->getExprLoc();
10917           SourceRange DSR = Dest->getSourceRange();
10918           SourceRange SSR = SizeOfArg->getSourceRange();
10919           SourceManager &SM = getSourceManager();
10920 
10921           if (SM.isMacroArgExpansion(SL)) {
10922             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10923             SL = SM.getSpellingLoc(SL);
10924             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10925                              SM.getSpellingLoc(DSR.getEnd()));
10926             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10927                              SM.getSpellingLoc(SSR.getEnd()));
10928           }
10929 
10930           DiagRuntimeBehavior(SL, SizeOfArg,
10931                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10932                                 << ReadableName
10933                                 << PointeeTy
10934                                 << DestTy
10935                                 << DSR
10936                                 << SSR);
10937           DiagRuntimeBehavior(SL, SizeOfArg,
10938                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10939                                 << ActionIdx
10940                                 << SSR);
10941 
10942           break;
10943         }
10944       }
10945 
10946       // Also check for cases where the sizeof argument is the exact same
10947       // type as the memory argument, and where it points to a user-defined
10948       // record type.
10949       if (SizeOfArgTy != QualType()) {
10950         if (PointeeTy->isRecordType() &&
10951             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10952           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10953                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10954                                 << FnName << SizeOfArgTy << ArgIdx
10955                                 << PointeeTy << Dest->getSourceRange()
10956                                 << LenExpr->getSourceRange());
10957           break;
10958         }
10959       }
10960     } else if (DestTy->isArrayType()) {
10961       PointeeTy = DestTy;
10962     }
10963 
10964     if (PointeeTy == QualType())
10965       continue;
10966 
10967     // Always complain about dynamic classes.
10968     bool IsContained;
10969     if (const CXXRecordDecl *ContainedRD =
10970             getContainedDynamicClass(PointeeTy, IsContained)) {
10971 
10972       unsigned OperationType = 0;
10973       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10974       // "overwritten" if we're warning about the destination for any call
10975       // but memcmp; otherwise a verb appropriate to the call.
10976       if (ArgIdx != 0 || IsCmp) {
10977         if (BId == Builtin::BImemcpy)
10978           OperationType = 1;
10979         else if(BId == Builtin::BImemmove)
10980           OperationType = 2;
10981         else if (IsCmp)
10982           OperationType = 3;
10983       }
10984 
10985       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10986                           PDiag(diag::warn_dyn_class_memaccess)
10987                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10988                               << IsContained << ContainedRD << OperationType
10989                               << Call->getCallee()->getSourceRange());
10990     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10991              BId != Builtin::BImemset)
10992       DiagRuntimeBehavior(
10993         Dest->getExprLoc(), Dest,
10994         PDiag(diag::warn_arc_object_memaccess)
10995           << ArgIdx << FnName << PointeeTy
10996           << Call->getCallee()->getSourceRange());
10997     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10998       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10999           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
11000         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11001                             PDiag(diag::warn_cstruct_memaccess)
11002                                 << ArgIdx << FnName << PointeeTy << 0);
11003         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
11004       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11005                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
11006         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11007                             PDiag(diag::warn_cstruct_memaccess)
11008                                 << ArgIdx << FnName << PointeeTy << 1);
11009         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
11010       } else {
11011         continue;
11012       }
11013     } else
11014       continue;
11015 
11016     DiagRuntimeBehavior(
11017       Dest->getExprLoc(), Dest,
11018       PDiag(diag::note_bad_memaccess_silence)
11019         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
11020     break;
11021   }
11022 }
11023 
11024 // A little helper routine: ignore addition and subtraction of integer literals.
11025 // This intentionally does not ignore all integer constant expressions because
11026 // we don't want to remove sizeof().
11027 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11028   Ex = Ex->IgnoreParenCasts();
11029 
11030   while (true) {
11031     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
11032     if (!BO || !BO->isAdditiveOp())
11033       break;
11034 
11035     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11036     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11037 
11038     if (isa<IntegerLiteral>(RHS))
11039       Ex = LHS;
11040     else if (isa<IntegerLiteral>(LHS))
11041       Ex = RHS;
11042     else
11043       break;
11044   }
11045 
11046   return Ex;
11047 }
11048 
11049 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
11050                                                       ASTContext &Context) {
11051   // Only handle constant-sized or VLAs, but not flexible members.
11052   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
11053     // Only issue the FIXIT for arrays of size > 1.
11054     if (CAT->getSize().getSExtValue() <= 1)
11055       return false;
11056   } else if (!Ty->isVariableArrayType()) {
11057     return false;
11058   }
11059   return true;
11060 }
11061 
11062 // Warn if the user has made the 'size' argument to strlcpy or strlcat
11063 // be the size of the source, instead of the destination.
11064 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11065                                     IdentifierInfo *FnName) {
11066 
11067   // Don't crash if the user has the wrong number of arguments
11068   unsigned NumArgs = Call->getNumArgs();
11069   if ((NumArgs != 3) && (NumArgs != 4))
11070     return;
11071 
11072   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
11073   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
11074   const Expr *CompareWithSrc = nullptr;
11075 
11076   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
11077                                      Call->getBeginLoc(), Call->getRParenLoc()))
11078     return;
11079 
11080   // Look for 'strlcpy(dst, x, sizeof(x))'
11081   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
11082     CompareWithSrc = Ex;
11083   else {
11084     // Look for 'strlcpy(dst, x, strlen(x))'
11085     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11086       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11087           SizeCall->getNumArgs() == 1)
11088         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
11089     }
11090   }
11091 
11092   if (!CompareWithSrc)
11093     return;
11094 
11095   // Determine if the argument to sizeof/strlen is equal to the source
11096   // argument.  In principle there's all kinds of things you could do
11097   // here, for instance creating an == expression and evaluating it with
11098   // EvaluateAsBooleanCondition, but this uses a more direct technique:
11099   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11100   if (!SrcArgDRE)
11101     return;
11102 
11103   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11104   if (!CompareWithSrcDRE ||
11105       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11106     return;
11107 
11108   const Expr *OriginalSizeArg = Call->getArg(2);
11109   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11110       << OriginalSizeArg->getSourceRange() << FnName;
11111 
11112   // Output a FIXIT hint if the destination is an array (rather than a
11113   // pointer to an array).  This could be enhanced to handle some
11114   // pointers if we know the actual size, like if DstArg is 'array+2'
11115   // we could say 'sizeof(array)-2'.
11116   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
11117   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
11118     return;
11119 
11120   SmallString<128> sizeString;
11121   llvm::raw_svector_ostream OS(sizeString);
11122   OS << "sizeof(";
11123   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11124   OS << ")";
11125 
11126   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
11127       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
11128                                       OS.str());
11129 }
11130 
11131 /// Check if two expressions refer to the same declaration.
11132 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11133   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11134     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11135       return D1->getDecl() == D2->getDecl();
11136   return false;
11137 }
11138 
11139 static const Expr *getStrlenExprArg(const Expr *E) {
11140   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11141     const FunctionDecl *FD = CE->getDirectCallee();
11142     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11143       return nullptr;
11144     return CE->getArg(0)->IgnoreParenCasts();
11145   }
11146   return nullptr;
11147 }
11148 
11149 // Warn on anti-patterns as the 'size' argument to strncat.
11150 // The correct size argument should look like following:
11151 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
11152 void Sema::CheckStrncatArguments(const CallExpr *CE,
11153                                  IdentifierInfo *FnName) {
11154   // Don't crash if the user has the wrong number of arguments.
11155   if (CE->getNumArgs() < 3)
11156     return;
11157   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11158   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11159   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11160 
11161   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11162                                      CE->getRParenLoc()))
11163     return;
11164 
11165   // Identify common expressions, which are wrongly used as the size argument
11166   // to strncat and may lead to buffer overflows.
11167   unsigned PatternType = 0;
11168   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11169     // - sizeof(dst)
11170     if (referToTheSameDecl(SizeOfArg, DstArg))
11171       PatternType = 1;
11172     // - sizeof(src)
11173     else if (referToTheSameDecl(SizeOfArg, SrcArg))
11174       PatternType = 2;
11175   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11176     if (BE->getOpcode() == BO_Sub) {
11177       const Expr *L = BE->getLHS()->IgnoreParenCasts();
11178       const Expr *R = BE->getRHS()->IgnoreParenCasts();
11179       // - sizeof(dst) - strlen(dst)
11180       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11181           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
11182         PatternType = 1;
11183       // - sizeof(src) - (anything)
11184       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11185         PatternType = 2;
11186     }
11187   }
11188 
11189   if (PatternType == 0)
11190     return;
11191 
11192   // Generate the diagnostic.
11193   SourceLocation SL = LenArg->getBeginLoc();
11194   SourceRange SR = LenArg->getSourceRange();
11195   SourceManager &SM = getSourceManager();
11196 
11197   // If the function is defined as a builtin macro, do not show macro expansion.
11198   if (SM.isMacroArgExpansion(SL)) {
11199     SL = SM.getSpellingLoc(SL);
11200     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11201                      SM.getSpellingLoc(SR.getEnd()));
11202   }
11203 
11204   // Check if the destination is an array (rather than a pointer to an array).
11205   QualType DstTy = DstArg->getType();
11206   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11207                                                                     Context);
11208   if (!isKnownSizeArray) {
11209     if (PatternType == 1)
11210       Diag(SL, diag::warn_strncat_wrong_size) << SR;
11211     else
11212       Diag(SL, diag::warn_strncat_src_size) << SR;
11213     return;
11214   }
11215 
11216   if (PatternType == 1)
11217     Diag(SL, diag::warn_strncat_large_size) << SR;
11218   else
11219     Diag(SL, diag::warn_strncat_src_size) << SR;
11220 
11221   SmallString<128> sizeString;
11222   llvm::raw_svector_ostream OS(sizeString);
11223   OS << "sizeof(";
11224   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11225   OS << ") - ";
11226   OS << "strlen(";
11227   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11228   OS << ") - 1";
11229 
11230   Diag(SL, diag::note_strncat_wrong_size)
11231     << FixItHint::CreateReplacement(SR, OS.str());
11232 }
11233 
11234 namespace {
11235 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11236                                 const UnaryOperator *UnaryExpr, const Decl *D) {
11237   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
11238     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11239         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11240     return;
11241   }
11242 }
11243 
11244 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11245                                  const UnaryOperator *UnaryExpr) {
11246   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11247     const Decl *D = Lvalue->getDecl();
11248     if (isa<DeclaratorDecl>(D))
11249       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
11250         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11251   }
11252 
11253   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11254     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11255                                       Lvalue->getMemberDecl());
11256 }
11257 
11258 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11259                             const UnaryOperator *UnaryExpr) {
11260   const auto *Lambda = dyn_cast<LambdaExpr>(
11261       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11262   if (!Lambda)
11263     return;
11264 
11265   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11266       << CalleeName << 2 /*object: lambda expression*/;
11267 }
11268 
11269 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11270                                   const DeclRefExpr *Lvalue) {
11271   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11272   if (Var == nullptr)
11273     return;
11274 
11275   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11276       << CalleeName << 0 /*object: */ << Var;
11277 }
11278 
11279 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11280                             const CastExpr *Cast) {
11281   SmallString<128> SizeString;
11282   llvm::raw_svector_ostream OS(SizeString);
11283 
11284   clang::CastKind Kind = Cast->getCastKind();
11285   if (Kind == clang::CK_BitCast &&
11286       !Cast->getSubExpr()->getType()->isFunctionPointerType())
11287     return;
11288   if (Kind == clang::CK_IntegralToPointer &&
11289       !isa<IntegerLiteral>(
11290           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11291     return;
11292 
11293   switch (Cast->getCastKind()) {
11294   case clang::CK_BitCast:
11295   case clang::CK_IntegralToPointer:
11296   case clang::CK_FunctionToPointerDecay:
11297     OS << '\'';
11298     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11299     OS << '\'';
11300     break;
11301   default:
11302     return;
11303   }
11304 
11305   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11306       << CalleeName << 0 /*object: */ << OS.str();
11307 }
11308 } // namespace
11309 
11310 /// Alerts the user that they are attempting to free a non-malloc'd object.
11311 void Sema::CheckFreeArguments(const CallExpr *E) {
11312   const std::string CalleeName =
11313       cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11314 
11315   { // Prefer something that doesn't involve a cast to make things simpler.
11316     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11317     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11318       switch (UnaryExpr->getOpcode()) {
11319       case UnaryOperator::Opcode::UO_AddrOf:
11320         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11321       case UnaryOperator::Opcode::UO_Plus:
11322         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11323       default:
11324         break;
11325       }
11326 
11327     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11328       if (Lvalue->getType()->isArrayType())
11329         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11330 
11331     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11332       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11333           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11334       return;
11335     }
11336 
11337     if (isa<BlockExpr>(Arg)) {
11338       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11339           << CalleeName << 1 /*object: block*/;
11340       return;
11341     }
11342   }
11343   // Maybe the cast was important, check after the other cases.
11344   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11345     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11346 }
11347 
11348 void
11349 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11350                          SourceLocation ReturnLoc,
11351                          bool isObjCMethod,
11352                          const AttrVec *Attrs,
11353                          const FunctionDecl *FD) {
11354   // Check if the return value is null but should not be.
11355   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11356        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
11357       CheckNonNullExpr(*this, RetValExp))
11358     Diag(ReturnLoc, diag::warn_null_ret)
11359       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11360 
11361   // C++11 [basic.stc.dynamic.allocation]p4:
11362   //   If an allocation function declared with a non-throwing
11363   //   exception-specification fails to allocate storage, it shall return
11364   //   a null pointer. Any other allocation function that fails to allocate
11365   //   storage shall indicate failure only by throwing an exception [...]
11366   if (FD) {
11367     OverloadedOperatorKind Op = FD->getOverloadedOperator();
11368     if (Op == OO_New || Op == OO_Array_New) {
11369       const FunctionProtoType *Proto
11370         = FD->getType()->castAs<FunctionProtoType>();
11371       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11372           CheckNonNullExpr(*this, RetValExp))
11373         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11374           << FD << getLangOpts().CPlusPlus11;
11375     }
11376   }
11377 
11378   // PPC MMA non-pointer types are not allowed as return type. Checking the type
11379   // here prevent the user from using a PPC MMA type as trailing return type.
11380   if (Context.getTargetInfo().getTriple().isPPC64())
11381     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11382 }
11383 
11384 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
11385 
11386 /// Check for comparisons of floating point operands using != and ==.
11387 /// Issue a warning if these are no self-comparisons, as they are not likely
11388 /// to do what the programmer intended.
11389 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
11390   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
11391   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
11392 
11393   // Special case: check for x == x (which is OK).
11394   // Do not emit warnings for such cases.
11395   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11396     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11397       if (DRL->getDecl() == DRR->getDecl())
11398         return;
11399 
11400   // Special case: check for comparisons against literals that can be exactly
11401   //  represented by APFloat.  In such cases, do not emit a warning.  This
11402   //  is a heuristic: often comparison against such literals are used to
11403   //  detect if a value in a variable has not changed.  This clearly can
11404   //  lead to false negatives.
11405   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11406     if (FLL->isExact())
11407       return;
11408   } else
11409     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11410       if (FLR->isExact())
11411         return;
11412 
11413   // Check for comparisons with builtin types.
11414   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11415     if (CL->getBuiltinCallee())
11416       return;
11417 
11418   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11419     if (CR->getBuiltinCallee())
11420       return;
11421 
11422   // Emit the diagnostic.
11423   Diag(Loc, diag::warn_floatingpoint_eq)
11424     << LHS->getSourceRange() << RHS->getSourceRange();
11425 }
11426 
11427 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11428 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11429 
11430 namespace {
11431 
11432 /// Structure recording the 'active' range of an integer-valued
11433 /// expression.
11434 struct IntRange {
11435   /// The number of bits active in the int. Note that this includes exactly one
11436   /// sign bit if !NonNegative.
11437   unsigned Width;
11438 
11439   /// True if the int is known not to have negative values. If so, all leading
11440   /// bits before Width are known zero, otherwise they are known to be the
11441   /// same as the MSB within Width.
11442   bool NonNegative;
11443 
11444   IntRange(unsigned Width, bool NonNegative)
11445       : Width(Width), NonNegative(NonNegative) {}
11446 
11447   /// Number of bits excluding the sign bit.
11448   unsigned valueBits() const {
11449     return NonNegative ? Width : Width - 1;
11450   }
11451 
11452   /// Returns the range of the bool type.
11453   static IntRange forBoolType() {
11454     return IntRange(1, true);
11455   }
11456 
11457   /// Returns the range of an opaque value of the given integral type.
11458   static IntRange forValueOfType(ASTContext &C, QualType T) {
11459     return forValueOfCanonicalType(C,
11460                           T->getCanonicalTypeInternal().getTypePtr());
11461   }
11462 
11463   /// Returns the range of an opaque value of a canonical integral type.
11464   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11465     assert(T->isCanonicalUnqualified());
11466 
11467     if (const VectorType *VT = dyn_cast<VectorType>(T))
11468       T = VT->getElementType().getTypePtr();
11469     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11470       T = CT->getElementType().getTypePtr();
11471     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11472       T = AT->getValueType().getTypePtr();
11473 
11474     if (!C.getLangOpts().CPlusPlus) {
11475       // For enum types in C code, use the underlying datatype.
11476       if (const EnumType *ET = dyn_cast<EnumType>(T))
11477         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11478     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11479       // For enum types in C++, use the known bit width of the enumerators.
11480       EnumDecl *Enum = ET->getDecl();
11481       // In C++11, enums can have a fixed underlying type. Use this type to
11482       // compute the range.
11483       if (Enum->isFixed()) {
11484         return IntRange(C.getIntWidth(QualType(T, 0)),
11485                         !ET->isSignedIntegerOrEnumerationType());
11486       }
11487 
11488       unsigned NumPositive = Enum->getNumPositiveBits();
11489       unsigned NumNegative = Enum->getNumNegativeBits();
11490 
11491       if (NumNegative == 0)
11492         return IntRange(NumPositive, true/*NonNegative*/);
11493       else
11494         return IntRange(std::max(NumPositive + 1, NumNegative),
11495                         false/*NonNegative*/);
11496     }
11497 
11498     if (const auto *EIT = dyn_cast<BitIntType>(T))
11499       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11500 
11501     const BuiltinType *BT = cast<BuiltinType>(T);
11502     assert(BT->isInteger());
11503 
11504     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11505   }
11506 
11507   /// Returns the "target" range of a canonical integral type, i.e.
11508   /// the range of values expressible in the type.
11509   ///
11510   /// This matches forValueOfCanonicalType except that enums have the
11511   /// full range of their type, not the range of their enumerators.
11512   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11513     assert(T->isCanonicalUnqualified());
11514 
11515     if (const VectorType *VT = dyn_cast<VectorType>(T))
11516       T = VT->getElementType().getTypePtr();
11517     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11518       T = CT->getElementType().getTypePtr();
11519     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11520       T = AT->getValueType().getTypePtr();
11521     if (const EnumType *ET = dyn_cast<EnumType>(T))
11522       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11523 
11524     if (const auto *EIT = dyn_cast<BitIntType>(T))
11525       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11526 
11527     const BuiltinType *BT = cast<BuiltinType>(T);
11528     assert(BT->isInteger());
11529 
11530     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11531   }
11532 
11533   /// Returns the supremum of two ranges: i.e. their conservative merge.
11534   static IntRange join(IntRange L, IntRange R) {
11535     bool Unsigned = L.NonNegative && R.NonNegative;
11536     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11537                     L.NonNegative && R.NonNegative);
11538   }
11539 
11540   /// Return the range of a bitwise-AND of the two ranges.
11541   static IntRange bit_and(IntRange L, IntRange R) {
11542     unsigned Bits = std::max(L.Width, R.Width);
11543     bool NonNegative = false;
11544     if (L.NonNegative) {
11545       Bits = std::min(Bits, L.Width);
11546       NonNegative = true;
11547     }
11548     if (R.NonNegative) {
11549       Bits = std::min(Bits, R.Width);
11550       NonNegative = true;
11551     }
11552     return IntRange(Bits, NonNegative);
11553   }
11554 
11555   /// Return the range of a sum of the two ranges.
11556   static IntRange sum(IntRange L, IntRange R) {
11557     bool Unsigned = L.NonNegative && R.NonNegative;
11558     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11559                     Unsigned);
11560   }
11561 
11562   /// Return the range of a difference of the two ranges.
11563   static IntRange difference(IntRange L, IntRange R) {
11564     // We need a 1-bit-wider range if:
11565     //   1) LHS can be negative: least value can be reduced.
11566     //   2) RHS can be negative: greatest value can be increased.
11567     bool CanWiden = !L.NonNegative || !R.NonNegative;
11568     bool Unsigned = L.NonNegative && R.Width == 0;
11569     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11570                         !Unsigned,
11571                     Unsigned);
11572   }
11573 
11574   /// Return the range of a product of the two ranges.
11575   static IntRange product(IntRange L, IntRange R) {
11576     // If both LHS and RHS can be negative, we can form
11577     //   -2^L * -2^R = 2^(L + R)
11578     // which requires L + R + 1 value bits to represent.
11579     bool CanWiden = !L.NonNegative && !R.NonNegative;
11580     bool Unsigned = L.NonNegative && R.NonNegative;
11581     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11582                     Unsigned);
11583   }
11584 
11585   /// Return the range of a remainder operation between the two ranges.
11586   static IntRange rem(IntRange L, IntRange R) {
11587     // The result of a remainder can't be larger than the result of
11588     // either side. The sign of the result is the sign of the LHS.
11589     bool Unsigned = L.NonNegative;
11590     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11591                     Unsigned);
11592   }
11593 };
11594 
11595 } // namespace
11596 
11597 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11598                               unsigned MaxWidth) {
11599   if (value.isSigned() && value.isNegative())
11600     return IntRange(value.getMinSignedBits(), false);
11601 
11602   if (value.getBitWidth() > MaxWidth)
11603     value = value.trunc(MaxWidth);
11604 
11605   // isNonNegative() just checks the sign bit without considering
11606   // signedness.
11607   return IntRange(value.getActiveBits(), true);
11608 }
11609 
11610 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11611                               unsigned MaxWidth) {
11612   if (result.isInt())
11613     return GetValueRange(C, result.getInt(), MaxWidth);
11614 
11615   if (result.isVector()) {
11616     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11617     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11618       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11619       R = IntRange::join(R, El);
11620     }
11621     return R;
11622   }
11623 
11624   if (result.isComplexInt()) {
11625     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11626     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11627     return IntRange::join(R, I);
11628   }
11629 
11630   // This can happen with lossless casts to intptr_t of "based" lvalues.
11631   // Assume it might use arbitrary bits.
11632   // FIXME: The only reason we need to pass the type in here is to get
11633   // the sign right on this one case.  It would be nice if APValue
11634   // preserved this.
11635   assert(result.isLValue() || result.isAddrLabelDiff());
11636   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11637 }
11638 
11639 static QualType GetExprType(const Expr *E) {
11640   QualType Ty = E->getType();
11641   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11642     Ty = AtomicRHS->getValueType();
11643   return Ty;
11644 }
11645 
11646 /// Pseudo-evaluate the given integer expression, estimating the
11647 /// range of values it might take.
11648 ///
11649 /// \param MaxWidth The width to which the value will be truncated.
11650 /// \param Approximate If \c true, return a likely range for the result: in
11651 ///        particular, assume that arithmetic on narrower types doesn't leave
11652 ///        those types. If \c false, return a range including all possible
11653 ///        result values.
11654 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11655                              bool InConstantContext, bool Approximate) {
11656   E = E->IgnoreParens();
11657 
11658   // Try a full evaluation first.
11659   Expr::EvalResult result;
11660   if (E->EvaluateAsRValue(result, C, InConstantContext))
11661     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11662 
11663   // I think we only want to look through implicit casts here; if the
11664   // user has an explicit widening cast, we should treat the value as
11665   // being of the new, wider type.
11666   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11667     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11668       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11669                           Approximate);
11670 
11671     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11672 
11673     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11674                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11675 
11676     // Assume that non-integer casts can span the full range of the type.
11677     if (!isIntegerCast)
11678       return OutputTypeRange;
11679 
11680     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11681                                      std::min(MaxWidth, OutputTypeRange.Width),
11682                                      InConstantContext, Approximate);
11683 
11684     // Bail out if the subexpr's range is as wide as the cast type.
11685     if (SubRange.Width >= OutputTypeRange.Width)
11686       return OutputTypeRange;
11687 
11688     // Otherwise, we take the smaller width, and we're non-negative if
11689     // either the output type or the subexpr is.
11690     return IntRange(SubRange.Width,
11691                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11692   }
11693 
11694   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11695     // If we can fold the condition, just take that operand.
11696     bool CondResult;
11697     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11698       return GetExprRange(C,
11699                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11700                           MaxWidth, InConstantContext, Approximate);
11701 
11702     // Otherwise, conservatively merge.
11703     // GetExprRange requires an integer expression, but a throw expression
11704     // results in a void type.
11705     Expr *E = CO->getTrueExpr();
11706     IntRange L = E->getType()->isVoidType()
11707                      ? IntRange{0, true}
11708                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11709     E = CO->getFalseExpr();
11710     IntRange R = E->getType()->isVoidType()
11711                      ? IntRange{0, true}
11712                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11713     return IntRange::join(L, R);
11714   }
11715 
11716   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11717     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11718 
11719     switch (BO->getOpcode()) {
11720     case BO_Cmp:
11721       llvm_unreachable("builtin <=> should have class type");
11722 
11723     // Boolean-valued operations are single-bit and positive.
11724     case BO_LAnd:
11725     case BO_LOr:
11726     case BO_LT:
11727     case BO_GT:
11728     case BO_LE:
11729     case BO_GE:
11730     case BO_EQ:
11731     case BO_NE:
11732       return IntRange::forBoolType();
11733 
11734     // The type of the assignments is the type of the LHS, so the RHS
11735     // is not necessarily the same type.
11736     case BO_MulAssign:
11737     case BO_DivAssign:
11738     case BO_RemAssign:
11739     case BO_AddAssign:
11740     case BO_SubAssign:
11741     case BO_XorAssign:
11742     case BO_OrAssign:
11743       // TODO: bitfields?
11744       return IntRange::forValueOfType(C, GetExprType(E));
11745 
11746     // Simple assignments just pass through the RHS, which will have
11747     // been coerced to the LHS type.
11748     case BO_Assign:
11749       // TODO: bitfields?
11750       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11751                           Approximate);
11752 
11753     // Operations with opaque sources are black-listed.
11754     case BO_PtrMemD:
11755     case BO_PtrMemI:
11756       return IntRange::forValueOfType(C, GetExprType(E));
11757 
11758     // Bitwise-and uses the *infinum* of the two source ranges.
11759     case BO_And:
11760     case BO_AndAssign:
11761       Combine = IntRange::bit_and;
11762       break;
11763 
11764     // Left shift gets black-listed based on a judgement call.
11765     case BO_Shl:
11766       // ...except that we want to treat '1 << (blah)' as logically
11767       // positive.  It's an important idiom.
11768       if (IntegerLiteral *I
11769             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11770         if (I->getValue() == 1) {
11771           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11772           return IntRange(R.Width, /*NonNegative*/ true);
11773         }
11774       }
11775       LLVM_FALLTHROUGH;
11776 
11777     case BO_ShlAssign:
11778       return IntRange::forValueOfType(C, GetExprType(E));
11779 
11780     // Right shift by a constant can narrow its left argument.
11781     case BO_Shr:
11782     case BO_ShrAssign: {
11783       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11784                                 Approximate);
11785 
11786       // If the shift amount is a positive constant, drop the width by
11787       // that much.
11788       if (Optional<llvm::APSInt> shift =
11789               BO->getRHS()->getIntegerConstantExpr(C)) {
11790         if (shift->isNonNegative()) {
11791           unsigned zext = shift->getZExtValue();
11792           if (zext >= L.Width)
11793             L.Width = (L.NonNegative ? 0 : 1);
11794           else
11795             L.Width -= zext;
11796         }
11797       }
11798 
11799       return L;
11800     }
11801 
11802     // Comma acts as its right operand.
11803     case BO_Comma:
11804       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11805                           Approximate);
11806 
11807     case BO_Add:
11808       if (!Approximate)
11809         Combine = IntRange::sum;
11810       break;
11811 
11812     case BO_Sub:
11813       if (BO->getLHS()->getType()->isPointerType())
11814         return IntRange::forValueOfType(C, GetExprType(E));
11815       if (!Approximate)
11816         Combine = IntRange::difference;
11817       break;
11818 
11819     case BO_Mul:
11820       if (!Approximate)
11821         Combine = IntRange::product;
11822       break;
11823 
11824     // The width of a division result is mostly determined by the size
11825     // of the LHS.
11826     case BO_Div: {
11827       // Don't 'pre-truncate' the operands.
11828       unsigned opWidth = C.getIntWidth(GetExprType(E));
11829       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11830                                 Approximate);
11831 
11832       // If the divisor is constant, use that.
11833       if (Optional<llvm::APSInt> divisor =
11834               BO->getRHS()->getIntegerConstantExpr(C)) {
11835         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11836         if (log2 >= L.Width)
11837           L.Width = (L.NonNegative ? 0 : 1);
11838         else
11839           L.Width = std::min(L.Width - log2, MaxWidth);
11840         return L;
11841       }
11842 
11843       // Otherwise, just use the LHS's width.
11844       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11845       // could be -1.
11846       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11847                                 Approximate);
11848       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11849     }
11850 
11851     case BO_Rem:
11852       Combine = IntRange::rem;
11853       break;
11854 
11855     // The default behavior is okay for these.
11856     case BO_Xor:
11857     case BO_Or:
11858       break;
11859     }
11860 
11861     // Combine the two ranges, but limit the result to the type in which we
11862     // performed the computation.
11863     QualType T = GetExprType(E);
11864     unsigned opWidth = C.getIntWidth(T);
11865     IntRange L =
11866         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11867     IntRange R =
11868         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11869     IntRange C = Combine(L, R);
11870     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11871     C.Width = std::min(C.Width, MaxWidth);
11872     return C;
11873   }
11874 
11875   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11876     switch (UO->getOpcode()) {
11877     // Boolean-valued operations are white-listed.
11878     case UO_LNot:
11879       return IntRange::forBoolType();
11880 
11881     // Operations with opaque sources are black-listed.
11882     case UO_Deref:
11883     case UO_AddrOf: // should be impossible
11884       return IntRange::forValueOfType(C, GetExprType(E));
11885 
11886     default:
11887       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11888                           Approximate);
11889     }
11890   }
11891 
11892   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11893     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11894                         Approximate);
11895 
11896   if (const auto *BitField = E->getSourceBitField())
11897     return IntRange(BitField->getBitWidthValue(C),
11898                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11899 
11900   return IntRange::forValueOfType(C, GetExprType(E));
11901 }
11902 
11903 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11904                              bool InConstantContext, bool Approximate) {
11905   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11906                       Approximate);
11907 }
11908 
11909 /// Checks whether the given value, which currently has the given
11910 /// source semantics, has the same value when coerced through the
11911 /// target semantics.
11912 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11913                                  const llvm::fltSemantics &Src,
11914                                  const llvm::fltSemantics &Tgt) {
11915   llvm::APFloat truncated = value;
11916 
11917   bool ignored;
11918   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11919   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11920 
11921   return truncated.bitwiseIsEqual(value);
11922 }
11923 
11924 /// Checks whether the given value, which currently has the given
11925 /// source semantics, has the same value when coerced through the
11926 /// target semantics.
11927 ///
11928 /// The value might be a vector of floats (or a complex number).
11929 static bool IsSameFloatAfterCast(const APValue &value,
11930                                  const llvm::fltSemantics &Src,
11931                                  const llvm::fltSemantics &Tgt) {
11932   if (value.isFloat())
11933     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11934 
11935   if (value.isVector()) {
11936     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11937       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11938         return false;
11939     return true;
11940   }
11941 
11942   assert(value.isComplexFloat());
11943   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11944           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11945 }
11946 
11947 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11948                                        bool IsListInit = false);
11949 
11950 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11951   // Suppress cases where we are comparing against an enum constant.
11952   if (const DeclRefExpr *DR =
11953       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11954     if (isa<EnumConstantDecl>(DR->getDecl()))
11955       return true;
11956 
11957   // Suppress cases where the value is expanded from a macro, unless that macro
11958   // is how a language represents a boolean literal. This is the case in both C
11959   // and Objective-C.
11960   SourceLocation BeginLoc = E->getBeginLoc();
11961   if (BeginLoc.isMacroID()) {
11962     StringRef MacroName = Lexer::getImmediateMacroName(
11963         BeginLoc, S.getSourceManager(), S.getLangOpts());
11964     return MacroName != "YES" && MacroName != "NO" &&
11965            MacroName != "true" && MacroName != "false";
11966   }
11967 
11968   return false;
11969 }
11970 
11971 static bool isKnownToHaveUnsignedValue(Expr *E) {
11972   return E->getType()->isIntegerType() &&
11973          (!E->getType()->isSignedIntegerType() ||
11974           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11975 }
11976 
11977 namespace {
11978 /// The promoted range of values of a type. In general this has the
11979 /// following structure:
11980 ///
11981 ///     |-----------| . . . |-----------|
11982 ///     ^           ^       ^           ^
11983 ///    Min       HoleMin  HoleMax      Max
11984 ///
11985 /// ... where there is only a hole if a signed type is promoted to unsigned
11986 /// (in which case Min and Max are the smallest and largest representable
11987 /// values).
11988 struct PromotedRange {
11989   // Min, or HoleMax if there is a hole.
11990   llvm::APSInt PromotedMin;
11991   // Max, or HoleMin if there is a hole.
11992   llvm::APSInt PromotedMax;
11993 
11994   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11995     if (R.Width == 0)
11996       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11997     else if (R.Width >= BitWidth && !Unsigned) {
11998       // Promotion made the type *narrower*. This happens when promoting
11999       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12000       // Treat all values of 'signed int' as being in range for now.
12001       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
12002       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
12003     } else {
12004       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
12005                         .extOrTrunc(BitWidth);
12006       PromotedMin.setIsUnsigned(Unsigned);
12007 
12008       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
12009                         .extOrTrunc(BitWidth);
12010       PromotedMax.setIsUnsigned(Unsigned);
12011     }
12012   }
12013 
12014   // Determine whether this range is contiguous (has no hole).
12015   bool isContiguous() const { return PromotedMin <= PromotedMax; }
12016 
12017   // Where a constant value is within the range.
12018   enum ComparisonResult {
12019     LT = 0x1,
12020     LE = 0x2,
12021     GT = 0x4,
12022     GE = 0x8,
12023     EQ = 0x10,
12024     NE = 0x20,
12025     InRangeFlag = 0x40,
12026 
12027     Less = LE | LT | NE,
12028     Min = LE | InRangeFlag,
12029     InRange = InRangeFlag,
12030     Max = GE | InRangeFlag,
12031     Greater = GE | GT | NE,
12032 
12033     OnlyValue = LE | GE | EQ | InRangeFlag,
12034     InHole = NE
12035   };
12036 
12037   ComparisonResult compare(const llvm::APSInt &Value) const {
12038     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12039            Value.isUnsigned() == PromotedMin.isUnsigned());
12040     if (!isContiguous()) {
12041       assert(Value.isUnsigned() && "discontiguous range for signed compare");
12042       if (Value.isMinValue()) return Min;
12043       if (Value.isMaxValue()) return Max;
12044       if (Value >= PromotedMin) return InRange;
12045       if (Value <= PromotedMax) return InRange;
12046       return InHole;
12047     }
12048 
12049     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
12050     case -1: return Less;
12051     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12052     case 1:
12053       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
12054       case -1: return InRange;
12055       case 0: return Max;
12056       case 1: return Greater;
12057       }
12058     }
12059 
12060     llvm_unreachable("impossible compare result");
12061   }
12062 
12063   static llvm::Optional<StringRef>
12064   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12065     if (Op == BO_Cmp) {
12066       ComparisonResult LTFlag = LT, GTFlag = GT;
12067       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
12068 
12069       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12070       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12071       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12072       return llvm::None;
12073     }
12074 
12075     ComparisonResult TrueFlag, FalseFlag;
12076     if (Op == BO_EQ) {
12077       TrueFlag = EQ;
12078       FalseFlag = NE;
12079     } else if (Op == BO_NE) {
12080       TrueFlag = NE;
12081       FalseFlag = EQ;
12082     } else {
12083       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12084         TrueFlag = LT;
12085         FalseFlag = GE;
12086       } else {
12087         TrueFlag = GT;
12088         FalseFlag = LE;
12089       }
12090       if (Op == BO_GE || Op == BO_LE)
12091         std::swap(TrueFlag, FalseFlag);
12092     }
12093     if (R & TrueFlag)
12094       return StringRef("true");
12095     if (R & FalseFlag)
12096       return StringRef("false");
12097     return llvm::None;
12098   }
12099 };
12100 }
12101 
12102 static bool HasEnumType(Expr *E) {
12103   // Strip off implicit integral promotions.
12104   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12105     if (ICE->getCastKind() != CK_IntegralCast &&
12106         ICE->getCastKind() != CK_NoOp)
12107       break;
12108     E = ICE->getSubExpr();
12109   }
12110 
12111   return E->getType()->isEnumeralType();
12112 }
12113 
12114 static int classifyConstantValue(Expr *Constant) {
12115   // The values of this enumeration are used in the diagnostics
12116   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12117   enum ConstantValueKind {
12118     Miscellaneous = 0,
12119     LiteralTrue,
12120     LiteralFalse
12121   };
12122   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12123     return BL->getValue() ? ConstantValueKind::LiteralTrue
12124                           : ConstantValueKind::LiteralFalse;
12125   return ConstantValueKind::Miscellaneous;
12126 }
12127 
12128 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
12129                                         Expr *Constant, Expr *Other,
12130                                         const llvm::APSInt &Value,
12131                                         bool RhsConstant) {
12132   if (S.inTemplateInstantiation())
12133     return false;
12134 
12135   Expr *OriginalOther = Other;
12136 
12137   Constant = Constant->IgnoreParenImpCasts();
12138   Other = Other->IgnoreParenImpCasts();
12139 
12140   // Suppress warnings on tautological comparisons between values of the same
12141   // enumeration type. There are only two ways we could warn on this:
12142   //  - If the constant is outside the range of representable values of
12143   //    the enumeration. In such a case, we should warn about the cast
12144   //    to enumeration type, not about the comparison.
12145   //  - If the constant is the maximum / minimum in-range value. For an
12146   //    enumeratin type, such comparisons can be meaningful and useful.
12147   if (Constant->getType()->isEnumeralType() &&
12148       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12149     return false;
12150 
12151   IntRange OtherValueRange = GetExprRange(
12152       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
12153 
12154   QualType OtherT = Other->getType();
12155   if (const auto *AT = OtherT->getAs<AtomicType>())
12156     OtherT = AT->getValueType();
12157   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12158 
12159   // Special case for ObjC BOOL on targets where its a typedef for a signed char
12160   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12161   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12162                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
12163                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12164 
12165   // Whether we're treating Other as being a bool because of the form of
12166   // expression despite it having another type (typically 'int' in C).
12167   bool OtherIsBooleanDespiteType =
12168       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12169   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12170     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
12171 
12172   // Check if all values in the range of possible values of this expression
12173   // lead to the same comparison outcome.
12174   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
12175                                         Value.isUnsigned());
12176   auto Cmp = OtherPromotedValueRange.compare(Value);
12177   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12178   if (!Result)
12179     return false;
12180 
12181   // Also consider the range determined by the type alone. This allows us to
12182   // classify the warning under the proper diagnostic group.
12183   bool TautologicalTypeCompare = false;
12184   {
12185     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12186                                          Value.isUnsigned());
12187     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12188     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12189                                                        RhsConstant)) {
12190       TautologicalTypeCompare = true;
12191       Cmp = TypeCmp;
12192       Result = TypeResult;
12193     }
12194   }
12195 
12196   // Don't warn if the non-constant operand actually always evaluates to the
12197   // same value.
12198   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
12199     return false;
12200 
12201   // Suppress the diagnostic for an in-range comparison if the constant comes
12202   // from a macro or enumerator. We don't want to diagnose
12203   //
12204   //   some_long_value <= INT_MAX
12205   //
12206   // when sizeof(int) == sizeof(long).
12207   bool InRange = Cmp & PromotedRange::InRangeFlag;
12208   if (InRange && IsEnumConstOrFromMacro(S, Constant))
12209     return false;
12210 
12211   // A comparison of an unsigned bit-field against 0 is really a type problem,
12212   // even though at the type level the bit-field might promote to 'signed int'.
12213   if (Other->refersToBitField() && InRange && Value == 0 &&
12214       Other->getType()->isUnsignedIntegerOrEnumerationType())
12215     TautologicalTypeCompare = true;
12216 
12217   // If this is a comparison to an enum constant, include that
12218   // constant in the diagnostic.
12219   const EnumConstantDecl *ED = nullptr;
12220   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
12221     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12222 
12223   // Should be enough for uint128 (39 decimal digits)
12224   SmallString<64> PrettySourceValue;
12225   llvm::raw_svector_ostream OS(PrettySourceValue);
12226   if (ED) {
12227     OS << '\'' << *ED << "' (" << Value << ")";
12228   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12229                Constant->IgnoreParenImpCasts())) {
12230     OS << (BL->getValue() ? "YES" : "NO");
12231   } else {
12232     OS << Value;
12233   }
12234 
12235   if (!TautologicalTypeCompare) {
12236     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12237         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
12238         << E->getOpcodeStr() << OS.str() << *Result
12239         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12240     return true;
12241   }
12242 
12243   if (IsObjCSignedCharBool) {
12244     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12245                           S.PDiag(diag::warn_tautological_compare_objc_bool)
12246                               << OS.str() << *Result);
12247     return true;
12248   }
12249 
12250   // FIXME: We use a somewhat different formatting for the in-range cases and
12251   // cases involving boolean values for historical reasons. We should pick a
12252   // consistent way of presenting these diagnostics.
12253   if (!InRange || Other->isKnownToHaveBooleanValue()) {
12254 
12255     S.DiagRuntimeBehavior(
12256         E->getOperatorLoc(), E,
12257         S.PDiag(!InRange ? diag::warn_out_of_range_compare
12258                          : diag::warn_tautological_bool_compare)
12259             << OS.str() << classifyConstantValue(Constant) << OtherT
12260             << OtherIsBooleanDespiteType << *Result
12261             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12262   } else {
12263     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12264     unsigned Diag =
12265         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12266             ? (HasEnumType(OriginalOther)
12267                    ? diag::warn_unsigned_enum_always_true_comparison
12268                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12269                               : diag::warn_unsigned_always_true_comparison)
12270             : diag::warn_tautological_constant_compare;
12271 
12272     S.Diag(E->getOperatorLoc(), Diag)
12273         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12274         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12275   }
12276 
12277   return true;
12278 }
12279 
12280 /// Analyze the operands of the given comparison.  Implements the
12281 /// fallback case from AnalyzeComparison.
12282 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12283   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12284   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12285 }
12286 
12287 /// Implements -Wsign-compare.
12288 ///
12289 /// \param E the binary operator to check for warnings
12290 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12291   // The type the comparison is being performed in.
12292   QualType T = E->getLHS()->getType();
12293 
12294   // Only analyze comparison operators where both sides have been converted to
12295   // the same type.
12296   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12297     return AnalyzeImpConvsInComparison(S, E);
12298 
12299   // Don't analyze value-dependent comparisons directly.
12300   if (E->isValueDependent())
12301     return AnalyzeImpConvsInComparison(S, E);
12302 
12303   Expr *LHS = E->getLHS();
12304   Expr *RHS = E->getRHS();
12305 
12306   if (T->isIntegralType(S.Context)) {
12307     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
12308     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
12309 
12310     // We don't care about expressions whose result is a constant.
12311     if (RHSValue && LHSValue)
12312       return AnalyzeImpConvsInComparison(S, E);
12313 
12314     // We only care about expressions where just one side is literal
12315     if ((bool)RHSValue ^ (bool)LHSValue) {
12316       // Is the constant on the RHS or LHS?
12317       const bool RhsConstant = (bool)RHSValue;
12318       Expr *Const = RhsConstant ? RHS : LHS;
12319       Expr *Other = RhsConstant ? LHS : RHS;
12320       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12321 
12322       // Check whether an integer constant comparison results in a value
12323       // of 'true' or 'false'.
12324       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12325         return AnalyzeImpConvsInComparison(S, E);
12326     }
12327   }
12328 
12329   if (!T->hasUnsignedIntegerRepresentation()) {
12330     // We don't do anything special if this isn't an unsigned integral
12331     // comparison:  we're only interested in integral comparisons, and
12332     // signed comparisons only happen in cases we don't care to warn about.
12333     return AnalyzeImpConvsInComparison(S, E);
12334   }
12335 
12336   LHS = LHS->IgnoreParenImpCasts();
12337   RHS = RHS->IgnoreParenImpCasts();
12338 
12339   if (!S.getLangOpts().CPlusPlus) {
12340     // Avoid warning about comparison of integers with different signs when
12341     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12342     // the type of `E`.
12343     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12344       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12345     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12346       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12347   }
12348 
12349   // Check to see if one of the (unmodified) operands is of different
12350   // signedness.
12351   Expr *signedOperand, *unsignedOperand;
12352   if (LHS->getType()->hasSignedIntegerRepresentation()) {
12353     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12354            "unsigned comparison between two signed integer expressions?");
12355     signedOperand = LHS;
12356     unsignedOperand = RHS;
12357   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12358     signedOperand = RHS;
12359     unsignedOperand = LHS;
12360   } else {
12361     return AnalyzeImpConvsInComparison(S, E);
12362   }
12363 
12364   // Otherwise, calculate the effective range of the signed operand.
12365   IntRange signedRange = GetExprRange(
12366       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
12367 
12368   // Go ahead and analyze implicit conversions in the operands.  Note
12369   // that we skip the implicit conversions on both sides.
12370   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
12371   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
12372 
12373   // If the signed range is non-negative, -Wsign-compare won't fire.
12374   if (signedRange.NonNegative)
12375     return;
12376 
12377   // For (in)equality comparisons, if the unsigned operand is a
12378   // constant which cannot collide with a overflowed signed operand,
12379   // then reinterpreting the signed operand as unsigned will not
12380   // change the result of the comparison.
12381   if (E->isEqualityOp()) {
12382     unsigned comparisonWidth = S.Context.getIntWidth(T);
12383     IntRange unsignedRange =
12384         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
12385                      /*Approximate*/ true);
12386 
12387     // We should never be unable to prove that the unsigned operand is
12388     // non-negative.
12389     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
12390 
12391     if (unsignedRange.Width < comparisonWidth)
12392       return;
12393   }
12394 
12395   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12396                         S.PDiag(diag::warn_mixed_sign_comparison)
12397                             << LHS->getType() << RHS->getType()
12398                             << LHS->getSourceRange() << RHS->getSourceRange());
12399 }
12400 
12401 /// Analyzes an attempt to assign the given value to a bitfield.
12402 ///
12403 /// Returns true if there was something fishy about the attempt.
12404 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12405                                       SourceLocation InitLoc) {
12406   assert(Bitfield->isBitField());
12407   if (Bitfield->isInvalidDecl())
12408     return false;
12409 
12410   // White-list bool bitfields.
12411   QualType BitfieldType = Bitfield->getType();
12412   if (BitfieldType->isBooleanType())
12413      return false;
12414 
12415   if (BitfieldType->isEnumeralType()) {
12416     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12417     // If the underlying enum type was not explicitly specified as an unsigned
12418     // type and the enum contain only positive values, MSVC++ will cause an
12419     // inconsistency by storing this as a signed type.
12420     if (S.getLangOpts().CPlusPlus11 &&
12421         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12422         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12423         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12424       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12425           << BitfieldEnumDecl;
12426     }
12427   }
12428 
12429   if (Bitfield->getType()->isBooleanType())
12430     return false;
12431 
12432   // Ignore value- or type-dependent expressions.
12433   if (Bitfield->getBitWidth()->isValueDependent() ||
12434       Bitfield->getBitWidth()->isTypeDependent() ||
12435       Init->isValueDependent() ||
12436       Init->isTypeDependent())
12437     return false;
12438 
12439   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12440   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12441 
12442   Expr::EvalResult Result;
12443   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12444                                    Expr::SE_AllowSideEffects)) {
12445     // The RHS is not constant.  If the RHS has an enum type, make sure the
12446     // bitfield is wide enough to hold all the values of the enum without
12447     // truncation.
12448     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12449       EnumDecl *ED = EnumTy->getDecl();
12450       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12451 
12452       // Enum types are implicitly signed on Windows, so check if there are any
12453       // negative enumerators to see if the enum was intended to be signed or
12454       // not.
12455       bool SignedEnum = ED->getNumNegativeBits() > 0;
12456 
12457       // Check for surprising sign changes when assigning enum values to a
12458       // bitfield of different signedness.  If the bitfield is signed and we
12459       // have exactly the right number of bits to store this unsigned enum,
12460       // suggest changing the enum to an unsigned type. This typically happens
12461       // on Windows where unfixed enums always use an underlying type of 'int'.
12462       unsigned DiagID = 0;
12463       if (SignedEnum && !SignedBitfield) {
12464         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12465       } else if (SignedBitfield && !SignedEnum &&
12466                  ED->getNumPositiveBits() == FieldWidth) {
12467         DiagID = diag::warn_signed_bitfield_enum_conversion;
12468       }
12469 
12470       if (DiagID) {
12471         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12472         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12473         SourceRange TypeRange =
12474             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12475         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12476             << SignedEnum << TypeRange;
12477       }
12478 
12479       // Compute the required bitwidth. If the enum has negative values, we need
12480       // one more bit than the normal number of positive bits to represent the
12481       // sign bit.
12482       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12483                                                   ED->getNumNegativeBits())
12484                                        : ED->getNumPositiveBits();
12485 
12486       // Check the bitwidth.
12487       if (BitsNeeded > FieldWidth) {
12488         Expr *WidthExpr = Bitfield->getBitWidth();
12489         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12490             << Bitfield << ED;
12491         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12492             << BitsNeeded << ED << WidthExpr->getSourceRange();
12493       }
12494     }
12495 
12496     return false;
12497   }
12498 
12499   llvm::APSInt Value = Result.Val.getInt();
12500 
12501   unsigned OriginalWidth = Value.getBitWidth();
12502 
12503   if (!Value.isSigned() || Value.isNegative())
12504     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12505       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12506         OriginalWidth = Value.getMinSignedBits();
12507 
12508   if (OriginalWidth <= FieldWidth)
12509     return false;
12510 
12511   // Compute the value which the bitfield will contain.
12512   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12513   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12514 
12515   // Check whether the stored value is equal to the original value.
12516   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12517   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12518     return false;
12519 
12520   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12521   // therefore don't strictly fit into a signed bitfield of width 1.
12522   if (FieldWidth == 1 && Value == 1)
12523     return false;
12524 
12525   std::string PrettyValue = toString(Value, 10);
12526   std::string PrettyTrunc = toString(TruncatedValue, 10);
12527 
12528   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12529     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12530     << Init->getSourceRange();
12531 
12532   return true;
12533 }
12534 
12535 /// Analyze the given simple or compound assignment for warning-worthy
12536 /// operations.
12537 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12538   // Just recurse on the LHS.
12539   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12540 
12541   // We want to recurse on the RHS as normal unless we're assigning to
12542   // a bitfield.
12543   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12544     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12545                                   E->getOperatorLoc())) {
12546       // Recurse, ignoring any implicit conversions on the RHS.
12547       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12548                                         E->getOperatorLoc());
12549     }
12550   }
12551 
12552   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12553 
12554   // Diagnose implicitly sequentially-consistent atomic assignment.
12555   if (E->getLHS()->getType()->isAtomicType())
12556     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12557 }
12558 
12559 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12560 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12561                             SourceLocation CContext, unsigned diag,
12562                             bool pruneControlFlow = false) {
12563   if (pruneControlFlow) {
12564     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12565                           S.PDiag(diag)
12566                               << SourceType << T << E->getSourceRange()
12567                               << SourceRange(CContext));
12568     return;
12569   }
12570   S.Diag(E->getExprLoc(), diag)
12571     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12572 }
12573 
12574 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12575 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12576                             SourceLocation CContext,
12577                             unsigned diag, bool pruneControlFlow = false) {
12578   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12579 }
12580 
12581 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12582   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12583       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12584 }
12585 
12586 static void adornObjCBoolConversionDiagWithTernaryFixit(
12587     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12588   Expr *Ignored = SourceExpr->IgnoreImplicit();
12589   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12590     Ignored = OVE->getSourceExpr();
12591   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12592                      isa<BinaryOperator>(Ignored) ||
12593                      isa<CXXOperatorCallExpr>(Ignored);
12594   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12595   if (NeedsParens)
12596     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12597             << FixItHint::CreateInsertion(EndLoc, ")");
12598   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12599 }
12600 
12601 /// Diagnose an implicit cast from a floating point value to an integer value.
12602 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12603                                     SourceLocation CContext) {
12604   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12605   const bool PruneWarnings = S.inTemplateInstantiation();
12606 
12607   Expr *InnerE = E->IgnoreParenImpCasts();
12608   // We also want to warn on, e.g., "int i = -1.234"
12609   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12610     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12611       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12612 
12613   const bool IsLiteral =
12614       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12615 
12616   llvm::APFloat Value(0.0);
12617   bool IsConstant =
12618     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12619   if (!IsConstant) {
12620     if (isObjCSignedCharBool(S, T)) {
12621       return adornObjCBoolConversionDiagWithTernaryFixit(
12622           S, E,
12623           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12624               << E->getType());
12625     }
12626 
12627     return DiagnoseImpCast(S, E, T, CContext,
12628                            diag::warn_impcast_float_integer, PruneWarnings);
12629   }
12630 
12631   bool isExact = false;
12632 
12633   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12634                             T->hasUnsignedIntegerRepresentation());
12635   llvm::APFloat::opStatus Result = Value.convertToInteger(
12636       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12637 
12638   // FIXME: Force the precision of the source value down so we don't print
12639   // digits which are usually useless (we don't really care here if we
12640   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12641   // would automatically print the shortest representation, but it's a bit
12642   // tricky to implement.
12643   SmallString<16> PrettySourceValue;
12644   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12645   precision = (precision * 59 + 195) / 196;
12646   Value.toString(PrettySourceValue, precision);
12647 
12648   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12649     return adornObjCBoolConversionDiagWithTernaryFixit(
12650         S, E,
12651         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12652             << PrettySourceValue);
12653   }
12654 
12655   if (Result == llvm::APFloat::opOK && isExact) {
12656     if (IsLiteral) return;
12657     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12658                            PruneWarnings);
12659   }
12660 
12661   // Conversion of a floating-point value to a non-bool integer where the
12662   // integral part cannot be represented by the integer type is undefined.
12663   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12664     return DiagnoseImpCast(
12665         S, E, T, CContext,
12666         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12667                   : diag::warn_impcast_float_to_integer_out_of_range,
12668         PruneWarnings);
12669 
12670   unsigned DiagID = 0;
12671   if (IsLiteral) {
12672     // Warn on floating point literal to integer.
12673     DiagID = diag::warn_impcast_literal_float_to_integer;
12674   } else if (IntegerValue == 0) {
12675     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12676       return DiagnoseImpCast(S, E, T, CContext,
12677                              diag::warn_impcast_float_integer, PruneWarnings);
12678     }
12679     // Warn on non-zero to zero conversion.
12680     DiagID = diag::warn_impcast_float_to_integer_zero;
12681   } else {
12682     if (IntegerValue.isUnsigned()) {
12683       if (!IntegerValue.isMaxValue()) {
12684         return DiagnoseImpCast(S, E, T, CContext,
12685                                diag::warn_impcast_float_integer, PruneWarnings);
12686       }
12687     } else {  // IntegerValue.isSigned()
12688       if (!IntegerValue.isMaxSignedValue() &&
12689           !IntegerValue.isMinSignedValue()) {
12690         return DiagnoseImpCast(S, E, T, CContext,
12691                                diag::warn_impcast_float_integer, PruneWarnings);
12692       }
12693     }
12694     // Warn on evaluatable floating point expression to integer conversion.
12695     DiagID = diag::warn_impcast_float_to_integer;
12696   }
12697 
12698   SmallString<16> PrettyTargetValue;
12699   if (IsBool)
12700     PrettyTargetValue = Value.isZero() ? "false" : "true";
12701   else
12702     IntegerValue.toString(PrettyTargetValue);
12703 
12704   if (PruneWarnings) {
12705     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12706                           S.PDiag(DiagID)
12707                               << E->getType() << T.getUnqualifiedType()
12708                               << PrettySourceValue << PrettyTargetValue
12709                               << E->getSourceRange() << SourceRange(CContext));
12710   } else {
12711     S.Diag(E->getExprLoc(), DiagID)
12712         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12713         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12714   }
12715 }
12716 
12717 /// Analyze the given compound assignment for the possible losing of
12718 /// floating-point precision.
12719 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12720   assert(isa<CompoundAssignOperator>(E) &&
12721          "Must be compound assignment operation");
12722   // Recurse on the LHS and RHS in here
12723   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12724   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12725 
12726   if (E->getLHS()->getType()->isAtomicType())
12727     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12728 
12729   // Now check the outermost expression
12730   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12731   const auto *RBT = cast<CompoundAssignOperator>(E)
12732                         ->getComputationResultType()
12733                         ->getAs<BuiltinType>();
12734 
12735   // The below checks assume source is floating point.
12736   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12737 
12738   // If source is floating point but target is an integer.
12739   if (ResultBT->isInteger())
12740     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12741                            E->getExprLoc(), diag::warn_impcast_float_integer);
12742 
12743   if (!ResultBT->isFloatingPoint())
12744     return;
12745 
12746   // If both source and target are floating points, warn about losing precision.
12747   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12748       QualType(ResultBT, 0), QualType(RBT, 0));
12749   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12750     // warn about dropping FP rank.
12751     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12752                     diag::warn_impcast_float_result_precision);
12753 }
12754 
12755 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12756                                       IntRange Range) {
12757   if (!Range.Width) return "0";
12758 
12759   llvm::APSInt ValueInRange = Value;
12760   ValueInRange.setIsSigned(!Range.NonNegative);
12761   ValueInRange = ValueInRange.trunc(Range.Width);
12762   return toString(ValueInRange, 10);
12763 }
12764 
12765 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12766   if (!isa<ImplicitCastExpr>(Ex))
12767     return false;
12768 
12769   Expr *InnerE = Ex->IgnoreParenImpCasts();
12770   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12771   const Type *Source =
12772     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12773   if (Target->isDependentType())
12774     return false;
12775 
12776   const BuiltinType *FloatCandidateBT =
12777     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12778   const Type *BoolCandidateType = ToBool ? Target : Source;
12779 
12780   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12781           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12782 }
12783 
12784 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12785                                              SourceLocation CC) {
12786   unsigned NumArgs = TheCall->getNumArgs();
12787   for (unsigned i = 0; i < NumArgs; ++i) {
12788     Expr *CurrA = TheCall->getArg(i);
12789     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12790       continue;
12791 
12792     bool IsSwapped = ((i > 0) &&
12793         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12794     IsSwapped |= ((i < (NumArgs - 1)) &&
12795         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12796     if (IsSwapped) {
12797       // Warn on this floating-point to bool conversion.
12798       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12799                       CurrA->getType(), CC,
12800                       diag::warn_impcast_floating_point_to_bool);
12801     }
12802   }
12803 }
12804 
12805 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12806                                    SourceLocation CC) {
12807   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12808                         E->getExprLoc()))
12809     return;
12810 
12811   // Don't warn on functions which have return type nullptr_t.
12812   if (isa<CallExpr>(E))
12813     return;
12814 
12815   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12816   const Expr::NullPointerConstantKind NullKind =
12817       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12818   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12819     return;
12820 
12821   // Return if target type is a safe conversion.
12822   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12823       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12824     return;
12825 
12826   SourceLocation Loc = E->getSourceRange().getBegin();
12827 
12828   // Venture through the macro stacks to get to the source of macro arguments.
12829   // The new location is a better location than the complete location that was
12830   // passed in.
12831   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12832   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12833 
12834   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12835   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12836     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12837         Loc, S.SourceMgr, S.getLangOpts());
12838     if (MacroName == "NULL")
12839       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12840   }
12841 
12842   // Only warn if the null and context location are in the same macro expansion.
12843   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12844     return;
12845 
12846   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12847       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12848       << FixItHint::CreateReplacement(Loc,
12849                                       S.getFixItZeroLiteralForType(T, Loc));
12850 }
12851 
12852 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12853                                   ObjCArrayLiteral *ArrayLiteral);
12854 
12855 static void
12856 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12857                            ObjCDictionaryLiteral *DictionaryLiteral);
12858 
12859 /// Check a single element within a collection literal against the
12860 /// target element type.
12861 static void checkObjCCollectionLiteralElement(Sema &S,
12862                                               QualType TargetElementType,
12863                                               Expr *Element,
12864                                               unsigned ElementKind) {
12865   // Skip a bitcast to 'id' or qualified 'id'.
12866   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12867     if (ICE->getCastKind() == CK_BitCast &&
12868         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12869       Element = ICE->getSubExpr();
12870   }
12871 
12872   QualType ElementType = Element->getType();
12873   ExprResult ElementResult(Element);
12874   if (ElementType->getAs<ObjCObjectPointerType>() &&
12875       S.CheckSingleAssignmentConstraints(TargetElementType,
12876                                          ElementResult,
12877                                          false, false)
12878         != Sema::Compatible) {
12879     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12880         << ElementType << ElementKind << TargetElementType
12881         << Element->getSourceRange();
12882   }
12883 
12884   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12885     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12886   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12887     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12888 }
12889 
12890 /// Check an Objective-C array literal being converted to the given
12891 /// target type.
12892 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12893                                   ObjCArrayLiteral *ArrayLiteral) {
12894   if (!S.NSArrayDecl)
12895     return;
12896 
12897   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12898   if (!TargetObjCPtr)
12899     return;
12900 
12901   if (TargetObjCPtr->isUnspecialized() ||
12902       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12903         != S.NSArrayDecl->getCanonicalDecl())
12904     return;
12905 
12906   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12907   if (TypeArgs.size() != 1)
12908     return;
12909 
12910   QualType TargetElementType = TypeArgs[0];
12911   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12912     checkObjCCollectionLiteralElement(S, TargetElementType,
12913                                       ArrayLiteral->getElement(I),
12914                                       0);
12915   }
12916 }
12917 
12918 /// Check an Objective-C dictionary literal being converted to the given
12919 /// target type.
12920 static void
12921 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12922                            ObjCDictionaryLiteral *DictionaryLiteral) {
12923   if (!S.NSDictionaryDecl)
12924     return;
12925 
12926   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12927   if (!TargetObjCPtr)
12928     return;
12929 
12930   if (TargetObjCPtr->isUnspecialized() ||
12931       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12932         != S.NSDictionaryDecl->getCanonicalDecl())
12933     return;
12934 
12935   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12936   if (TypeArgs.size() != 2)
12937     return;
12938 
12939   QualType TargetKeyType = TypeArgs[0];
12940   QualType TargetObjectType = TypeArgs[1];
12941   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12942     auto Element = DictionaryLiteral->getKeyValueElement(I);
12943     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12944     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12945   }
12946 }
12947 
12948 // Helper function to filter out cases for constant width constant conversion.
12949 // Don't warn on char array initialization or for non-decimal values.
12950 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12951                                           SourceLocation CC) {
12952   // If initializing from a constant, and the constant starts with '0',
12953   // then it is a binary, octal, or hexadecimal.  Allow these constants
12954   // to fill all the bits, even if there is a sign change.
12955   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12956     const char FirstLiteralCharacter =
12957         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12958     if (FirstLiteralCharacter == '0')
12959       return false;
12960   }
12961 
12962   // If the CC location points to a '{', and the type is char, then assume
12963   // assume it is an array initialization.
12964   if (CC.isValid() && T->isCharType()) {
12965     const char FirstContextCharacter =
12966         S.getSourceManager().getCharacterData(CC)[0];
12967     if (FirstContextCharacter == '{')
12968       return false;
12969   }
12970 
12971   return true;
12972 }
12973 
12974 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12975   const auto *IL = dyn_cast<IntegerLiteral>(E);
12976   if (!IL) {
12977     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12978       if (UO->getOpcode() == UO_Minus)
12979         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12980     }
12981   }
12982 
12983   return IL;
12984 }
12985 
12986 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12987   E = E->IgnoreParenImpCasts();
12988   SourceLocation ExprLoc = E->getExprLoc();
12989 
12990   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12991     BinaryOperator::Opcode Opc = BO->getOpcode();
12992     Expr::EvalResult Result;
12993     // Do not diagnose unsigned shifts.
12994     if (Opc == BO_Shl) {
12995       const auto *LHS = getIntegerLiteral(BO->getLHS());
12996       const auto *RHS = getIntegerLiteral(BO->getRHS());
12997       if (LHS && LHS->getValue() == 0)
12998         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12999       else if (!E->isValueDependent() && LHS && RHS &&
13000                RHS->getValue().isNonNegative() &&
13001                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
13002         S.Diag(ExprLoc, diag::warn_left_shift_always)
13003             << (Result.Val.getInt() != 0);
13004       else if (E->getType()->isSignedIntegerType())
13005         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
13006     }
13007   }
13008 
13009   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
13010     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
13011     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
13012     if (!LHS || !RHS)
13013       return;
13014     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13015         (RHS->getValue() == 0 || RHS->getValue() == 1))
13016       // Do not diagnose common idioms.
13017       return;
13018     if (LHS->getValue() != 0 && RHS->getValue() != 0)
13019       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
13020   }
13021 }
13022 
13023 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
13024                                     SourceLocation CC,
13025                                     bool *ICContext = nullptr,
13026                                     bool IsListInit = false) {
13027   if (E->isTypeDependent() || E->isValueDependent()) return;
13028 
13029   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
13030   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
13031   if (Source == Target) return;
13032   if (Target->isDependentType()) return;
13033 
13034   // If the conversion context location is invalid don't complain. We also
13035   // don't want to emit a warning if the issue occurs from the expansion of
13036   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13037   // delay this check as long as possible. Once we detect we are in that
13038   // scenario, we just return.
13039   if (CC.isInvalid())
13040     return;
13041 
13042   if (Source->isAtomicType())
13043     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
13044 
13045   // Diagnose implicit casts to bool.
13046   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
13047     if (isa<StringLiteral>(E))
13048       // Warn on string literal to bool.  Checks for string literals in logical
13049       // and expressions, for instance, assert(0 && "error here"), are
13050       // prevented by a check in AnalyzeImplicitConversions().
13051       return DiagnoseImpCast(S, E, T, CC,
13052                              diag::warn_impcast_string_literal_to_bool);
13053     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
13054         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
13055       // This covers the literal expressions that evaluate to Objective-C
13056       // objects.
13057       return DiagnoseImpCast(S, E, T, CC,
13058                              diag::warn_impcast_objective_c_literal_to_bool);
13059     }
13060     if (Source->isPointerType() || Source->canDecayToPointerType()) {
13061       // Warn on pointer to bool conversion that is always true.
13062       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
13063                                      SourceRange(CC));
13064     }
13065   }
13066 
13067   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13068   // is a typedef for signed char (macOS), then that constant value has to be 1
13069   // or 0.
13070   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
13071     Expr::EvalResult Result;
13072     if (E->EvaluateAsInt(Result, S.getASTContext(),
13073                          Expr::SE_AllowSideEffects)) {
13074       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13075         adornObjCBoolConversionDiagWithTernaryFixit(
13076             S, E,
13077             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13078                 << toString(Result.Val.getInt(), 10));
13079       }
13080       return;
13081     }
13082   }
13083 
13084   // Check implicit casts from Objective-C collection literals to specialized
13085   // collection types, e.g., NSArray<NSString *> *.
13086   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13087     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
13088   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13089     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
13090 
13091   // Strip vector types.
13092   if (isa<VectorType>(Source)) {
13093     if (Target->isVLSTBuiltinType() &&
13094         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
13095                                          QualType(Source, 0)) ||
13096          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
13097                                             QualType(Source, 0))))
13098       return;
13099 
13100     if (!isa<VectorType>(Target)) {
13101       if (S.SourceMgr.isInSystemMacro(CC))
13102         return;
13103       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
13104     }
13105 
13106     // If the vector cast is cast between two vectors of the same size, it is
13107     // a bitcast, not a conversion.
13108     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
13109       return;
13110 
13111     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13112     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13113   }
13114   if (auto VecTy = dyn_cast<VectorType>(Target))
13115     Target = VecTy->getElementType().getTypePtr();
13116 
13117   // Strip complex types.
13118   if (isa<ComplexType>(Source)) {
13119     if (!isa<ComplexType>(Target)) {
13120       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13121         return;
13122 
13123       return DiagnoseImpCast(S, E, T, CC,
13124                              S.getLangOpts().CPlusPlus
13125                                  ? diag::err_impcast_complex_scalar
13126                                  : diag::warn_impcast_complex_scalar);
13127     }
13128 
13129     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13130     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13131   }
13132 
13133   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13134   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13135 
13136   // If the source is floating point...
13137   if (SourceBT && SourceBT->isFloatingPoint()) {
13138     // ...and the target is floating point...
13139     if (TargetBT && TargetBT->isFloatingPoint()) {
13140       // ...then warn if we're dropping FP rank.
13141 
13142       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
13143           QualType(SourceBT, 0), QualType(TargetBT, 0));
13144       if (Order > 0) {
13145         // Don't warn about float constants that are precisely
13146         // representable in the target type.
13147         Expr::EvalResult result;
13148         if (E->EvaluateAsRValue(result, S.Context)) {
13149           // Value might be a float, a float vector, or a float complex.
13150           if (IsSameFloatAfterCast(result.Val,
13151                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13152                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13153             return;
13154         }
13155 
13156         if (S.SourceMgr.isInSystemMacro(CC))
13157           return;
13158 
13159         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
13160       }
13161       // ... or possibly if we're increasing rank, too
13162       else if (Order < 0) {
13163         if (S.SourceMgr.isInSystemMacro(CC))
13164           return;
13165 
13166         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
13167       }
13168       return;
13169     }
13170 
13171     // If the target is integral, always warn.
13172     if (TargetBT && TargetBT->isInteger()) {
13173       if (S.SourceMgr.isInSystemMacro(CC))
13174         return;
13175 
13176       DiagnoseFloatingImpCast(S, E, T, CC);
13177     }
13178 
13179     // Detect the case where a call result is converted from floating-point to
13180     // to bool, and the final argument to the call is converted from bool, to
13181     // discover this typo:
13182     //
13183     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
13184     //
13185     // FIXME: This is an incredibly special case; is there some more general
13186     // way to detect this class of misplaced-parentheses bug?
13187     if (Target->isBooleanType() && isa<CallExpr>(E)) {
13188       // Check last argument of function call to see if it is an
13189       // implicit cast from a type matching the type the result
13190       // is being cast to.
13191       CallExpr *CEx = cast<CallExpr>(E);
13192       if (unsigned NumArgs = CEx->getNumArgs()) {
13193         Expr *LastA = CEx->getArg(NumArgs - 1);
13194         Expr *InnerE = LastA->IgnoreParenImpCasts();
13195         if (isa<ImplicitCastExpr>(LastA) &&
13196             InnerE->getType()->isBooleanType()) {
13197           // Warn on this floating-point to bool conversion
13198           DiagnoseImpCast(S, E, T, CC,
13199                           diag::warn_impcast_floating_point_to_bool);
13200         }
13201       }
13202     }
13203     return;
13204   }
13205 
13206   // Valid casts involving fixed point types should be accounted for here.
13207   if (Source->isFixedPointType()) {
13208     if (Target->isUnsaturatedFixedPointType()) {
13209       Expr::EvalResult Result;
13210       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
13211                                   S.isConstantEvaluated())) {
13212         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13213         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
13214         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
13215         if (Value > MaxVal || Value < MinVal) {
13216           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13217                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13218                                     << Value.toString() << T
13219                                     << E->getSourceRange()
13220                                     << clang::SourceRange(CC));
13221           return;
13222         }
13223       }
13224     } else if (Target->isIntegerType()) {
13225       Expr::EvalResult Result;
13226       if (!S.isConstantEvaluated() &&
13227           E->EvaluateAsFixedPoint(Result, S.Context,
13228                                   Expr::SE_AllowSideEffects)) {
13229         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13230 
13231         bool Overflowed;
13232         llvm::APSInt IntResult = FXResult.convertToInt(
13233             S.Context.getIntWidth(T),
13234             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
13235 
13236         if (Overflowed) {
13237           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13238                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13239                                     << FXResult.toString() << T
13240                                     << E->getSourceRange()
13241                                     << clang::SourceRange(CC));
13242           return;
13243         }
13244       }
13245     }
13246   } else if (Target->isUnsaturatedFixedPointType()) {
13247     if (Source->isIntegerType()) {
13248       Expr::EvalResult Result;
13249       if (!S.isConstantEvaluated() &&
13250           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
13251         llvm::APSInt Value = Result.Val.getInt();
13252 
13253         bool Overflowed;
13254         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13255             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
13256 
13257         if (Overflowed) {
13258           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13259                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13260                                     << toString(Value, /*Radix=*/10) << T
13261                                     << E->getSourceRange()
13262                                     << clang::SourceRange(CC));
13263           return;
13264         }
13265       }
13266     }
13267   }
13268 
13269   // If we are casting an integer type to a floating point type without
13270   // initialization-list syntax, we might lose accuracy if the floating
13271   // point type has a narrower significand than the integer type.
13272   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13273       TargetBT->isFloatingType() && !IsListInit) {
13274     // Determine the number of precision bits in the source integer type.
13275     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
13276                                         /*Approximate*/ true);
13277     unsigned int SourcePrecision = SourceRange.Width;
13278 
13279     // Determine the number of precision bits in the
13280     // target floating point type.
13281     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13282         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13283 
13284     if (SourcePrecision > 0 && TargetPrecision > 0 &&
13285         SourcePrecision > TargetPrecision) {
13286 
13287       if (Optional<llvm::APSInt> SourceInt =
13288               E->getIntegerConstantExpr(S.Context)) {
13289         // If the source integer is a constant, convert it to the target
13290         // floating point type. Issue a warning if the value changes
13291         // during the whole conversion.
13292         llvm::APFloat TargetFloatValue(
13293             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13294         llvm::APFloat::opStatus ConversionStatus =
13295             TargetFloatValue.convertFromAPInt(
13296                 *SourceInt, SourceBT->isSignedInteger(),
13297                 llvm::APFloat::rmNearestTiesToEven);
13298 
13299         if (ConversionStatus != llvm::APFloat::opOK) {
13300           SmallString<32> PrettySourceValue;
13301           SourceInt->toString(PrettySourceValue, 10);
13302           SmallString<32> PrettyTargetValue;
13303           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13304 
13305           S.DiagRuntimeBehavior(
13306               E->getExprLoc(), E,
13307               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
13308                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
13309                   << E->getSourceRange() << clang::SourceRange(CC));
13310         }
13311       } else {
13312         // Otherwise, the implicit conversion may lose precision.
13313         DiagnoseImpCast(S, E, T, CC,
13314                         diag::warn_impcast_integer_float_precision);
13315       }
13316     }
13317   }
13318 
13319   DiagnoseNullConversion(S, E, T, CC);
13320 
13321   S.DiscardMisalignedMemberAddress(Target, E);
13322 
13323   if (Target->isBooleanType())
13324     DiagnoseIntInBoolContext(S, E);
13325 
13326   if (!Source->isIntegerType() || !Target->isIntegerType())
13327     return;
13328 
13329   // TODO: remove this early return once the false positives for constant->bool
13330   // in templates, macros, etc, are reduced or removed.
13331   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13332     return;
13333 
13334   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
13335       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13336     return adornObjCBoolConversionDiagWithTernaryFixit(
13337         S, E,
13338         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13339             << E->getType());
13340   }
13341 
13342   IntRange SourceTypeRange =
13343       IntRange::forTargetOfCanonicalType(S.Context, Source);
13344   IntRange LikelySourceRange =
13345       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
13346   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
13347 
13348   if (LikelySourceRange.Width > TargetRange.Width) {
13349     // If the source is a constant, use a default-on diagnostic.
13350     // TODO: this should happen for bitfield stores, too.
13351     Expr::EvalResult Result;
13352     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
13353                          S.isConstantEvaluated())) {
13354       llvm::APSInt Value(32);
13355       Value = Result.Val.getInt();
13356 
13357       if (S.SourceMgr.isInSystemMacro(CC))
13358         return;
13359 
13360       std::string PrettySourceValue = toString(Value, 10);
13361       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13362 
13363       S.DiagRuntimeBehavior(
13364           E->getExprLoc(), E,
13365           S.PDiag(diag::warn_impcast_integer_precision_constant)
13366               << PrettySourceValue << PrettyTargetValue << E->getType() << T
13367               << E->getSourceRange() << SourceRange(CC));
13368       return;
13369     }
13370 
13371     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13372     if (S.SourceMgr.isInSystemMacro(CC))
13373       return;
13374 
13375     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
13376       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
13377                              /* pruneControlFlow */ true);
13378     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
13379   }
13380 
13381   if (TargetRange.Width > SourceTypeRange.Width) {
13382     if (auto *UO = dyn_cast<UnaryOperator>(E))
13383       if (UO->getOpcode() == UO_Minus)
13384         if (Source->isUnsignedIntegerType()) {
13385           if (Target->isUnsignedIntegerType())
13386             return DiagnoseImpCast(S, E, T, CC,
13387                                    diag::warn_impcast_high_order_zero_bits);
13388           if (Target->isSignedIntegerType())
13389             return DiagnoseImpCast(S, E, T, CC,
13390                                    diag::warn_impcast_nonnegative_result);
13391         }
13392   }
13393 
13394   if (TargetRange.Width == LikelySourceRange.Width &&
13395       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13396       Source->isSignedIntegerType()) {
13397     // Warn when doing a signed to signed conversion, warn if the positive
13398     // source value is exactly the width of the target type, which will
13399     // cause a negative value to be stored.
13400 
13401     Expr::EvalResult Result;
13402     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
13403         !S.SourceMgr.isInSystemMacro(CC)) {
13404       llvm::APSInt Value = Result.Val.getInt();
13405       if (isSameWidthConstantConversion(S, E, T, CC)) {
13406         std::string PrettySourceValue = toString(Value, 10);
13407         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13408 
13409         S.DiagRuntimeBehavior(
13410             E->getExprLoc(), E,
13411             S.PDiag(diag::warn_impcast_integer_precision_constant)
13412                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13413                 << E->getSourceRange() << SourceRange(CC));
13414         return;
13415       }
13416     }
13417 
13418     // Fall through for non-constants to give a sign conversion warning.
13419   }
13420 
13421   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13422       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13423        LikelySourceRange.Width == TargetRange.Width)) {
13424     if (S.SourceMgr.isInSystemMacro(CC))
13425       return;
13426 
13427     unsigned DiagID = diag::warn_impcast_integer_sign;
13428 
13429     // Traditionally, gcc has warned about this under -Wsign-compare.
13430     // We also want to warn about it in -Wconversion.
13431     // So if -Wconversion is off, use a completely identical diagnostic
13432     // in the sign-compare group.
13433     // The conditional-checking code will
13434     if (ICContext) {
13435       DiagID = diag::warn_impcast_integer_sign_conditional;
13436       *ICContext = true;
13437     }
13438 
13439     return DiagnoseImpCast(S, E, T, CC, DiagID);
13440   }
13441 
13442   // Diagnose conversions between different enumeration types.
13443   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13444   // type, to give us better diagnostics.
13445   QualType SourceType = E->getType();
13446   if (!S.getLangOpts().CPlusPlus) {
13447     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13448       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13449         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13450         SourceType = S.Context.getTypeDeclType(Enum);
13451         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13452       }
13453   }
13454 
13455   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13456     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13457       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13458           TargetEnum->getDecl()->hasNameForLinkage() &&
13459           SourceEnum != TargetEnum) {
13460         if (S.SourceMgr.isInSystemMacro(CC))
13461           return;
13462 
13463         return DiagnoseImpCast(S, E, SourceType, T, CC,
13464                                diag::warn_impcast_different_enum_types);
13465       }
13466 }
13467 
13468 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13469                                      SourceLocation CC, QualType T);
13470 
13471 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13472                                     SourceLocation CC, bool &ICContext) {
13473   E = E->IgnoreParenImpCasts();
13474 
13475   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13476     return CheckConditionalOperator(S, CO, CC, T);
13477 
13478   AnalyzeImplicitConversions(S, E, CC);
13479   if (E->getType() != T)
13480     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13481 }
13482 
13483 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13484                                      SourceLocation CC, QualType T) {
13485   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13486 
13487   Expr *TrueExpr = E->getTrueExpr();
13488   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13489     TrueExpr = BCO->getCommon();
13490 
13491   bool Suspicious = false;
13492   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13493   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13494 
13495   if (T->isBooleanType())
13496     DiagnoseIntInBoolContext(S, E);
13497 
13498   // If -Wconversion would have warned about either of the candidates
13499   // for a signedness conversion to the context type...
13500   if (!Suspicious) return;
13501 
13502   // ...but it's currently ignored...
13503   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13504     return;
13505 
13506   // ...then check whether it would have warned about either of the
13507   // candidates for a signedness conversion to the condition type.
13508   if (E->getType() == T) return;
13509 
13510   Suspicious = false;
13511   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13512                           E->getType(), CC, &Suspicious);
13513   if (!Suspicious)
13514     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13515                             E->getType(), CC, &Suspicious);
13516 }
13517 
13518 /// Check conversion of given expression to boolean.
13519 /// Input argument E is a logical expression.
13520 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13521   if (S.getLangOpts().Bool)
13522     return;
13523   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13524     return;
13525   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13526 }
13527 
13528 namespace {
13529 struct AnalyzeImplicitConversionsWorkItem {
13530   Expr *E;
13531   SourceLocation CC;
13532   bool IsListInit;
13533 };
13534 }
13535 
13536 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13537 /// that should be visited are added to WorkList.
13538 static void AnalyzeImplicitConversions(
13539     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13540     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13541   Expr *OrigE = Item.E;
13542   SourceLocation CC = Item.CC;
13543 
13544   QualType T = OrigE->getType();
13545   Expr *E = OrigE->IgnoreParenImpCasts();
13546 
13547   // Propagate whether we are in a C++ list initialization expression.
13548   // If so, we do not issue warnings for implicit int-float conversion
13549   // precision loss, because C++11 narrowing already handles it.
13550   bool IsListInit = Item.IsListInit ||
13551                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13552 
13553   if (E->isTypeDependent() || E->isValueDependent())
13554     return;
13555 
13556   Expr *SourceExpr = E;
13557   // Examine, but don't traverse into the source expression of an
13558   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13559   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13560   // evaluate it in the context of checking the specific conversion to T though.
13561   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13562     if (auto *Src = OVE->getSourceExpr())
13563       SourceExpr = Src;
13564 
13565   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13566     if (UO->getOpcode() == UO_Not &&
13567         UO->getSubExpr()->isKnownToHaveBooleanValue())
13568       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13569           << OrigE->getSourceRange() << T->isBooleanType()
13570           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13571 
13572   if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
13573     if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13574         BO->getLHS()->isKnownToHaveBooleanValue() &&
13575         BO->getRHS()->isKnownToHaveBooleanValue() &&
13576         BO->getLHS()->HasSideEffects(S.Context) &&
13577         BO->getRHS()->HasSideEffects(S.Context)) {
13578       S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13579           << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange()
13580           << FixItHint::CreateReplacement(
13581                  BO->getOperatorLoc(),
13582                  (BO->getOpcode() == BO_And ? "&&" : "||"));
13583       S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13584     }
13585 
13586   // For conditional operators, we analyze the arguments as if they
13587   // were being fed directly into the output.
13588   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13589     CheckConditionalOperator(S, CO, CC, T);
13590     return;
13591   }
13592 
13593   // Check implicit argument conversions for function calls.
13594   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13595     CheckImplicitArgumentConversions(S, Call, CC);
13596 
13597   // Go ahead and check any implicit conversions we might have skipped.
13598   // The non-canonical typecheck is just an optimization;
13599   // CheckImplicitConversion will filter out dead implicit conversions.
13600   if (SourceExpr->getType() != T)
13601     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13602 
13603   // Now continue drilling into this expression.
13604 
13605   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13606     // The bound subexpressions in a PseudoObjectExpr are not reachable
13607     // as transitive children.
13608     // FIXME: Use a more uniform representation for this.
13609     for (auto *SE : POE->semantics())
13610       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13611         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13612   }
13613 
13614   // Skip past explicit casts.
13615   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13616     E = CE->getSubExpr()->IgnoreParenImpCasts();
13617     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13618       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13619     WorkList.push_back({E, CC, IsListInit});
13620     return;
13621   }
13622 
13623   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13624     // Do a somewhat different check with comparison operators.
13625     if (BO->isComparisonOp())
13626       return AnalyzeComparison(S, BO);
13627 
13628     // And with simple assignments.
13629     if (BO->getOpcode() == BO_Assign)
13630       return AnalyzeAssignment(S, BO);
13631     // And with compound assignments.
13632     if (BO->isAssignmentOp())
13633       return AnalyzeCompoundAssignment(S, BO);
13634   }
13635 
13636   // These break the otherwise-useful invariant below.  Fortunately,
13637   // we don't really need to recurse into them, because any internal
13638   // expressions should have been analyzed already when they were
13639   // built into statements.
13640   if (isa<StmtExpr>(E)) return;
13641 
13642   // Don't descend into unevaluated contexts.
13643   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13644 
13645   // Now just recurse over the expression's children.
13646   CC = E->getExprLoc();
13647   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13648   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13649   for (Stmt *SubStmt : E->children()) {
13650     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13651     if (!ChildExpr)
13652       continue;
13653 
13654     if (IsLogicalAndOperator &&
13655         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13656       // Ignore checking string literals that are in logical and operators.
13657       // This is a common pattern for asserts.
13658       continue;
13659     WorkList.push_back({ChildExpr, CC, IsListInit});
13660   }
13661 
13662   if (BO && BO->isLogicalOp()) {
13663     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13664     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13665       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13666 
13667     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13668     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13669       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13670   }
13671 
13672   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13673     if (U->getOpcode() == UO_LNot) {
13674       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13675     } else if (U->getOpcode() != UO_AddrOf) {
13676       if (U->getSubExpr()->getType()->isAtomicType())
13677         S.Diag(U->getSubExpr()->getBeginLoc(),
13678                diag::warn_atomic_implicit_seq_cst);
13679     }
13680   }
13681 }
13682 
13683 /// AnalyzeImplicitConversions - Find and report any interesting
13684 /// implicit conversions in the given expression.  There are a couple
13685 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13686 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13687                                        bool IsListInit/*= false*/) {
13688   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13689   WorkList.push_back({OrigE, CC, IsListInit});
13690   while (!WorkList.empty())
13691     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13692 }
13693 
13694 /// Diagnose integer type and any valid implicit conversion to it.
13695 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13696   // Taking into account implicit conversions,
13697   // allow any integer.
13698   if (!E->getType()->isIntegerType()) {
13699     S.Diag(E->getBeginLoc(),
13700            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13701     return true;
13702   }
13703   // Potentially emit standard warnings for implicit conversions if enabled
13704   // using -Wconversion.
13705   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13706   return false;
13707 }
13708 
13709 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13710 // Returns true when emitting a warning about taking the address of a reference.
13711 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13712                               const PartialDiagnostic &PD) {
13713   E = E->IgnoreParenImpCasts();
13714 
13715   const FunctionDecl *FD = nullptr;
13716 
13717   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13718     if (!DRE->getDecl()->getType()->isReferenceType())
13719       return false;
13720   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13721     if (!M->getMemberDecl()->getType()->isReferenceType())
13722       return false;
13723   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13724     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13725       return false;
13726     FD = Call->getDirectCallee();
13727   } else {
13728     return false;
13729   }
13730 
13731   SemaRef.Diag(E->getExprLoc(), PD);
13732 
13733   // If possible, point to location of function.
13734   if (FD) {
13735     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13736   }
13737 
13738   return true;
13739 }
13740 
13741 // Returns true if the SourceLocation is expanded from any macro body.
13742 // Returns false if the SourceLocation is invalid, is from not in a macro
13743 // expansion, or is from expanded from a top-level macro argument.
13744 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13745   if (Loc.isInvalid())
13746     return false;
13747 
13748   while (Loc.isMacroID()) {
13749     if (SM.isMacroBodyExpansion(Loc))
13750       return true;
13751     Loc = SM.getImmediateMacroCallerLoc(Loc);
13752   }
13753 
13754   return false;
13755 }
13756 
13757 /// Diagnose pointers that are always non-null.
13758 /// \param E the expression containing the pointer
13759 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13760 /// compared to a null pointer
13761 /// \param IsEqual True when the comparison is equal to a null pointer
13762 /// \param Range Extra SourceRange to highlight in the diagnostic
13763 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13764                                         Expr::NullPointerConstantKind NullKind,
13765                                         bool IsEqual, SourceRange Range) {
13766   if (!E)
13767     return;
13768 
13769   // Don't warn inside macros.
13770   if (E->getExprLoc().isMacroID()) {
13771     const SourceManager &SM = getSourceManager();
13772     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13773         IsInAnyMacroBody(SM, Range.getBegin()))
13774       return;
13775   }
13776   E = E->IgnoreImpCasts();
13777 
13778   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13779 
13780   if (isa<CXXThisExpr>(E)) {
13781     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13782                                 : diag::warn_this_bool_conversion;
13783     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13784     return;
13785   }
13786 
13787   bool IsAddressOf = false;
13788 
13789   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13790     if (UO->getOpcode() != UO_AddrOf)
13791       return;
13792     IsAddressOf = true;
13793     E = UO->getSubExpr();
13794   }
13795 
13796   if (IsAddressOf) {
13797     unsigned DiagID = IsCompare
13798                           ? diag::warn_address_of_reference_null_compare
13799                           : diag::warn_address_of_reference_bool_conversion;
13800     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13801                                          << IsEqual;
13802     if (CheckForReference(*this, E, PD)) {
13803       return;
13804     }
13805   }
13806 
13807   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13808     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13809     std::string Str;
13810     llvm::raw_string_ostream S(Str);
13811     E->printPretty(S, nullptr, getPrintingPolicy());
13812     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13813                                 : diag::warn_cast_nonnull_to_bool;
13814     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13815       << E->getSourceRange() << Range << IsEqual;
13816     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13817   };
13818 
13819   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13820   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13821     if (auto *Callee = Call->getDirectCallee()) {
13822       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13823         ComplainAboutNonnullParamOrCall(A);
13824         return;
13825       }
13826     }
13827   }
13828 
13829   // Expect to find a single Decl.  Skip anything more complicated.
13830   ValueDecl *D = nullptr;
13831   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13832     D = R->getDecl();
13833   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13834     D = M->getMemberDecl();
13835   }
13836 
13837   // Weak Decls can be null.
13838   if (!D || D->isWeak())
13839     return;
13840 
13841   // Check for parameter decl with nonnull attribute
13842   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13843     if (getCurFunction() &&
13844         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13845       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13846         ComplainAboutNonnullParamOrCall(A);
13847         return;
13848       }
13849 
13850       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13851         // Skip function template not specialized yet.
13852         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13853           return;
13854         auto ParamIter = llvm::find(FD->parameters(), PV);
13855         assert(ParamIter != FD->param_end());
13856         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13857 
13858         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13859           if (!NonNull->args_size()) {
13860               ComplainAboutNonnullParamOrCall(NonNull);
13861               return;
13862           }
13863 
13864           for (const ParamIdx &ArgNo : NonNull->args()) {
13865             if (ArgNo.getASTIndex() == ParamNo) {
13866               ComplainAboutNonnullParamOrCall(NonNull);
13867               return;
13868             }
13869           }
13870         }
13871       }
13872     }
13873   }
13874 
13875   QualType T = D->getType();
13876   const bool IsArray = T->isArrayType();
13877   const bool IsFunction = T->isFunctionType();
13878 
13879   // Address of function is used to silence the function warning.
13880   if (IsAddressOf && IsFunction) {
13881     return;
13882   }
13883 
13884   // Found nothing.
13885   if (!IsAddressOf && !IsFunction && !IsArray)
13886     return;
13887 
13888   // Pretty print the expression for the diagnostic.
13889   std::string Str;
13890   llvm::raw_string_ostream S(Str);
13891   E->printPretty(S, nullptr, getPrintingPolicy());
13892 
13893   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13894                               : diag::warn_impcast_pointer_to_bool;
13895   enum {
13896     AddressOf,
13897     FunctionPointer,
13898     ArrayPointer
13899   } DiagType;
13900   if (IsAddressOf)
13901     DiagType = AddressOf;
13902   else if (IsFunction)
13903     DiagType = FunctionPointer;
13904   else if (IsArray)
13905     DiagType = ArrayPointer;
13906   else
13907     llvm_unreachable("Could not determine diagnostic.");
13908   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13909                                 << Range << IsEqual;
13910 
13911   if (!IsFunction)
13912     return;
13913 
13914   // Suggest '&' to silence the function warning.
13915   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13916       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13917 
13918   // Check to see if '()' fixit should be emitted.
13919   QualType ReturnType;
13920   UnresolvedSet<4> NonTemplateOverloads;
13921   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13922   if (ReturnType.isNull())
13923     return;
13924 
13925   if (IsCompare) {
13926     // There are two cases here.  If there is null constant, the only suggest
13927     // for a pointer return type.  If the null is 0, then suggest if the return
13928     // type is a pointer or an integer type.
13929     if (!ReturnType->isPointerType()) {
13930       if (NullKind == Expr::NPCK_ZeroExpression ||
13931           NullKind == Expr::NPCK_ZeroLiteral) {
13932         if (!ReturnType->isIntegerType())
13933           return;
13934       } else {
13935         return;
13936       }
13937     }
13938   } else { // !IsCompare
13939     // For function to bool, only suggest if the function pointer has bool
13940     // return type.
13941     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13942       return;
13943   }
13944   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13945       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13946 }
13947 
13948 /// Diagnoses "dangerous" implicit conversions within the given
13949 /// expression (which is a full expression).  Implements -Wconversion
13950 /// and -Wsign-compare.
13951 ///
13952 /// \param CC the "context" location of the implicit conversion, i.e.
13953 ///   the most location of the syntactic entity requiring the implicit
13954 ///   conversion
13955 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13956   // Don't diagnose in unevaluated contexts.
13957   if (isUnevaluatedContext())
13958     return;
13959 
13960   // Don't diagnose for value- or type-dependent expressions.
13961   if (E->isTypeDependent() || E->isValueDependent())
13962     return;
13963 
13964   // Check for array bounds violations in cases where the check isn't triggered
13965   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13966   // ArraySubscriptExpr is on the RHS of a variable initialization.
13967   CheckArrayAccess(E);
13968 
13969   // This is not the right CC for (e.g.) a variable initialization.
13970   AnalyzeImplicitConversions(*this, E, CC);
13971 }
13972 
13973 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13974 /// Input argument E is a logical expression.
13975 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13976   ::CheckBoolLikeConversion(*this, E, CC);
13977 }
13978 
13979 /// Diagnose when expression is an integer constant expression and its evaluation
13980 /// results in integer overflow
13981 void Sema::CheckForIntOverflow (Expr *E) {
13982   // Use a work list to deal with nested struct initializers.
13983   SmallVector<Expr *, 2> Exprs(1, E);
13984 
13985   do {
13986     Expr *OriginalE = Exprs.pop_back_val();
13987     Expr *E = OriginalE->IgnoreParenCasts();
13988 
13989     if (isa<BinaryOperator>(E)) {
13990       E->EvaluateForOverflow(Context);
13991       continue;
13992     }
13993 
13994     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13995       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13996     else if (isa<ObjCBoxedExpr>(OriginalE))
13997       E->EvaluateForOverflow(Context);
13998     else if (auto Call = dyn_cast<CallExpr>(E))
13999       Exprs.append(Call->arg_begin(), Call->arg_end());
14000     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
14001       Exprs.append(Message->arg_begin(), Message->arg_end());
14002   } while (!Exprs.empty());
14003 }
14004 
14005 namespace {
14006 
14007 /// Visitor for expressions which looks for unsequenced operations on the
14008 /// same object.
14009 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14010   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14011 
14012   /// A tree of sequenced regions within an expression. Two regions are
14013   /// unsequenced if one is an ancestor or a descendent of the other. When we
14014   /// finish processing an expression with sequencing, such as a comma
14015   /// expression, we fold its tree nodes into its parent, since they are
14016   /// unsequenced with respect to nodes we will visit later.
14017   class SequenceTree {
14018     struct Value {
14019       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14020       unsigned Parent : 31;
14021       unsigned Merged : 1;
14022     };
14023     SmallVector<Value, 8> Values;
14024 
14025   public:
14026     /// A region within an expression which may be sequenced with respect
14027     /// to some other region.
14028     class Seq {
14029       friend class SequenceTree;
14030 
14031       unsigned Index;
14032 
14033       explicit Seq(unsigned N) : Index(N) {}
14034 
14035     public:
14036       Seq() : Index(0) {}
14037     };
14038 
14039     SequenceTree() { Values.push_back(Value(0)); }
14040     Seq root() const { return Seq(0); }
14041 
14042     /// Create a new sequence of operations, which is an unsequenced
14043     /// subset of \p Parent. This sequence of operations is sequenced with
14044     /// respect to other children of \p Parent.
14045     Seq allocate(Seq Parent) {
14046       Values.push_back(Value(Parent.Index));
14047       return Seq(Values.size() - 1);
14048     }
14049 
14050     /// Merge a sequence of operations into its parent.
14051     void merge(Seq S) {
14052       Values[S.Index].Merged = true;
14053     }
14054 
14055     /// Determine whether two operations are unsequenced. This operation
14056     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14057     /// should have been merged into its parent as appropriate.
14058     bool isUnsequenced(Seq Cur, Seq Old) {
14059       unsigned C = representative(Cur.Index);
14060       unsigned Target = representative(Old.Index);
14061       while (C >= Target) {
14062         if (C == Target)
14063           return true;
14064         C = Values[C].Parent;
14065       }
14066       return false;
14067     }
14068 
14069   private:
14070     /// Pick a representative for a sequence.
14071     unsigned representative(unsigned K) {
14072       if (Values[K].Merged)
14073         // Perform path compression as we go.
14074         return Values[K].Parent = representative(Values[K].Parent);
14075       return K;
14076     }
14077   };
14078 
14079   /// An object for which we can track unsequenced uses.
14080   using Object = const NamedDecl *;
14081 
14082   /// Different flavors of object usage which we track. We only track the
14083   /// least-sequenced usage of each kind.
14084   enum UsageKind {
14085     /// A read of an object. Multiple unsequenced reads are OK.
14086     UK_Use,
14087 
14088     /// A modification of an object which is sequenced before the value
14089     /// computation of the expression, such as ++n in C++.
14090     UK_ModAsValue,
14091 
14092     /// A modification of an object which is not sequenced before the value
14093     /// computation of the expression, such as n++.
14094     UK_ModAsSideEffect,
14095 
14096     UK_Count = UK_ModAsSideEffect + 1
14097   };
14098 
14099   /// Bundle together a sequencing region and the expression corresponding
14100   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14101   struct Usage {
14102     const Expr *UsageExpr;
14103     SequenceTree::Seq Seq;
14104 
14105     Usage() : UsageExpr(nullptr) {}
14106   };
14107 
14108   struct UsageInfo {
14109     Usage Uses[UK_Count];
14110 
14111     /// Have we issued a diagnostic for this object already?
14112     bool Diagnosed;
14113 
14114     UsageInfo() : Diagnosed(false) {}
14115   };
14116   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14117 
14118   Sema &SemaRef;
14119 
14120   /// Sequenced regions within the expression.
14121   SequenceTree Tree;
14122 
14123   /// Declaration modifications and references which we have seen.
14124   UsageInfoMap UsageMap;
14125 
14126   /// The region we are currently within.
14127   SequenceTree::Seq Region;
14128 
14129   /// Filled in with declarations which were modified as a side-effect
14130   /// (that is, post-increment operations).
14131   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14132 
14133   /// Expressions to check later. We defer checking these to reduce
14134   /// stack usage.
14135   SmallVectorImpl<const Expr *> &WorkList;
14136 
14137   /// RAII object wrapping the visitation of a sequenced subexpression of an
14138   /// expression. At the end of this process, the side-effects of the evaluation
14139   /// become sequenced with respect to the value computation of the result, so
14140   /// we downgrade any UK_ModAsSideEffect within the evaluation to
14141   /// UK_ModAsValue.
14142   struct SequencedSubexpression {
14143     SequencedSubexpression(SequenceChecker &Self)
14144       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14145       Self.ModAsSideEffect = &ModAsSideEffect;
14146     }
14147 
14148     ~SequencedSubexpression() {
14149       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14150         // Add a new usage with usage kind UK_ModAsValue, and then restore
14151         // the previous usage with UK_ModAsSideEffect (thus clearing it if
14152         // the previous one was empty).
14153         UsageInfo &UI = Self.UsageMap[M.first];
14154         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14155         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14156         SideEffectUsage = M.second;
14157       }
14158       Self.ModAsSideEffect = OldModAsSideEffect;
14159     }
14160 
14161     SequenceChecker &Self;
14162     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14163     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14164   };
14165 
14166   /// RAII object wrapping the visitation of a subexpression which we might
14167   /// choose to evaluate as a constant. If any subexpression is evaluated and
14168   /// found to be non-constant, this allows us to suppress the evaluation of
14169   /// the outer expression.
14170   class EvaluationTracker {
14171   public:
14172     EvaluationTracker(SequenceChecker &Self)
14173         : Self(Self), Prev(Self.EvalTracker) {
14174       Self.EvalTracker = this;
14175     }
14176 
14177     ~EvaluationTracker() {
14178       Self.EvalTracker = Prev;
14179       if (Prev)
14180         Prev->EvalOK &= EvalOK;
14181     }
14182 
14183     bool evaluate(const Expr *E, bool &Result) {
14184       if (!EvalOK || E->isValueDependent())
14185         return false;
14186       EvalOK = E->EvaluateAsBooleanCondition(
14187           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
14188       return EvalOK;
14189     }
14190 
14191   private:
14192     SequenceChecker &Self;
14193     EvaluationTracker *Prev;
14194     bool EvalOK = true;
14195   } *EvalTracker = nullptr;
14196 
14197   /// Find the object which is produced by the specified expression,
14198   /// if any.
14199   Object getObject(const Expr *E, bool Mod) const {
14200     E = E->IgnoreParenCasts();
14201     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14202       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14203         return getObject(UO->getSubExpr(), Mod);
14204     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14205       if (BO->getOpcode() == BO_Comma)
14206         return getObject(BO->getRHS(), Mod);
14207       if (Mod && BO->isAssignmentOp())
14208         return getObject(BO->getLHS(), Mod);
14209     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14210       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14211       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14212         return ME->getMemberDecl();
14213     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14214       // FIXME: If this is a reference, map through to its value.
14215       return DRE->getDecl();
14216     return nullptr;
14217   }
14218 
14219   /// Note that an object \p O was modified or used by an expression
14220   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14221   /// the object \p O as obtained via the \p UsageMap.
14222   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14223     // Get the old usage for the given object and usage kind.
14224     Usage &U = UI.Uses[UK];
14225     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14226       // If we have a modification as side effect and are in a sequenced
14227       // subexpression, save the old Usage so that we can restore it later
14228       // in SequencedSubexpression::~SequencedSubexpression.
14229       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14230         ModAsSideEffect->push_back(std::make_pair(O, U));
14231       // Then record the new usage with the current sequencing region.
14232       U.UsageExpr = UsageExpr;
14233       U.Seq = Region;
14234     }
14235   }
14236 
14237   /// Check whether a modification or use of an object \p O in an expression
14238   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14239   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14240   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14241   /// usage and false we are checking for a mod-use unsequenced usage.
14242   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14243                   UsageKind OtherKind, bool IsModMod) {
14244     if (UI.Diagnosed)
14245       return;
14246 
14247     const Usage &U = UI.Uses[OtherKind];
14248     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14249       return;
14250 
14251     const Expr *Mod = U.UsageExpr;
14252     const Expr *ModOrUse = UsageExpr;
14253     if (OtherKind == UK_Use)
14254       std::swap(Mod, ModOrUse);
14255 
14256     SemaRef.DiagRuntimeBehavior(
14257         Mod->getExprLoc(), {Mod, ModOrUse},
14258         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14259                                : diag::warn_unsequenced_mod_use)
14260             << O << SourceRange(ModOrUse->getExprLoc()));
14261     UI.Diagnosed = true;
14262   }
14263 
14264   // A note on note{Pre, Post}{Use, Mod}:
14265   //
14266   // (It helps to follow the algorithm with an expression such as
14267   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14268   //  operations before C++17 and both are well-defined in C++17).
14269   //
14270   // When visiting a node which uses/modify an object we first call notePreUse
14271   // or notePreMod before visiting its sub-expression(s). At this point the
14272   // children of the current node have not yet been visited and so the eventual
14273   // uses/modifications resulting from the children of the current node have not
14274   // been recorded yet.
14275   //
14276   // We then visit the children of the current node. After that notePostUse or
14277   // notePostMod is called. These will 1) detect an unsequenced modification
14278   // as side effect (as in "k++ + k") and 2) add a new usage with the
14279   // appropriate usage kind.
14280   //
14281   // We also have to be careful that some operation sequences modification as
14282   // side effect as well (for example: || or ,). To account for this we wrap
14283   // the visitation of such a sub-expression (for example: the LHS of || or ,)
14284   // with SequencedSubexpression. SequencedSubexpression is an RAII object
14285   // which record usages which are modifications as side effect, and then
14286   // downgrade them (or more accurately restore the previous usage which was a
14287   // modification as side effect) when exiting the scope of the sequenced
14288   // subexpression.
14289 
14290   void notePreUse(Object O, const Expr *UseExpr) {
14291     UsageInfo &UI = UsageMap[O];
14292     // Uses conflict with other modifications.
14293     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14294   }
14295 
14296   void notePostUse(Object O, const Expr *UseExpr) {
14297     UsageInfo &UI = UsageMap[O];
14298     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14299                /*IsModMod=*/false);
14300     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14301   }
14302 
14303   void notePreMod(Object O, const Expr *ModExpr) {
14304     UsageInfo &UI = UsageMap[O];
14305     // Modifications conflict with other modifications and with uses.
14306     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14307     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14308   }
14309 
14310   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14311     UsageInfo &UI = UsageMap[O];
14312     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14313                /*IsModMod=*/true);
14314     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14315   }
14316 
14317 public:
14318   SequenceChecker(Sema &S, const Expr *E,
14319                   SmallVectorImpl<const Expr *> &WorkList)
14320       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14321     Visit(E);
14322     // Silence a -Wunused-private-field since WorkList is now unused.
14323     // TODO: Evaluate if it can be used, and if not remove it.
14324     (void)this->WorkList;
14325   }
14326 
14327   void VisitStmt(const Stmt *S) {
14328     // Skip all statements which aren't expressions for now.
14329   }
14330 
14331   void VisitExpr(const Expr *E) {
14332     // By default, just recurse to evaluated subexpressions.
14333     Base::VisitStmt(E);
14334   }
14335 
14336   void VisitCastExpr(const CastExpr *E) {
14337     Object O = Object();
14338     if (E->getCastKind() == CK_LValueToRValue)
14339       O = getObject(E->getSubExpr(), false);
14340 
14341     if (O)
14342       notePreUse(O, E);
14343     VisitExpr(E);
14344     if (O)
14345       notePostUse(O, E);
14346   }
14347 
14348   void VisitSequencedExpressions(const Expr *SequencedBefore,
14349                                  const Expr *SequencedAfter) {
14350     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14351     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14352     SequenceTree::Seq OldRegion = Region;
14353 
14354     {
14355       SequencedSubexpression SeqBefore(*this);
14356       Region = BeforeRegion;
14357       Visit(SequencedBefore);
14358     }
14359 
14360     Region = AfterRegion;
14361     Visit(SequencedAfter);
14362 
14363     Region = OldRegion;
14364 
14365     Tree.merge(BeforeRegion);
14366     Tree.merge(AfterRegion);
14367   }
14368 
14369   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14370     // C++17 [expr.sub]p1:
14371     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14372     //   expression E1 is sequenced before the expression E2.
14373     if (SemaRef.getLangOpts().CPlusPlus17)
14374       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14375     else {
14376       Visit(ASE->getLHS());
14377       Visit(ASE->getRHS());
14378     }
14379   }
14380 
14381   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14382   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14383   void VisitBinPtrMem(const BinaryOperator *BO) {
14384     // C++17 [expr.mptr.oper]p4:
14385     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14386     //  the expression E1 is sequenced before the expression E2.
14387     if (SemaRef.getLangOpts().CPlusPlus17)
14388       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14389     else {
14390       Visit(BO->getLHS());
14391       Visit(BO->getRHS());
14392     }
14393   }
14394 
14395   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14396   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14397   void VisitBinShlShr(const BinaryOperator *BO) {
14398     // C++17 [expr.shift]p4:
14399     //  The expression E1 is sequenced before the expression E2.
14400     if (SemaRef.getLangOpts().CPlusPlus17)
14401       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14402     else {
14403       Visit(BO->getLHS());
14404       Visit(BO->getRHS());
14405     }
14406   }
14407 
14408   void VisitBinComma(const BinaryOperator *BO) {
14409     // C++11 [expr.comma]p1:
14410     //   Every value computation and side effect associated with the left
14411     //   expression is sequenced before every value computation and side
14412     //   effect associated with the right expression.
14413     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14414   }
14415 
14416   void VisitBinAssign(const BinaryOperator *BO) {
14417     SequenceTree::Seq RHSRegion;
14418     SequenceTree::Seq LHSRegion;
14419     if (SemaRef.getLangOpts().CPlusPlus17) {
14420       RHSRegion = Tree.allocate(Region);
14421       LHSRegion = Tree.allocate(Region);
14422     } else {
14423       RHSRegion = Region;
14424       LHSRegion = Region;
14425     }
14426     SequenceTree::Seq OldRegion = Region;
14427 
14428     // C++11 [expr.ass]p1:
14429     //  [...] the assignment is sequenced after the value computation
14430     //  of the right and left operands, [...]
14431     //
14432     // so check it before inspecting the operands and update the
14433     // map afterwards.
14434     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14435     if (O)
14436       notePreMod(O, BO);
14437 
14438     if (SemaRef.getLangOpts().CPlusPlus17) {
14439       // C++17 [expr.ass]p1:
14440       //  [...] The right operand is sequenced before the left operand. [...]
14441       {
14442         SequencedSubexpression SeqBefore(*this);
14443         Region = RHSRegion;
14444         Visit(BO->getRHS());
14445       }
14446 
14447       Region = LHSRegion;
14448       Visit(BO->getLHS());
14449 
14450       if (O && isa<CompoundAssignOperator>(BO))
14451         notePostUse(O, BO);
14452 
14453     } else {
14454       // C++11 does not specify any sequencing between the LHS and RHS.
14455       Region = LHSRegion;
14456       Visit(BO->getLHS());
14457 
14458       if (O && isa<CompoundAssignOperator>(BO))
14459         notePostUse(O, BO);
14460 
14461       Region = RHSRegion;
14462       Visit(BO->getRHS());
14463     }
14464 
14465     // C++11 [expr.ass]p1:
14466     //  the assignment is sequenced [...] before the value computation of the
14467     //  assignment expression.
14468     // C11 6.5.16/3 has no such rule.
14469     Region = OldRegion;
14470     if (O)
14471       notePostMod(O, BO,
14472                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14473                                                   : UK_ModAsSideEffect);
14474     if (SemaRef.getLangOpts().CPlusPlus17) {
14475       Tree.merge(RHSRegion);
14476       Tree.merge(LHSRegion);
14477     }
14478   }
14479 
14480   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14481     VisitBinAssign(CAO);
14482   }
14483 
14484   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14485   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14486   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14487     Object O = getObject(UO->getSubExpr(), true);
14488     if (!O)
14489       return VisitExpr(UO);
14490 
14491     notePreMod(O, UO);
14492     Visit(UO->getSubExpr());
14493     // C++11 [expr.pre.incr]p1:
14494     //   the expression ++x is equivalent to x+=1
14495     notePostMod(O, UO,
14496                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14497                                                 : UK_ModAsSideEffect);
14498   }
14499 
14500   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14501   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14502   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14503     Object O = getObject(UO->getSubExpr(), true);
14504     if (!O)
14505       return VisitExpr(UO);
14506 
14507     notePreMod(O, UO);
14508     Visit(UO->getSubExpr());
14509     notePostMod(O, UO, UK_ModAsSideEffect);
14510   }
14511 
14512   void VisitBinLOr(const BinaryOperator *BO) {
14513     // C++11 [expr.log.or]p2:
14514     //  If the second expression is evaluated, every value computation and
14515     //  side effect associated with the first expression is sequenced before
14516     //  every value computation and side effect associated with the
14517     //  second expression.
14518     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14519     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14520     SequenceTree::Seq OldRegion = Region;
14521 
14522     EvaluationTracker Eval(*this);
14523     {
14524       SequencedSubexpression Sequenced(*this);
14525       Region = LHSRegion;
14526       Visit(BO->getLHS());
14527     }
14528 
14529     // C++11 [expr.log.or]p1:
14530     //  [...] the second operand is not evaluated if the first operand
14531     //  evaluates to true.
14532     bool EvalResult = false;
14533     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14534     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14535     if (ShouldVisitRHS) {
14536       Region = RHSRegion;
14537       Visit(BO->getRHS());
14538     }
14539 
14540     Region = OldRegion;
14541     Tree.merge(LHSRegion);
14542     Tree.merge(RHSRegion);
14543   }
14544 
14545   void VisitBinLAnd(const BinaryOperator *BO) {
14546     // C++11 [expr.log.and]p2:
14547     //  If the second expression is evaluated, every value computation and
14548     //  side effect associated with the first expression is sequenced before
14549     //  every value computation and side effect associated with the
14550     //  second expression.
14551     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14552     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14553     SequenceTree::Seq OldRegion = Region;
14554 
14555     EvaluationTracker Eval(*this);
14556     {
14557       SequencedSubexpression Sequenced(*this);
14558       Region = LHSRegion;
14559       Visit(BO->getLHS());
14560     }
14561 
14562     // C++11 [expr.log.and]p1:
14563     //  [...] the second operand is not evaluated if the first operand is false.
14564     bool EvalResult = false;
14565     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14566     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14567     if (ShouldVisitRHS) {
14568       Region = RHSRegion;
14569       Visit(BO->getRHS());
14570     }
14571 
14572     Region = OldRegion;
14573     Tree.merge(LHSRegion);
14574     Tree.merge(RHSRegion);
14575   }
14576 
14577   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14578     // C++11 [expr.cond]p1:
14579     //  [...] Every value computation and side effect associated with the first
14580     //  expression is sequenced before every value computation and side effect
14581     //  associated with the second or third expression.
14582     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14583 
14584     // No sequencing is specified between the true and false expression.
14585     // However since exactly one of both is going to be evaluated we can
14586     // consider them to be sequenced. This is needed to avoid warning on
14587     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14588     // both the true and false expressions because we can't evaluate x.
14589     // This will still allow us to detect an expression like (pre C++17)
14590     // "(x ? y += 1 : y += 2) = y".
14591     //
14592     // We don't wrap the visitation of the true and false expression with
14593     // SequencedSubexpression because we don't want to downgrade modifications
14594     // as side effect in the true and false expressions after the visition
14595     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14596     // not warn between the two "y++", but we should warn between the "y++"
14597     // and the "y".
14598     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14599     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14600     SequenceTree::Seq OldRegion = Region;
14601 
14602     EvaluationTracker Eval(*this);
14603     {
14604       SequencedSubexpression Sequenced(*this);
14605       Region = ConditionRegion;
14606       Visit(CO->getCond());
14607     }
14608 
14609     // C++11 [expr.cond]p1:
14610     // [...] The first expression is contextually converted to bool (Clause 4).
14611     // It is evaluated and if it is true, the result of the conditional
14612     // expression is the value of the second expression, otherwise that of the
14613     // third expression. Only one of the second and third expressions is
14614     // evaluated. [...]
14615     bool EvalResult = false;
14616     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14617     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14618     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14619     if (ShouldVisitTrueExpr) {
14620       Region = TrueRegion;
14621       Visit(CO->getTrueExpr());
14622     }
14623     if (ShouldVisitFalseExpr) {
14624       Region = FalseRegion;
14625       Visit(CO->getFalseExpr());
14626     }
14627 
14628     Region = OldRegion;
14629     Tree.merge(ConditionRegion);
14630     Tree.merge(TrueRegion);
14631     Tree.merge(FalseRegion);
14632   }
14633 
14634   void VisitCallExpr(const CallExpr *CE) {
14635     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14636 
14637     if (CE->isUnevaluatedBuiltinCall(Context))
14638       return;
14639 
14640     // C++11 [intro.execution]p15:
14641     //   When calling a function [...], every value computation and side effect
14642     //   associated with any argument expression, or with the postfix expression
14643     //   designating the called function, is sequenced before execution of every
14644     //   expression or statement in the body of the function [and thus before
14645     //   the value computation of its result].
14646     SequencedSubexpression Sequenced(*this);
14647     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14648       // C++17 [expr.call]p5
14649       //   The postfix-expression is sequenced before each expression in the
14650       //   expression-list and any default argument. [...]
14651       SequenceTree::Seq CalleeRegion;
14652       SequenceTree::Seq OtherRegion;
14653       if (SemaRef.getLangOpts().CPlusPlus17) {
14654         CalleeRegion = Tree.allocate(Region);
14655         OtherRegion = Tree.allocate(Region);
14656       } else {
14657         CalleeRegion = Region;
14658         OtherRegion = Region;
14659       }
14660       SequenceTree::Seq OldRegion = Region;
14661 
14662       // Visit the callee expression first.
14663       Region = CalleeRegion;
14664       if (SemaRef.getLangOpts().CPlusPlus17) {
14665         SequencedSubexpression Sequenced(*this);
14666         Visit(CE->getCallee());
14667       } else {
14668         Visit(CE->getCallee());
14669       }
14670 
14671       // Then visit the argument expressions.
14672       Region = OtherRegion;
14673       for (const Expr *Argument : CE->arguments())
14674         Visit(Argument);
14675 
14676       Region = OldRegion;
14677       if (SemaRef.getLangOpts().CPlusPlus17) {
14678         Tree.merge(CalleeRegion);
14679         Tree.merge(OtherRegion);
14680       }
14681     });
14682   }
14683 
14684   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14685     // C++17 [over.match.oper]p2:
14686     //   [...] the operator notation is first transformed to the equivalent
14687     //   function-call notation as summarized in Table 12 (where @ denotes one
14688     //   of the operators covered in the specified subclause). However, the
14689     //   operands are sequenced in the order prescribed for the built-in
14690     //   operator (Clause 8).
14691     //
14692     // From the above only overloaded binary operators and overloaded call
14693     // operators have sequencing rules in C++17 that we need to handle
14694     // separately.
14695     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14696         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14697       return VisitCallExpr(CXXOCE);
14698 
14699     enum {
14700       NoSequencing,
14701       LHSBeforeRHS,
14702       RHSBeforeLHS,
14703       LHSBeforeRest
14704     } SequencingKind;
14705     switch (CXXOCE->getOperator()) {
14706     case OO_Equal:
14707     case OO_PlusEqual:
14708     case OO_MinusEqual:
14709     case OO_StarEqual:
14710     case OO_SlashEqual:
14711     case OO_PercentEqual:
14712     case OO_CaretEqual:
14713     case OO_AmpEqual:
14714     case OO_PipeEqual:
14715     case OO_LessLessEqual:
14716     case OO_GreaterGreaterEqual:
14717       SequencingKind = RHSBeforeLHS;
14718       break;
14719 
14720     case OO_LessLess:
14721     case OO_GreaterGreater:
14722     case OO_AmpAmp:
14723     case OO_PipePipe:
14724     case OO_Comma:
14725     case OO_ArrowStar:
14726     case OO_Subscript:
14727       SequencingKind = LHSBeforeRHS;
14728       break;
14729 
14730     case OO_Call:
14731       SequencingKind = LHSBeforeRest;
14732       break;
14733 
14734     default:
14735       SequencingKind = NoSequencing;
14736       break;
14737     }
14738 
14739     if (SequencingKind == NoSequencing)
14740       return VisitCallExpr(CXXOCE);
14741 
14742     // This is a call, so all subexpressions are sequenced before the result.
14743     SequencedSubexpression Sequenced(*this);
14744 
14745     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14746       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14747              "Should only get there with C++17 and above!");
14748       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14749              "Should only get there with an overloaded binary operator"
14750              " or an overloaded call operator!");
14751 
14752       if (SequencingKind == LHSBeforeRest) {
14753         assert(CXXOCE->getOperator() == OO_Call &&
14754                "We should only have an overloaded call operator here!");
14755 
14756         // This is very similar to VisitCallExpr, except that we only have the
14757         // C++17 case. The postfix-expression is the first argument of the
14758         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14759         // are in the following arguments.
14760         //
14761         // Note that we intentionally do not visit the callee expression since
14762         // it is just a decayed reference to a function.
14763         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14764         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14765         SequenceTree::Seq OldRegion = Region;
14766 
14767         assert(CXXOCE->getNumArgs() >= 1 &&
14768                "An overloaded call operator must have at least one argument"
14769                " for the postfix-expression!");
14770         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14771         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14772                                           CXXOCE->getNumArgs() - 1);
14773 
14774         // Visit the postfix-expression first.
14775         {
14776           Region = PostfixExprRegion;
14777           SequencedSubexpression Sequenced(*this);
14778           Visit(PostfixExpr);
14779         }
14780 
14781         // Then visit the argument expressions.
14782         Region = ArgsRegion;
14783         for (const Expr *Arg : Args)
14784           Visit(Arg);
14785 
14786         Region = OldRegion;
14787         Tree.merge(PostfixExprRegion);
14788         Tree.merge(ArgsRegion);
14789       } else {
14790         assert(CXXOCE->getNumArgs() == 2 &&
14791                "Should only have two arguments here!");
14792         assert((SequencingKind == LHSBeforeRHS ||
14793                 SequencingKind == RHSBeforeLHS) &&
14794                "Unexpected sequencing kind!");
14795 
14796         // We do not visit the callee expression since it is just a decayed
14797         // reference to a function.
14798         const Expr *E1 = CXXOCE->getArg(0);
14799         const Expr *E2 = CXXOCE->getArg(1);
14800         if (SequencingKind == RHSBeforeLHS)
14801           std::swap(E1, E2);
14802 
14803         return VisitSequencedExpressions(E1, E2);
14804       }
14805     });
14806   }
14807 
14808   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14809     // This is a call, so all subexpressions are sequenced before the result.
14810     SequencedSubexpression Sequenced(*this);
14811 
14812     if (!CCE->isListInitialization())
14813       return VisitExpr(CCE);
14814 
14815     // In C++11, list initializations are sequenced.
14816     SmallVector<SequenceTree::Seq, 32> Elts;
14817     SequenceTree::Seq Parent = Region;
14818     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14819                                               E = CCE->arg_end();
14820          I != E; ++I) {
14821       Region = Tree.allocate(Parent);
14822       Elts.push_back(Region);
14823       Visit(*I);
14824     }
14825 
14826     // Forget that the initializers are sequenced.
14827     Region = Parent;
14828     for (unsigned I = 0; I < Elts.size(); ++I)
14829       Tree.merge(Elts[I]);
14830   }
14831 
14832   void VisitInitListExpr(const InitListExpr *ILE) {
14833     if (!SemaRef.getLangOpts().CPlusPlus11)
14834       return VisitExpr(ILE);
14835 
14836     // In C++11, list initializations are sequenced.
14837     SmallVector<SequenceTree::Seq, 32> Elts;
14838     SequenceTree::Seq Parent = Region;
14839     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14840       const Expr *E = ILE->getInit(I);
14841       if (!E)
14842         continue;
14843       Region = Tree.allocate(Parent);
14844       Elts.push_back(Region);
14845       Visit(E);
14846     }
14847 
14848     // Forget that the initializers are sequenced.
14849     Region = Parent;
14850     for (unsigned I = 0; I < Elts.size(); ++I)
14851       Tree.merge(Elts[I]);
14852   }
14853 };
14854 
14855 } // namespace
14856 
14857 void Sema::CheckUnsequencedOperations(const Expr *E) {
14858   SmallVector<const Expr *, 8> WorkList;
14859   WorkList.push_back(E);
14860   while (!WorkList.empty()) {
14861     const Expr *Item = WorkList.pop_back_val();
14862     SequenceChecker(*this, Item, WorkList);
14863   }
14864 }
14865 
14866 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14867                               bool IsConstexpr) {
14868   llvm::SaveAndRestore<bool> ConstantContext(
14869       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14870   CheckImplicitConversions(E, CheckLoc);
14871   if (!E->isInstantiationDependent())
14872     CheckUnsequencedOperations(E);
14873   if (!IsConstexpr && !E->isValueDependent())
14874     CheckForIntOverflow(E);
14875   DiagnoseMisalignedMembers();
14876 }
14877 
14878 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14879                                        FieldDecl *BitField,
14880                                        Expr *Init) {
14881   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14882 }
14883 
14884 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14885                                          SourceLocation Loc) {
14886   if (!PType->isVariablyModifiedType())
14887     return;
14888   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14889     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14890     return;
14891   }
14892   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14893     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14894     return;
14895   }
14896   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14897     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14898     return;
14899   }
14900 
14901   const ArrayType *AT = S.Context.getAsArrayType(PType);
14902   if (!AT)
14903     return;
14904 
14905   if (AT->getSizeModifier() != ArrayType::Star) {
14906     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14907     return;
14908   }
14909 
14910   S.Diag(Loc, diag::err_array_star_in_function_definition);
14911 }
14912 
14913 /// CheckParmsForFunctionDef - Check that the parameters of the given
14914 /// function are appropriate for the definition of a function. This
14915 /// takes care of any checks that cannot be performed on the
14916 /// declaration itself, e.g., that the types of each of the function
14917 /// parameters are complete.
14918 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14919                                     bool CheckParameterNames) {
14920   bool HasInvalidParm = false;
14921   for (ParmVarDecl *Param : Parameters) {
14922     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14923     // function declarator that is part of a function definition of
14924     // that function shall not have incomplete type.
14925     //
14926     // This is also C++ [dcl.fct]p6.
14927     if (!Param->isInvalidDecl() &&
14928         RequireCompleteType(Param->getLocation(), Param->getType(),
14929                             diag::err_typecheck_decl_incomplete_type)) {
14930       Param->setInvalidDecl();
14931       HasInvalidParm = true;
14932     }
14933 
14934     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14935     // declaration of each parameter shall include an identifier.
14936     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14937         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14938       // Diagnose this as an extension in C17 and earlier.
14939       if (!getLangOpts().C2x)
14940         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14941     }
14942 
14943     // C99 6.7.5.3p12:
14944     //   If the function declarator is not part of a definition of that
14945     //   function, parameters may have incomplete type and may use the [*]
14946     //   notation in their sequences of declarator specifiers to specify
14947     //   variable length array types.
14948     QualType PType = Param->getOriginalType();
14949     // FIXME: This diagnostic should point the '[*]' if source-location
14950     // information is added for it.
14951     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14952 
14953     // If the parameter is a c++ class type and it has to be destructed in the
14954     // callee function, declare the destructor so that it can be called by the
14955     // callee function. Do not perform any direct access check on the dtor here.
14956     if (!Param->isInvalidDecl()) {
14957       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14958         if (!ClassDecl->isInvalidDecl() &&
14959             !ClassDecl->hasIrrelevantDestructor() &&
14960             !ClassDecl->isDependentContext() &&
14961             ClassDecl->isParamDestroyedInCallee()) {
14962           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14963           MarkFunctionReferenced(Param->getLocation(), Destructor);
14964           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14965         }
14966       }
14967     }
14968 
14969     // Parameters with the pass_object_size attribute only need to be marked
14970     // constant at function definitions. Because we lack information about
14971     // whether we're on a declaration or definition when we're instantiating the
14972     // attribute, we need to check for constness here.
14973     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14974       if (!Param->getType().isConstQualified())
14975         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14976             << Attr->getSpelling() << 1;
14977 
14978     // Check for parameter names shadowing fields from the class.
14979     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14980       // The owning context for the parameter should be the function, but we
14981       // want to see if this function's declaration context is a record.
14982       DeclContext *DC = Param->getDeclContext();
14983       if (DC && DC->isFunctionOrMethod()) {
14984         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14985           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14986                                      RD, /*DeclIsField*/ false);
14987       }
14988     }
14989   }
14990 
14991   return HasInvalidParm;
14992 }
14993 
14994 Optional<std::pair<CharUnits, CharUnits>>
14995 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14996 
14997 /// Compute the alignment and offset of the base class object given the
14998 /// derived-to-base cast expression and the alignment and offset of the derived
14999 /// class object.
15000 static std::pair<CharUnits, CharUnits>
15001 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
15002                                    CharUnits BaseAlignment, CharUnits Offset,
15003                                    ASTContext &Ctx) {
15004   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15005        ++PathI) {
15006     const CXXBaseSpecifier *Base = *PathI;
15007     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15008     if (Base->isVirtual()) {
15009       // The complete object may have a lower alignment than the non-virtual
15010       // alignment of the base, in which case the base may be misaligned. Choose
15011       // the smaller of the non-virtual alignment and BaseAlignment, which is a
15012       // conservative lower bound of the complete object alignment.
15013       CharUnits NonVirtualAlignment =
15014           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
15015       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15016       Offset = CharUnits::Zero();
15017     } else {
15018       const ASTRecordLayout &RL =
15019           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
15020       Offset += RL.getBaseClassOffset(BaseDecl);
15021     }
15022     DerivedType = Base->getType();
15023   }
15024 
15025   return std::make_pair(BaseAlignment, Offset);
15026 }
15027 
15028 /// Compute the alignment and offset of a binary additive operator.
15029 static Optional<std::pair<CharUnits, CharUnits>>
15030 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
15031                                      bool IsSub, ASTContext &Ctx) {
15032   QualType PointeeType = PtrE->getType()->getPointeeType();
15033 
15034   if (!PointeeType->isConstantSizeType())
15035     return llvm::None;
15036 
15037   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
15038 
15039   if (!P)
15040     return llvm::None;
15041 
15042   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
15043   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15044     CharUnits Offset = EltSize * IdxRes->getExtValue();
15045     if (IsSub)
15046       Offset = -Offset;
15047     return std::make_pair(P->first, P->second + Offset);
15048   }
15049 
15050   // If the integer expression isn't a constant expression, compute the lower
15051   // bound of the alignment using the alignment and offset of the pointer
15052   // expression and the element size.
15053   return std::make_pair(
15054       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15055       CharUnits::Zero());
15056 }
15057 
15058 /// This helper function takes an lvalue expression and returns the alignment of
15059 /// a VarDecl and a constant offset from the VarDecl.
15060 Optional<std::pair<CharUnits, CharUnits>>
15061 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
15062   E = E->IgnoreParens();
15063   switch (E->getStmtClass()) {
15064   default:
15065     break;
15066   case Stmt::CStyleCastExprClass:
15067   case Stmt::CXXStaticCastExprClass:
15068   case Stmt::ImplicitCastExprClass: {
15069     auto *CE = cast<CastExpr>(E);
15070     const Expr *From = CE->getSubExpr();
15071     switch (CE->getCastKind()) {
15072     default:
15073       break;
15074     case CK_NoOp:
15075       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15076     case CK_UncheckedDerivedToBase:
15077     case CK_DerivedToBase: {
15078       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15079       if (!P)
15080         break;
15081       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15082                                                 P->second, Ctx);
15083     }
15084     }
15085     break;
15086   }
15087   case Stmt::ArraySubscriptExprClass: {
15088     auto *ASE = cast<ArraySubscriptExpr>(E);
15089     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
15090                                                 false, Ctx);
15091   }
15092   case Stmt::DeclRefExprClass: {
15093     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15094       // FIXME: If VD is captured by copy or is an escaping __block variable,
15095       // use the alignment of VD's type.
15096       if (!VD->getType()->isReferenceType())
15097         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15098       if (VD->hasInit())
15099         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15100     }
15101     break;
15102   }
15103   case Stmt::MemberExprClass: {
15104     auto *ME = cast<MemberExpr>(E);
15105     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15106     if (!FD || FD->getType()->isReferenceType() ||
15107         FD->getParent()->isInvalidDecl())
15108       break;
15109     Optional<std::pair<CharUnits, CharUnits>> P;
15110     if (ME->isArrow())
15111       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15112     else
15113       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15114     if (!P)
15115       break;
15116     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15117     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15118     return std::make_pair(P->first,
15119                           P->second + CharUnits::fromQuantity(Offset));
15120   }
15121   case Stmt::UnaryOperatorClass: {
15122     auto *UO = cast<UnaryOperator>(E);
15123     switch (UO->getOpcode()) {
15124     default:
15125       break;
15126     case UO_Deref:
15127       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
15128     }
15129     break;
15130   }
15131   case Stmt::BinaryOperatorClass: {
15132     auto *BO = cast<BinaryOperator>(E);
15133     auto Opcode = BO->getOpcode();
15134     switch (Opcode) {
15135     default:
15136       break;
15137     case BO_Comma:
15138       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
15139     }
15140     break;
15141   }
15142   }
15143   return llvm::None;
15144 }
15145 
15146 /// This helper function takes a pointer expression and returns the alignment of
15147 /// a VarDecl and a constant offset from the VarDecl.
15148 Optional<std::pair<CharUnits, CharUnits>>
15149 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
15150   E = E->IgnoreParens();
15151   switch (E->getStmtClass()) {
15152   default:
15153     break;
15154   case Stmt::CStyleCastExprClass:
15155   case Stmt::CXXStaticCastExprClass:
15156   case Stmt::ImplicitCastExprClass: {
15157     auto *CE = cast<CastExpr>(E);
15158     const Expr *From = CE->getSubExpr();
15159     switch (CE->getCastKind()) {
15160     default:
15161       break;
15162     case CK_NoOp:
15163       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15164     case CK_ArrayToPointerDecay:
15165       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15166     case CK_UncheckedDerivedToBase:
15167     case CK_DerivedToBase: {
15168       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15169       if (!P)
15170         break;
15171       return getDerivedToBaseAlignmentAndOffset(
15172           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15173     }
15174     }
15175     break;
15176   }
15177   case Stmt::CXXThisExprClass: {
15178     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15179     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
15180     return std::make_pair(Alignment, CharUnits::Zero());
15181   }
15182   case Stmt::UnaryOperatorClass: {
15183     auto *UO = cast<UnaryOperator>(E);
15184     if (UO->getOpcode() == UO_AddrOf)
15185       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
15186     break;
15187   }
15188   case Stmt::BinaryOperatorClass: {
15189     auto *BO = cast<BinaryOperator>(E);
15190     auto Opcode = BO->getOpcode();
15191     switch (Opcode) {
15192     default:
15193       break;
15194     case BO_Add:
15195     case BO_Sub: {
15196       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15197       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15198         std::swap(LHS, RHS);
15199       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15200                                                   Ctx);
15201     }
15202     case BO_Comma:
15203       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15204     }
15205     break;
15206   }
15207   }
15208   return llvm::None;
15209 }
15210 
15211 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
15212   // See if we can compute the alignment of a VarDecl and an offset from it.
15213   Optional<std::pair<CharUnits, CharUnits>> P =
15214       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
15215 
15216   if (P)
15217     return P->first.alignmentAtOffset(P->second);
15218 
15219   // If that failed, return the type's alignment.
15220   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
15221 }
15222 
15223 /// CheckCastAlign - Implements -Wcast-align, which warns when a
15224 /// pointer cast increases the alignment requirements.
15225 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
15226   // This is actually a lot of work to potentially be doing on every
15227   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15228   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15229     return;
15230 
15231   // Ignore dependent types.
15232   if (T->isDependentType() || Op->getType()->isDependentType())
15233     return;
15234 
15235   // Require that the destination be a pointer type.
15236   const PointerType *DestPtr = T->getAs<PointerType>();
15237   if (!DestPtr) return;
15238 
15239   // If the destination has alignment 1, we're done.
15240   QualType DestPointee = DestPtr->getPointeeType();
15241   if (DestPointee->isIncompleteType()) return;
15242   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15243   if (DestAlign.isOne()) return;
15244 
15245   // Require that the source be a pointer type.
15246   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15247   if (!SrcPtr) return;
15248   QualType SrcPointee = SrcPtr->getPointeeType();
15249 
15250   // Explicitly allow casts from cv void*.  We already implicitly
15251   // allowed casts to cv void*, since they have alignment 1.
15252   // Also allow casts involving incomplete types, which implicitly
15253   // includes 'void'.
15254   if (SrcPointee->isIncompleteType()) return;
15255 
15256   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15257 
15258   if (SrcAlign >= DestAlign) return;
15259 
15260   Diag(TRange.getBegin(), diag::warn_cast_align)
15261     << Op->getType() << T
15262     << static_cast<unsigned>(SrcAlign.getQuantity())
15263     << static_cast<unsigned>(DestAlign.getQuantity())
15264     << TRange << Op->getSourceRange();
15265 }
15266 
15267 /// Check whether this array fits the idiom of a size-one tail padded
15268 /// array member of a struct.
15269 ///
15270 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
15271 /// commonly used to emulate flexible arrays in C89 code.
15272 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
15273                                     const NamedDecl *ND) {
15274   if (Size != 1 || !ND) return false;
15275 
15276   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
15277   if (!FD) return false;
15278 
15279   // Don't consider sizes resulting from macro expansions or template argument
15280   // substitution to form C89 tail-padded arrays.
15281 
15282   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
15283   while (TInfo) {
15284     TypeLoc TL = TInfo->getTypeLoc();
15285     // Look through typedefs.
15286     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
15287       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
15288       TInfo = TDL->getTypeSourceInfo();
15289       continue;
15290     }
15291     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
15292       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
15293       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
15294         return false;
15295     }
15296     break;
15297   }
15298 
15299   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
15300   if (!RD) return false;
15301   if (RD->isUnion()) return false;
15302   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15303     if (!CRD->isStandardLayout()) return false;
15304   }
15305 
15306   // See if this is the last field decl in the record.
15307   const Decl *D = FD;
15308   while ((D = D->getNextDeclInContext()))
15309     if (isa<FieldDecl>(D))
15310       return false;
15311   return true;
15312 }
15313 
15314 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15315                             const ArraySubscriptExpr *ASE,
15316                             bool AllowOnePastEnd, bool IndexNegated) {
15317   // Already diagnosed by the constant evaluator.
15318   if (isConstantEvaluated())
15319     return;
15320 
15321   IndexExpr = IndexExpr->IgnoreParenImpCasts();
15322   if (IndexExpr->isValueDependent())
15323     return;
15324 
15325   const Type *EffectiveType =
15326       BaseExpr->getType()->getPointeeOrArrayElementType();
15327   BaseExpr = BaseExpr->IgnoreParenCasts();
15328   const ConstantArrayType *ArrayTy =
15329       Context.getAsConstantArrayType(BaseExpr->getType());
15330 
15331   const Type *BaseType =
15332       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15333   bool IsUnboundedArray = (BaseType == nullptr);
15334   if (EffectiveType->isDependentType() ||
15335       (!IsUnboundedArray && BaseType->isDependentType()))
15336     return;
15337 
15338   Expr::EvalResult Result;
15339   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15340     return;
15341 
15342   llvm::APSInt index = Result.Val.getInt();
15343   if (IndexNegated) {
15344     index.setIsUnsigned(false);
15345     index = -index;
15346   }
15347 
15348   const NamedDecl *ND = nullptr;
15349   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15350     ND = DRE->getDecl();
15351   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
15352     ND = ME->getMemberDecl();
15353 
15354   if (IsUnboundedArray) {
15355     if (index.isUnsigned() || !index.isNegative()) {
15356       const auto &ASTC = getASTContext();
15357       unsigned AddrBits =
15358           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
15359               EffectiveType->getCanonicalTypeInternal()));
15360       if (index.getBitWidth() < AddrBits)
15361         index = index.zext(AddrBits);
15362       Optional<CharUnits> ElemCharUnits =
15363           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15364       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15365       // pointer) bounds-checking isn't meaningful.
15366       if (!ElemCharUnits)
15367         return;
15368       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15369       // If index has more active bits than address space, we already know
15370       // we have a bounds violation to warn about.  Otherwise, compute
15371       // address of (index + 1)th element, and warn about bounds violation
15372       // only if that address exceeds address space.
15373       if (index.getActiveBits() <= AddrBits) {
15374         bool Overflow;
15375         llvm::APInt Product(index);
15376         Product += 1;
15377         Product = Product.umul_ov(ElemBytes, Overflow);
15378         if (!Overflow && Product.getActiveBits() <= AddrBits)
15379           return;
15380       }
15381 
15382       // Need to compute max possible elements in address space, since that
15383       // is included in diag message.
15384       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15385       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15386       MaxElems += 1;
15387       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15388       MaxElems = MaxElems.udiv(ElemBytes);
15389 
15390       unsigned DiagID =
15391           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15392               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15393 
15394       // Diag message shows element size in bits and in "bytes" (platform-
15395       // dependent CharUnits)
15396       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15397                           PDiag(DiagID)
15398                               << toString(index, 10, true) << AddrBits
15399                               << (unsigned)ASTC.toBits(*ElemCharUnits)
15400                               << toString(ElemBytes, 10, false)
15401                               << toString(MaxElems, 10, false)
15402                               << (unsigned)MaxElems.getLimitedValue(~0U)
15403                               << IndexExpr->getSourceRange());
15404 
15405       if (!ND) {
15406         // Try harder to find a NamedDecl to point at in the note.
15407         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15408           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15409         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15410           ND = DRE->getDecl();
15411         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15412           ND = ME->getMemberDecl();
15413       }
15414 
15415       if (ND)
15416         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15417                             PDiag(diag::note_array_declared_here) << ND);
15418     }
15419     return;
15420   }
15421 
15422   if (index.isUnsigned() || !index.isNegative()) {
15423     // It is possible that the type of the base expression after
15424     // IgnoreParenCasts is incomplete, even though the type of the base
15425     // expression before IgnoreParenCasts is complete (see PR39746 for an
15426     // example). In this case we have no information about whether the array
15427     // access exceeds the array bounds. However we can still diagnose an array
15428     // access which precedes the array bounds.
15429     if (BaseType->isIncompleteType())
15430       return;
15431 
15432     llvm::APInt size = ArrayTy->getSize();
15433     if (!size.isStrictlyPositive())
15434       return;
15435 
15436     if (BaseType != EffectiveType) {
15437       // Make sure we're comparing apples to apples when comparing index to size
15438       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15439       uint64_t array_typesize = Context.getTypeSize(BaseType);
15440       // Handle ptrarith_typesize being zero, such as when casting to void*
15441       if (!ptrarith_typesize) ptrarith_typesize = 1;
15442       if (ptrarith_typesize != array_typesize) {
15443         // There's a cast to a different size type involved
15444         uint64_t ratio = array_typesize / ptrarith_typesize;
15445         // TODO: Be smarter about handling cases where array_typesize is not a
15446         // multiple of ptrarith_typesize
15447         if (ptrarith_typesize * ratio == array_typesize)
15448           size *= llvm::APInt(size.getBitWidth(), ratio);
15449       }
15450     }
15451 
15452     if (size.getBitWidth() > index.getBitWidth())
15453       index = index.zext(size.getBitWidth());
15454     else if (size.getBitWidth() < index.getBitWidth())
15455       size = size.zext(index.getBitWidth());
15456 
15457     // For array subscripting the index must be less than size, but for pointer
15458     // arithmetic also allow the index (offset) to be equal to size since
15459     // computing the next address after the end of the array is legal and
15460     // commonly done e.g. in C++ iterators and range-based for loops.
15461     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15462       return;
15463 
15464     // Also don't warn for arrays of size 1 which are members of some
15465     // structure. These are often used to approximate flexible arrays in C89
15466     // code.
15467     if (IsTailPaddedMemberArray(*this, size, ND))
15468       return;
15469 
15470     // Suppress the warning if the subscript expression (as identified by the
15471     // ']' location) and the index expression are both from macro expansions
15472     // within a system header.
15473     if (ASE) {
15474       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15475           ASE->getRBracketLoc());
15476       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15477         SourceLocation IndexLoc =
15478             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15479         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15480           return;
15481       }
15482     }
15483 
15484     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15485                           : diag::warn_ptr_arith_exceeds_bounds;
15486 
15487     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15488                         PDiag(DiagID) << toString(index, 10, true)
15489                                       << toString(size, 10, true)
15490                                       << (unsigned)size.getLimitedValue(~0U)
15491                                       << IndexExpr->getSourceRange());
15492   } else {
15493     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15494     if (!ASE) {
15495       DiagID = diag::warn_ptr_arith_precedes_bounds;
15496       if (index.isNegative()) index = -index;
15497     }
15498 
15499     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15500                         PDiag(DiagID) << toString(index, 10, true)
15501                                       << IndexExpr->getSourceRange());
15502   }
15503 
15504   if (!ND) {
15505     // Try harder to find a NamedDecl to point at in the note.
15506     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15507       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15508     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15509       ND = DRE->getDecl();
15510     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15511       ND = ME->getMemberDecl();
15512   }
15513 
15514   if (ND)
15515     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15516                         PDiag(diag::note_array_declared_here) << ND);
15517 }
15518 
15519 void Sema::CheckArrayAccess(const Expr *expr) {
15520   int AllowOnePastEnd = 0;
15521   while (expr) {
15522     expr = expr->IgnoreParenImpCasts();
15523     switch (expr->getStmtClass()) {
15524       case Stmt::ArraySubscriptExprClass: {
15525         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15526         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15527                          AllowOnePastEnd > 0);
15528         expr = ASE->getBase();
15529         break;
15530       }
15531       case Stmt::MemberExprClass: {
15532         expr = cast<MemberExpr>(expr)->getBase();
15533         break;
15534       }
15535       case Stmt::OMPArraySectionExprClass: {
15536         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15537         if (ASE->getLowerBound())
15538           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15539                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15540         return;
15541       }
15542       case Stmt::UnaryOperatorClass: {
15543         // Only unwrap the * and & unary operators
15544         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15545         expr = UO->getSubExpr();
15546         switch (UO->getOpcode()) {
15547           case UO_AddrOf:
15548             AllowOnePastEnd++;
15549             break;
15550           case UO_Deref:
15551             AllowOnePastEnd--;
15552             break;
15553           default:
15554             return;
15555         }
15556         break;
15557       }
15558       case Stmt::ConditionalOperatorClass: {
15559         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15560         if (const Expr *lhs = cond->getLHS())
15561           CheckArrayAccess(lhs);
15562         if (const Expr *rhs = cond->getRHS())
15563           CheckArrayAccess(rhs);
15564         return;
15565       }
15566       case Stmt::CXXOperatorCallExprClass: {
15567         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15568         for (const auto *Arg : OCE->arguments())
15569           CheckArrayAccess(Arg);
15570         return;
15571       }
15572       default:
15573         return;
15574     }
15575   }
15576 }
15577 
15578 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15579 
15580 namespace {
15581 
15582 struct RetainCycleOwner {
15583   VarDecl *Variable = nullptr;
15584   SourceRange Range;
15585   SourceLocation Loc;
15586   bool Indirect = false;
15587 
15588   RetainCycleOwner() = default;
15589 
15590   void setLocsFrom(Expr *e) {
15591     Loc = e->getExprLoc();
15592     Range = e->getSourceRange();
15593   }
15594 };
15595 
15596 } // namespace
15597 
15598 /// Consider whether capturing the given variable can possibly lead to
15599 /// a retain cycle.
15600 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15601   // In ARC, it's captured strongly iff the variable has __strong
15602   // lifetime.  In MRR, it's captured strongly if the variable is
15603   // __block and has an appropriate type.
15604   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15605     return false;
15606 
15607   owner.Variable = var;
15608   if (ref)
15609     owner.setLocsFrom(ref);
15610   return true;
15611 }
15612 
15613 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15614   while (true) {
15615     e = e->IgnoreParens();
15616     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15617       switch (cast->getCastKind()) {
15618       case CK_BitCast:
15619       case CK_LValueBitCast:
15620       case CK_LValueToRValue:
15621       case CK_ARCReclaimReturnedObject:
15622         e = cast->getSubExpr();
15623         continue;
15624 
15625       default:
15626         return false;
15627       }
15628     }
15629 
15630     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15631       ObjCIvarDecl *ivar = ref->getDecl();
15632       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15633         return false;
15634 
15635       // Try to find a retain cycle in the base.
15636       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15637         return false;
15638 
15639       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15640       owner.Indirect = true;
15641       return true;
15642     }
15643 
15644     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15645       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15646       if (!var) return false;
15647       return considerVariable(var, ref, owner);
15648     }
15649 
15650     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15651       if (member->isArrow()) return false;
15652 
15653       // Don't count this as an indirect ownership.
15654       e = member->getBase();
15655       continue;
15656     }
15657 
15658     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15659       // Only pay attention to pseudo-objects on property references.
15660       ObjCPropertyRefExpr *pre
15661         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15662                                               ->IgnoreParens());
15663       if (!pre) return false;
15664       if (pre->isImplicitProperty()) return false;
15665       ObjCPropertyDecl *property = pre->getExplicitProperty();
15666       if (!property->isRetaining() &&
15667           !(property->getPropertyIvarDecl() &&
15668             property->getPropertyIvarDecl()->getType()
15669               .getObjCLifetime() == Qualifiers::OCL_Strong))
15670           return false;
15671 
15672       owner.Indirect = true;
15673       if (pre->isSuperReceiver()) {
15674         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15675         if (!owner.Variable)
15676           return false;
15677         owner.Loc = pre->getLocation();
15678         owner.Range = pre->getSourceRange();
15679         return true;
15680       }
15681       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15682                               ->getSourceExpr());
15683       continue;
15684     }
15685 
15686     // Array ivars?
15687 
15688     return false;
15689   }
15690 }
15691 
15692 namespace {
15693 
15694   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15695     ASTContext &Context;
15696     VarDecl *Variable;
15697     Expr *Capturer = nullptr;
15698     bool VarWillBeReased = false;
15699 
15700     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15701         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15702           Context(Context), Variable(variable) {}
15703 
15704     void VisitDeclRefExpr(DeclRefExpr *ref) {
15705       if (ref->getDecl() == Variable && !Capturer)
15706         Capturer = ref;
15707     }
15708 
15709     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15710       if (Capturer) return;
15711       Visit(ref->getBase());
15712       if (Capturer && ref->isFreeIvar())
15713         Capturer = ref;
15714     }
15715 
15716     void VisitBlockExpr(BlockExpr *block) {
15717       // Look inside nested blocks
15718       if (block->getBlockDecl()->capturesVariable(Variable))
15719         Visit(block->getBlockDecl()->getBody());
15720     }
15721 
15722     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15723       if (Capturer) return;
15724       if (OVE->getSourceExpr())
15725         Visit(OVE->getSourceExpr());
15726     }
15727 
15728     void VisitBinaryOperator(BinaryOperator *BinOp) {
15729       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15730         return;
15731       Expr *LHS = BinOp->getLHS();
15732       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15733         if (DRE->getDecl() != Variable)
15734           return;
15735         if (Expr *RHS = BinOp->getRHS()) {
15736           RHS = RHS->IgnoreParenCasts();
15737           Optional<llvm::APSInt> Value;
15738           VarWillBeReased =
15739               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15740                *Value == 0);
15741         }
15742       }
15743     }
15744   };
15745 
15746 } // namespace
15747 
15748 /// Check whether the given argument is a block which captures a
15749 /// variable.
15750 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15751   assert(owner.Variable && owner.Loc.isValid());
15752 
15753   e = e->IgnoreParenCasts();
15754 
15755   // Look through [^{...} copy] and Block_copy(^{...}).
15756   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15757     Selector Cmd = ME->getSelector();
15758     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15759       e = ME->getInstanceReceiver();
15760       if (!e)
15761         return nullptr;
15762       e = e->IgnoreParenCasts();
15763     }
15764   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15765     if (CE->getNumArgs() == 1) {
15766       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15767       if (Fn) {
15768         const IdentifierInfo *FnI = Fn->getIdentifier();
15769         if (FnI && FnI->isStr("_Block_copy")) {
15770           e = CE->getArg(0)->IgnoreParenCasts();
15771         }
15772       }
15773     }
15774   }
15775 
15776   BlockExpr *block = dyn_cast<BlockExpr>(e);
15777   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15778     return nullptr;
15779 
15780   FindCaptureVisitor visitor(S.Context, owner.Variable);
15781   visitor.Visit(block->getBlockDecl()->getBody());
15782   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15783 }
15784 
15785 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15786                                 RetainCycleOwner &owner) {
15787   assert(capturer);
15788   assert(owner.Variable && owner.Loc.isValid());
15789 
15790   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15791     << owner.Variable << capturer->getSourceRange();
15792   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15793     << owner.Indirect << owner.Range;
15794 }
15795 
15796 /// Check for a keyword selector that starts with the word 'add' or
15797 /// 'set'.
15798 static bool isSetterLikeSelector(Selector sel) {
15799   if (sel.isUnarySelector()) return false;
15800 
15801   StringRef str = sel.getNameForSlot(0);
15802   while (!str.empty() && str.front() == '_') str = str.substr(1);
15803   if (str.startswith("set"))
15804     str = str.substr(3);
15805   else if (str.startswith("add")) {
15806     // Specially allow 'addOperationWithBlock:'.
15807     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15808       return false;
15809     str = str.substr(3);
15810   }
15811   else
15812     return false;
15813 
15814   if (str.empty()) return true;
15815   return !isLowercase(str.front());
15816 }
15817 
15818 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15819                                                     ObjCMessageExpr *Message) {
15820   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15821                                                 Message->getReceiverInterface(),
15822                                                 NSAPI::ClassId_NSMutableArray);
15823   if (!IsMutableArray) {
15824     return None;
15825   }
15826 
15827   Selector Sel = Message->getSelector();
15828 
15829   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15830     S.NSAPIObj->getNSArrayMethodKind(Sel);
15831   if (!MKOpt) {
15832     return None;
15833   }
15834 
15835   NSAPI::NSArrayMethodKind MK = *MKOpt;
15836 
15837   switch (MK) {
15838     case NSAPI::NSMutableArr_addObject:
15839     case NSAPI::NSMutableArr_insertObjectAtIndex:
15840     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15841       return 0;
15842     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15843       return 1;
15844 
15845     default:
15846       return None;
15847   }
15848 
15849   return None;
15850 }
15851 
15852 static
15853 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15854                                                   ObjCMessageExpr *Message) {
15855   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15856                                             Message->getReceiverInterface(),
15857                                             NSAPI::ClassId_NSMutableDictionary);
15858   if (!IsMutableDictionary) {
15859     return None;
15860   }
15861 
15862   Selector Sel = Message->getSelector();
15863 
15864   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15865     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15866   if (!MKOpt) {
15867     return None;
15868   }
15869 
15870   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15871 
15872   switch (MK) {
15873     case NSAPI::NSMutableDict_setObjectForKey:
15874     case NSAPI::NSMutableDict_setValueForKey:
15875     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15876       return 0;
15877 
15878     default:
15879       return None;
15880   }
15881 
15882   return None;
15883 }
15884 
15885 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15886   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15887                                                 Message->getReceiverInterface(),
15888                                                 NSAPI::ClassId_NSMutableSet);
15889 
15890   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15891                                             Message->getReceiverInterface(),
15892                                             NSAPI::ClassId_NSMutableOrderedSet);
15893   if (!IsMutableSet && !IsMutableOrderedSet) {
15894     return None;
15895   }
15896 
15897   Selector Sel = Message->getSelector();
15898 
15899   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15900   if (!MKOpt) {
15901     return None;
15902   }
15903 
15904   NSAPI::NSSetMethodKind MK = *MKOpt;
15905 
15906   switch (MK) {
15907     case NSAPI::NSMutableSet_addObject:
15908     case NSAPI::NSOrderedSet_setObjectAtIndex:
15909     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15910     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15911       return 0;
15912     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15913       return 1;
15914   }
15915 
15916   return None;
15917 }
15918 
15919 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15920   if (!Message->isInstanceMessage()) {
15921     return;
15922   }
15923 
15924   Optional<int> ArgOpt;
15925 
15926   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15927       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15928       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15929     return;
15930   }
15931 
15932   int ArgIndex = *ArgOpt;
15933 
15934   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15935   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15936     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15937   }
15938 
15939   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15940     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15941       if (ArgRE->isObjCSelfExpr()) {
15942         Diag(Message->getSourceRange().getBegin(),
15943              diag::warn_objc_circular_container)
15944           << ArgRE->getDecl() << StringRef("'super'");
15945       }
15946     }
15947   } else {
15948     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15949 
15950     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15951       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15952     }
15953 
15954     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15955       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15956         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15957           ValueDecl *Decl = ReceiverRE->getDecl();
15958           Diag(Message->getSourceRange().getBegin(),
15959                diag::warn_objc_circular_container)
15960             << Decl << Decl;
15961           if (!ArgRE->isObjCSelfExpr()) {
15962             Diag(Decl->getLocation(),
15963                  diag::note_objc_circular_container_declared_here)
15964               << Decl;
15965           }
15966         }
15967       }
15968     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15969       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15970         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15971           ObjCIvarDecl *Decl = IvarRE->getDecl();
15972           Diag(Message->getSourceRange().getBegin(),
15973                diag::warn_objc_circular_container)
15974             << Decl << Decl;
15975           Diag(Decl->getLocation(),
15976                diag::note_objc_circular_container_declared_here)
15977             << Decl;
15978         }
15979       }
15980     }
15981   }
15982 }
15983 
15984 /// Check a message send to see if it's likely to cause a retain cycle.
15985 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15986   // Only check instance methods whose selector looks like a setter.
15987   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15988     return;
15989 
15990   // Try to find a variable that the receiver is strongly owned by.
15991   RetainCycleOwner owner;
15992   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15993     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15994       return;
15995   } else {
15996     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15997     owner.Variable = getCurMethodDecl()->getSelfDecl();
15998     owner.Loc = msg->getSuperLoc();
15999     owner.Range = msg->getSuperLoc();
16000   }
16001 
16002   // Check whether the receiver is captured by any of the arguments.
16003   const ObjCMethodDecl *MD = msg->getMethodDecl();
16004   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
16005     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
16006       // noescape blocks should not be retained by the method.
16007       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
16008         continue;
16009       return diagnoseRetainCycle(*this, capturer, owner);
16010     }
16011   }
16012 }
16013 
16014 /// Check a property assign to see if it's likely to cause a retain cycle.
16015 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
16016   RetainCycleOwner owner;
16017   if (!findRetainCycleOwner(*this, receiver, owner))
16018     return;
16019 
16020   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
16021     diagnoseRetainCycle(*this, capturer, owner);
16022 }
16023 
16024 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
16025   RetainCycleOwner Owner;
16026   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
16027     return;
16028 
16029   // Because we don't have an expression for the variable, we have to set the
16030   // location explicitly here.
16031   Owner.Loc = Var->getLocation();
16032   Owner.Range = Var->getSourceRange();
16033 
16034   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
16035     diagnoseRetainCycle(*this, Capturer, Owner);
16036 }
16037 
16038 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
16039                                      Expr *RHS, bool isProperty) {
16040   // Check if RHS is an Objective-C object literal, which also can get
16041   // immediately zapped in a weak reference.  Note that we explicitly
16042   // allow ObjCStringLiterals, since those are designed to never really die.
16043   RHS = RHS->IgnoreParenImpCasts();
16044 
16045   // This enum needs to match with the 'select' in
16046   // warn_objc_arc_literal_assign (off-by-1).
16047   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
16048   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
16049     return false;
16050 
16051   S.Diag(Loc, diag::warn_arc_literal_assign)
16052     << (unsigned) Kind
16053     << (isProperty ? 0 : 1)
16054     << RHS->getSourceRange();
16055 
16056   return true;
16057 }
16058 
16059 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
16060                                     Qualifiers::ObjCLifetime LT,
16061                                     Expr *RHS, bool isProperty) {
16062   // Strip off any implicit cast added to get to the one ARC-specific.
16063   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16064     if (cast->getCastKind() == CK_ARCConsumeObject) {
16065       S.Diag(Loc, diag::warn_arc_retained_assign)
16066         << (LT == Qualifiers::OCL_ExplicitNone)
16067         << (isProperty ? 0 : 1)
16068         << RHS->getSourceRange();
16069       return true;
16070     }
16071     RHS = cast->getSubExpr();
16072   }
16073 
16074   if (LT == Qualifiers::OCL_Weak &&
16075       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16076     return true;
16077 
16078   return false;
16079 }
16080 
16081 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
16082                               QualType LHS, Expr *RHS) {
16083   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
16084 
16085   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
16086     return false;
16087 
16088   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
16089     return true;
16090 
16091   return false;
16092 }
16093 
16094 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
16095                               Expr *LHS, Expr *RHS) {
16096   QualType LHSType;
16097   // PropertyRef on LHS type need be directly obtained from
16098   // its declaration as it has a PseudoType.
16099   ObjCPropertyRefExpr *PRE
16100     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
16101   if (PRE && !PRE->isImplicitProperty()) {
16102     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16103     if (PD)
16104       LHSType = PD->getType();
16105   }
16106 
16107   if (LHSType.isNull())
16108     LHSType = LHS->getType();
16109 
16110   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
16111 
16112   if (LT == Qualifiers::OCL_Weak) {
16113     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
16114       getCurFunction()->markSafeWeakUse(LHS);
16115   }
16116 
16117   if (checkUnsafeAssigns(Loc, LHSType, RHS))
16118     return;
16119 
16120   // FIXME. Check for other life times.
16121   if (LT != Qualifiers::OCL_None)
16122     return;
16123 
16124   if (PRE) {
16125     if (PRE->isImplicitProperty())
16126       return;
16127     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16128     if (!PD)
16129       return;
16130 
16131     unsigned Attributes = PD->getPropertyAttributes();
16132     if (Attributes & ObjCPropertyAttribute::kind_assign) {
16133       // when 'assign' attribute was not explicitly specified
16134       // by user, ignore it and rely on property type itself
16135       // for lifetime info.
16136       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16137       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16138           LHSType->isObjCRetainableType())
16139         return;
16140 
16141       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16142         if (cast->getCastKind() == CK_ARCConsumeObject) {
16143           Diag(Loc, diag::warn_arc_retained_property_assign)
16144           << RHS->getSourceRange();
16145           return;
16146         }
16147         RHS = cast->getSubExpr();
16148       }
16149     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16150       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
16151         return;
16152     }
16153   }
16154 }
16155 
16156 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16157 
16158 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16159                                         SourceLocation StmtLoc,
16160                                         const NullStmt *Body) {
16161   // Do not warn if the body is a macro that expands to nothing, e.g:
16162   //
16163   // #define CALL(x)
16164   // if (condition)
16165   //   CALL(0);
16166   if (Body->hasLeadingEmptyMacro())
16167     return false;
16168 
16169   // Get line numbers of statement and body.
16170   bool StmtLineInvalid;
16171   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16172                                                       &StmtLineInvalid);
16173   if (StmtLineInvalid)
16174     return false;
16175 
16176   bool BodyLineInvalid;
16177   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16178                                                       &BodyLineInvalid);
16179   if (BodyLineInvalid)
16180     return false;
16181 
16182   // Warn if null statement and body are on the same line.
16183   if (StmtLine != BodyLine)
16184     return false;
16185 
16186   return true;
16187 }
16188 
16189 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
16190                                  const Stmt *Body,
16191                                  unsigned DiagID) {
16192   // Since this is a syntactic check, don't emit diagnostic for template
16193   // instantiations, this just adds noise.
16194   if (CurrentInstantiationScope)
16195     return;
16196 
16197   // The body should be a null statement.
16198   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16199   if (!NBody)
16200     return;
16201 
16202   // Do the usual checks.
16203   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16204     return;
16205 
16206   Diag(NBody->getSemiLoc(), DiagID);
16207   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16208 }
16209 
16210 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
16211                                  const Stmt *PossibleBody) {
16212   assert(!CurrentInstantiationScope); // Ensured by caller
16213 
16214   SourceLocation StmtLoc;
16215   const Stmt *Body;
16216   unsigned DiagID;
16217   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16218     StmtLoc = FS->getRParenLoc();
16219     Body = FS->getBody();
16220     DiagID = diag::warn_empty_for_body;
16221   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16222     StmtLoc = WS->getCond()->getSourceRange().getEnd();
16223     Body = WS->getBody();
16224     DiagID = diag::warn_empty_while_body;
16225   } else
16226     return; // Neither `for' nor `while'.
16227 
16228   // The body should be a null statement.
16229   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16230   if (!NBody)
16231     return;
16232 
16233   // Skip expensive checks if diagnostic is disabled.
16234   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16235     return;
16236 
16237   // Do the usual checks.
16238   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16239     return;
16240 
16241   // `for(...);' and `while(...);' are popular idioms, so in order to keep
16242   // noise level low, emit diagnostics only if for/while is followed by a
16243   // CompoundStmt, e.g.:
16244   //    for (int i = 0; i < n; i++);
16245   //    {
16246   //      a(i);
16247   //    }
16248   // or if for/while is followed by a statement with more indentation
16249   // than for/while itself:
16250   //    for (int i = 0; i < n; i++);
16251   //      a(i);
16252   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16253   if (!ProbableTypo) {
16254     bool BodyColInvalid;
16255     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16256         PossibleBody->getBeginLoc(), &BodyColInvalid);
16257     if (BodyColInvalid)
16258       return;
16259 
16260     bool StmtColInvalid;
16261     unsigned StmtCol =
16262         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16263     if (StmtColInvalid)
16264       return;
16265 
16266     if (BodyCol > StmtCol)
16267       ProbableTypo = true;
16268   }
16269 
16270   if (ProbableTypo) {
16271     Diag(NBody->getSemiLoc(), DiagID);
16272     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16273   }
16274 }
16275 
16276 //===--- CHECK: Warn on self move with std::move. -------------------------===//
16277 
16278 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
16279 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16280                              SourceLocation OpLoc) {
16281   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16282     return;
16283 
16284   if (inTemplateInstantiation())
16285     return;
16286 
16287   // Strip parens and casts away.
16288   LHSExpr = LHSExpr->IgnoreParenImpCasts();
16289   RHSExpr = RHSExpr->IgnoreParenImpCasts();
16290 
16291   // Check for a call expression
16292   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
16293   if (!CE || CE->getNumArgs() != 1)
16294     return;
16295 
16296   // Check for a call to std::move
16297   if (!CE->isCallToStdMove())
16298     return;
16299 
16300   // Get argument from std::move
16301   RHSExpr = CE->getArg(0);
16302 
16303   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16304   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16305 
16306   // Two DeclRefExpr's, check that the decls are the same.
16307   if (LHSDeclRef && RHSDeclRef) {
16308     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16309       return;
16310     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16311         RHSDeclRef->getDecl()->getCanonicalDecl())
16312       return;
16313 
16314     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16315                                         << LHSExpr->getSourceRange()
16316                                         << RHSExpr->getSourceRange();
16317     return;
16318   }
16319 
16320   // Member variables require a different approach to check for self moves.
16321   // MemberExpr's are the same if every nested MemberExpr refers to the same
16322   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16323   // the base Expr's are CXXThisExpr's.
16324   const Expr *LHSBase = LHSExpr;
16325   const Expr *RHSBase = RHSExpr;
16326   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16327   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16328   if (!LHSME || !RHSME)
16329     return;
16330 
16331   while (LHSME && RHSME) {
16332     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16333         RHSME->getMemberDecl()->getCanonicalDecl())
16334       return;
16335 
16336     LHSBase = LHSME->getBase();
16337     RHSBase = RHSME->getBase();
16338     LHSME = dyn_cast<MemberExpr>(LHSBase);
16339     RHSME = dyn_cast<MemberExpr>(RHSBase);
16340   }
16341 
16342   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16343   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16344   if (LHSDeclRef && RHSDeclRef) {
16345     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16346       return;
16347     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16348         RHSDeclRef->getDecl()->getCanonicalDecl())
16349       return;
16350 
16351     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16352                                         << LHSExpr->getSourceRange()
16353                                         << RHSExpr->getSourceRange();
16354     return;
16355   }
16356 
16357   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16358     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16359                                         << LHSExpr->getSourceRange()
16360                                         << RHSExpr->getSourceRange();
16361 }
16362 
16363 //===--- Layout compatibility ----------------------------------------------//
16364 
16365 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
16366 
16367 /// Check if two enumeration types are layout-compatible.
16368 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
16369   // C++11 [dcl.enum] p8:
16370   // Two enumeration types are layout-compatible if they have the same
16371   // underlying type.
16372   return ED1->isComplete() && ED2->isComplete() &&
16373          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16374 }
16375 
16376 /// Check if two fields are layout-compatible.
16377 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
16378                                FieldDecl *Field2) {
16379   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16380     return false;
16381 
16382   if (Field1->isBitField() != Field2->isBitField())
16383     return false;
16384 
16385   if (Field1->isBitField()) {
16386     // Make sure that the bit-fields are the same length.
16387     unsigned Bits1 = Field1->getBitWidthValue(C);
16388     unsigned Bits2 = Field2->getBitWidthValue(C);
16389 
16390     if (Bits1 != Bits2)
16391       return false;
16392   }
16393 
16394   return true;
16395 }
16396 
16397 /// Check if two standard-layout structs are layout-compatible.
16398 /// (C++11 [class.mem] p17)
16399 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
16400                                      RecordDecl *RD2) {
16401   // If both records are C++ classes, check that base classes match.
16402   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
16403     // If one of records is a CXXRecordDecl we are in C++ mode,
16404     // thus the other one is a CXXRecordDecl, too.
16405     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
16406     // Check number of base classes.
16407     if (D1CXX->getNumBases() != D2CXX->getNumBases())
16408       return false;
16409 
16410     // Check the base classes.
16411     for (CXXRecordDecl::base_class_const_iterator
16412                Base1 = D1CXX->bases_begin(),
16413            BaseEnd1 = D1CXX->bases_end(),
16414               Base2 = D2CXX->bases_begin();
16415          Base1 != BaseEnd1;
16416          ++Base1, ++Base2) {
16417       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16418         return false;
16419     }
16420   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16421     // If only RD2 is a C++ class, it should have zero base classes.
16422     if (D2CXX->getNumBases() > 0)
16423       return false;
16424   }
16425 
16426   // Check the fields.
16427   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16428                              Field2End = RD2->field_end(),
16429                              Field1 = RD1->field_begin(),
16430                              Field1End = RD1->field_end();
16431   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16432     if (!isLayoutCompatible(C, *Field1, *Field2))
16433       return false;
16434   }
16435   if (Field1 != Field1End || Field2 != Field2End)
16436     return false;
16437 
16438   return true;
16439 }
16440 
16441 /// Check if two standard-layout unions are layout-compatible.
16442 /// (C++11 [class.mem] p18)
16443 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16444                                     RecordDecl *RD2) {
16445   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16446   for (auto *Field2 : RD2->fields())
16447     UnmatchedFields.insert(Field2);
16448 
16449   for (auto *Field1 : RD1->fields()) {
16450     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16451         I = UnmatchedFields.begin(),
16452         E = UnmatchedFields.end();
16453 
16454     for ( ; I != E; ++I) {
16455       if (isLayoutCompatible(C, Field1, *I)) {
16456         bool Result = UnmatchedFields.erase(*I);
16457         (void) Result;
16458         assert(Result);
16459         break;
16460       }
16461     }
16462     if (I == E)
16463       return false;
16464   }
16465 
16466   return UnmatchedFields.empty();
16467 }
16468 
16469 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16470                                RecordDecl *RD2) {
16471   if (RD1->isUnion() != RD2->isUnion())
16472     return false;
16473 
16474   if (RD1->isUnion())
16475     return isLayoutCompatibleUnion(C, RD1, RD2);
16476   else
16477     return isLayoutCompatibleStruct(C, RD1, RD2);
16478 }
16479 
16480 /// Check if two types are layout-compatible in C++11 sense.
16481 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16482   if (T1.isNull() || T2.isNull())
16483     return false;
16484 
16485   // C++11 [basic.types] p11:
16486   // If two types T1 and T2 are the same type, then T1 and T2 are
16487   // layout-compatible types.
16488   if (C.hasSameType(T1, T2))
16489     return true;
16490 
16491   T1 = T1.getCanonicalType().getUnqualifiedType();
16492   T2 = T2.getCanonicalType().getUnqualifiedType();
16493 
16494   const Type::TypeClass TC1 = T1->getTypeClass();
16495   const Type::TypeClass TC2 = T2->getTypeClass();
16496 
16497   if (TC1 != TC2)
16498     return false;
16499 
16500   if (TC1 == Type::Enum) {
16501     return isLayoutCompatible(C,
16502                               cast<EnumType>(T1)->getDecl(),
16503                               cast<EnumType>(T2)->getDecl());
16504   } else if (TC1 == Type::Record) {
16505     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16506       return false;
16507 
16508     return isLayoutCompatible(C,
16509                               cast<RecordType>(T1)->getDecl(),
16510                               cast<RecordType>(T2)->getDecl());
16511   }
16512 
16513   return false;
16514 }
16515 
16516 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16517 
16518 /// Given a type tag expression find the type tag itself.
16519 ///
16520 /// \param TypeExpr Type tag expression, as it appears in user's code.
16521 ///
16522 /// \param VD Declaration of an identifier that appears in a type tag.
16523 ///
16524 /// \param MagicValue Type tag magic value.
16525 ///
16526 /// \param isConstantEvaluated whether the evalaution should be performed in
16527 
16528 /// constant context.
16529 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16530                             const ValueDecl **VD, uint64_t *MagicValue,
16531                             bool isConstantEvaluated) {
16532   while(true) {
16533     if (!TypeExpr)
16534       return false;
16535 
16536     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16537 
16538     switch (TypeExpr->getStmtClass()) {
16539     case Stmt::UnaryOperatorClass: {
16540       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16541       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16542         TypeExpr = UO->getSubExpr();
16543         continue;
16544       }
16545       return false;
16546     }
16547 
16548     case Stmt::DeclRefExprClass: {
16549       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16550       *VD = DRE->getDecl();
16551       return true;
16552     }
16553 
16554     case Stmt::IntegerLiteralClass: {
16555       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16556       llvm::APInt MagicValueAPInt = IL->getValue();
16557       if (MagicValueAPInt.getActiveBits() <= 64) {
16558         *MagicValue = MagicValueAPInt.getZExtValue();
16559         return true;
16560       } else
16561         return false;
16562     }
16563 
16564     case Stmt::BinaryConditionalOperatorClass:
16565     case Stmt::ConditionalOperatorClass: {
16566       const AbstractConditionalOperator *ACO =
16567           cast<AbstractConditionalOperator>(TypeExpr);
16568       bool Result;
16569       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16570                                                      isConstantEvaluated)) {
16571         if (Result)
16572           TypeExpr = ACO->getTrueExpr();
16573         else
16574           TypeExpr = ACO->getFalseExpr();
16575         continue;
16576       }
16577       return false;
16578     }
16579 
16580     case Stmt::BinaryOperatorClass: {
16581       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16582       if (BO->getOpcode() == BO_Comma) {
16583         TypeExpr = BO->getRHS();
16584         continue;
16585       }
16586       return false;
16587     }
16588 
16589     default:
16590       return false;
16591     }
16592   }
16593 }
16594 
16595 /// Retrieve the C type corresponding to type tag TypeExpr.
16596 ///
16597 /// \param TypeExpr Expression that specifies a type tag.
16598 ///
16599 /// \param MagicValues Registered magic values.
16600 ///
16601 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16602 ///        kind.
16603 ///
16604 /// \param TypeInfo Information about the corresponding C type.
16605 ///
16606 /// \param isConstantEvaluated whether the evalaution should be performed in
16607 /// constant context.
16608 ///
16609 /// \returns true if the corresponding C type was found.
16610 static bool GetMatchingCType(
16611     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16612     const ASTContext &Ctx,
16613     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16614         *MagicValues,
16615     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16616     bool isConstantEvaluated) {
16617   FoundWrongKind = false;
16618 
16619   // Variable declaration that has type_tag_for_datatype attribute.
16620   const ValueDecl *VD = nullptr;
16621 
16622   uint64_t MagicValue;
16623 
16624   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16625     return false;
16626 
16627   if (VD) {
16628     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16629       if (I->getArgumentKind() != ArgumentKind) {
16630         FoundWrongKind = true;
16631         return false;
16632       }
16633       TypeInfo.Type = I->getMatchingCType();
16634       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16635       TypeInfo.MustBeNull = I->getMustBeNull();
16636       return true;
16637     }
16638     return false;
16639   }
16640 
16641   if (!MagicValues)
16642     return false;
16643 
16644   llvm::DenseMap<Sema::TypeTagMagicValue,
16645                  Sema::TypeTagData>::const_iterator I =
16646       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16647   if (I == MagicValues->end())
16648     return false;
16649 
16650   TypeInfo = I->second;
16651   return true;
16652 }
16653 
16654 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16655                                       uint64_t MagicValue, QualType Type,
16656                                       bool LayoutCompatible,
16657                                       bool MustBeNull) {
16658   if (!TypeTagForDatatypeMagicValues)
16659     TypeTagForDatatypeMagicValues.reset(
16660         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16661 
16662   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16663   (*TypeTagForDatatypeMagicValues)[Magic] =
16664       TypeTagData(Type, LayoutCompatible, MustBeNull);
16665 }
16666 
16667 static bool IsSameCharType(QualType T1, QualType T2) {
16668   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16669   if (!BT1)
16670     return false;
16671 
16672   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16673   if (!BT2)
16674     return false;
16675 
16676   BuiltinType::Kind T1Kind = BT1->getKind();
16677   BuiltinType::Kind T2Kind = BT2->getKind();
16678 
16679   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16680          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16681          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16682          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16683 }
16684 
16685 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16686                                     const ArrayRef<const Expr *> ExprArgs,
16687                                     SourceLocation CallSiteLoc) {
16688   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16689   bool IsPointerAttr = Attr->getIsPointer();
16690 
16691   // Retrieve the argument representing the 'type_tag'.
16692   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16693   if (TypeTagIdxAST >= ExprArgs.size()) {
16694     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16695         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16696     return;
16697   }
16698   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16699   bool FoundWrongKind;
16700   TypeTagData TypeInfo;
16701   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16702                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16703                         TypeInfo, isConstantEvaluated())) {
16704     if (FoundWrongKind)
16705       Diag(TypeTagExpr->getExprLoc(),
16706            diag::warn_type_tag_for_datatype_wrong_kind)
16707         << TypeTagExpr->getSourceRange();
16708     return;
16709   }
16710 
16711   // Retrieve the argument representing the 'arg_idx'.
16712   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16713   if (ArgumentIdxAST >= ExprArgs.size()) {
16714     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16715         << 1 << Attr->getArgumentIdx().getSourceIndex();
16716     return;
16717   }
16718   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16719   if (IsPointerAttr) {
16720     // Skip implicit cast of pointer to `void *' (as a function argument).
16721     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16722       if (ICE->getType()->isVoidPointerType() &&
16723           ICE->getCastKind() == CK_BitCast)
16724         ArgumentExpr = ICE->getSubExpr();
16725   }
16726   QualType ArgumentType = ArgumentExpr->getType();
16727 
16728   // Passing a `void*' pointer shouldn't trigger a warning.
16729   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16730     return;
16731 
16732   if (TypeInfo.MustBeNull) {
16733     // Type tag with matching void type requires a null pointer.
16734     if (!ArgumentExpr->isNullPointerConstant(Context,
16735                                              Expr::NPC_ValueDependentIsNotNull)) {
16736       Diag(ArgumentExpr->getExprLoc(),
16737            diag::warn_type_safety_null_pointer_required)
16738           << ArgumentKind->getName()
16739           << ArgumentExpr->getSourceRange()
16740           << TypeTagExpr->getSourceRange();
16741     }
16742     return;
16743   }
16744 
16745   QualType RequiredType = TypeInfo.Type;
16746   if (IsPointerAttr)
16747     RequiredType = Context.getPointerType(RequiredType);
16748 
16749   bool mismatch = false;
16750   if (!TypeInfo.LayoutCompatible) {
16751     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16752 
16753     // C++11 [basic.fundamental] p1:
16754     // Plain char, signed char, and unsigned char are three distinct types.
16755     //
16756     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16757     // char' depending on the current char signedness mode.
16758     if (mismatch)
16759       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16760                                            RequiredType->getPointeeType())) ||
16761           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16762         mismatch = false;
16763   } else
16764     if (IsPointerAttr)
16765       mismatch = !isLayoutCompatible(Context,
16766                                      ArgumentType->getPointeeType(),
16767                                      RequiredType->getPointeeType());
16768     else
16769       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16770 
16771   if (mismatch)
16772     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16773         << ArgumentType << ArgumentKind
16774         << TypeInfo.LayoutCompatible << RequiredType
16775         << ArgumentExpr->getSourceRange()
16776         << TypeTagExpr->getSourceRange();
16777 }
16778 
16779 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16780                                          CharUnits Alignment) {
16781   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16782 }
16783 
16784 void Sema::DiagnoseMisalignedMembers() {
16785   for (MisalignedMember &m : MisalignedMembers) {
16786     const NamedDecl *ND = m.RD;
16787     if (ND->getName().empty()) {
16788       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16789         ND = TD;
16790     }
16791     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16792         << m.MD << ND << m.E->getSourceRange();
16793   }
16794   MisalignedMembers.clear();
16795 }
16796 
16797 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16798   E = E->IgnoreParens();
16799   if (!T->isPointerType() && !T->isIntegerType())
16800     return;
16801   if (isa<UnaryOperator>(E) &&
16802       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16803     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16804     if (isa<MemberExpr>(Op)) {
16805       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16806       if (MA != MisalignedMembers.end() &&
16807           (T->isIntegerType() ||
16808            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16809                                    Context.getTypeAlignInChars(
16810                                        T->getPointeeType()) <= MA->Alignment))))
16811         MisalignedMembers.erase(MA);
16812     }
16813   }
16814 }
16815 
16816 void Sema::RefersToMemberWithReducedAlignment(
16817     Expr *E,
16818     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16819         Action) {
16820   const auto *ME = dyn_cast<MemberExpr>(E);
16821   if (!ME)
16822     return;
16823 
16824   // No need to check expressions with an __unaligned-qualified type.
16825   if (E->getType().getQualifiers().hasUnaligned())
16826     return;
16827 
16828   // For a chain of MemberExpr like "a.b.c.d" this list
16829   // will keep FieldDecl's like [d, c, b].
16830   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16831   const MemberExpr *TopME = nullptr;
16832   bool AnyIsPacked = false;
16833   do {
16834     QualType BaseType = ME->getBase()->getType();
16835     if (BaseType->isDependentType())
16836       return;
16837     if (ME->isArrow())
16838       BaseType = BaseType->getPointeeType();
16839     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16840     if (RD->isInvalidDecl())
16841       return;
16842 
16843     ValueDecl *MD = ME->getMemberDecl();
16844     auto *FD = dyn_cast<FieldDecl>(MD);
16845     // We do not care about non-data members.
16846     if (!FD || FD->isInvalidDecl())
16847       return;
16848 
16849     AnyIsPacked =
16850         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16851     ReverseMemberChain.push_back(FD);
16852 
16853     TopME = ME;
16854     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16855   } while (ME);
16856   assert(TopME && "We did not compute a topmost MemberExpr!");
16857 
16858   // Not the scope of this diagnostic.
16859   if (!AnyIsPacked)
16860     return;
16861 
16862   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16863   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16864   // TODO: The innermost base of the member expression may be too complicated.
16865   // For now, just disregard these cases. This is left for future
16866   // improvement.
16867   if (!DRE && !isa<CXXThisExpr>(TopBase))
16868       return;
16869 
16870   // Alignment expected by the whole expression.
16871   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16872 
16873   // No need to do anything else with this case.
16874   if (ExpectedAlignment.isOne())
16875     return;
16876 
16877   // Synthesize offset of the whole access.
16878   CharUnits Offset;
16879   for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16880     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16881 
16882   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16883   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16884       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16885 
16886   // The base expression of the innermost MemberExpr may give
16887   // stronger guarantees than the class containing the member.
16888   if (DRE && !TopME->isArrow()) {
16889     const ValueDecl *VD = DRE->getDecl();
16890     if (!VD->getType()->isReferenceType())
16891       CompleteObjectAlignment =
16892           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16893   }
16894 
16895   // Check if the synthesized offset fulfills the alignment.
16896   if (Offset % ExpectedAlignment != 0 ||
16897       // It may fulfill the offset it but the effective alignment may still be
16898       // lower than the expected expression alignment.
16899       CompleteObjectAlignment < ExpectedAlignment) {
16900     // If this happens, we want to determine a sensible culprit of this.
16901     // Intuitively, watching the chain of member expressions from right to
16902     // left, we start with the required alignment (as required by the field
16903     // type) but some packed attribute in that chain has reduced the alignment.
16904     // It may happen that another packed structure increases it again. But if
16905     // we are here such increase has not been enough. So pointing the first
16906     // FieldDecl that either is packed or else its RecordDecl is,
16907     // seems reasonable.
16908     FieldDecl *FD = nullptr;
16909     CharUnits Alignment;
16910     for (FieldDecl *FDI : ReverseMemberChain) {
16911       if (FDI->hasAttr<PackedAttr>() ||
16912           FDI->getParent()->hasAttr<PackedAttr>()) {
16913         FD = FDI;
16914         Alignment = std::min(
16915             Context.getTypeAlignInChars(FD->getType()),
16916             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16917         break;
16918       }
16919     }
16920     assert(FD && "We did not find a packed FieldDecl!");
16921     Action(E, FD->getParent(), FD, Alignment);
16922   }
16923 }
16924 
16925 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16926   using namespace std::placeholders;
16927 
16928   RefersToMemberWithReducedAlignment(
16929       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16930                      _2, _3, _4));
16931 }
16932 
16933 // Check if \p Ty is a valid type for the elementwise math builtins. If it is
16934 // not a valid type, emit an error message and return true. Otherwise return
16935 // false.
16936 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc,
16937                                         QualType Ty) {
16938   if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) {
16939     S.Diag(Loc, diag::err_builtin_invalid_arg_type)
16940         << 1 << /* vector, integer or float ty*/ 0 << Ty;
16941     return true;
16942   }
16943   return false;
16944 }
16945 
16946 bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) {
16947   if (checkArgCount(*this, TheCall, 1))
16948     return true;
16949 
16950   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16951   if (A.isInvalid())
16952     return true;
16953 
16954   TheCall->setArg(0, A.get());
16955   QualType TyA = A.get()->getType();
16956 
16957   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
16958     return true;
16959 
16960   TheCall->setType(TyA);
16961   return false;
16962 }
16963 
16964 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) {
16965   if (checkArgCount(*this, TheCall, 2))
16966     return true;
16967 
16968   ExprResult A = TheCall->getArg(0);
16969   ExprResult B = TheCall->getArg(1);
16970   // Do standard promotions between the two arguments, returning their common
16971   // type.
16972   QualType Res =
16973       UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
16974   if (A.isInvalid() || B.isInvalid())
16975     return true;
16976 
16977   QualType TyA = A.get()->getType();
16978   QualType TyB = B.get()->getType();
16979 
16980   if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
16981     return Diag(A.get()->getBeginLoc(),
16982                 diag::err_typecheck_call_different_arg_types)
16983            << TyA << TyB;
16984 
16985   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
16986     return true;
16987 
16988   TheCall->setArg(0, A.get());
16989   TheCall->setArg(1, B.get());
16990   TheCall->setType(Res);
16991   return false;
16992 }
16993 
16994 bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
16995   if (checkArgCount(*this, TheCall, 1))
16996     return true;
16997 
16998   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16999   if (A.isInvalid())
17000     return true;
17001 
17002   TheCall->setArg(0, A.get());
17003   return false;
17004 }
17005 
17006 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
17007                                             ExprResult CallResult) {
17008   if (checkArgCount(*this, TheCall, 1))
17009     return ExprError();
17010 
17011   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
17012   if (MatrixArg.isInvalid())
17013     return MatrixArg;
17014   Expr *Matrix = MatrixArg.get();
17015 
17016   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17017   if (!MType) {
17018     Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17019         << 1 << /* matrix ty*/ 1 << Matrix->getType();
17020     return ExprError();
17021   }
17022 
17023   // Create returned matrix type by swapping rows and columns of the argument
17024   // matrix type.
17025   QualType ResultType = Context.getConstantMatrixType(
17026       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
17027 
17028   // Change the return type to the type of the returned matrix.
17029   TheCall->setType(ResultType);
17030 
17031   // Update call argument to use the possibly converted matrix argument.
17032   TheCall->setArg(0, Matrix);
17033   return CallResult;
17034 }
17035 
17036 // Get and verify the matrix dimensions.
17037 static llvm::Optional<unsigned>
17038 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
17039   SourceLocation ErrorPos;
17040   Optional<llvm::APSInt> Value =
17041       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
17042   if (!Value) {
17043     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
17044         << Name;
17045     return {};
17046   }
17047   uint64_t Dim = Value->getZExtValue();
17048   if (!ConstantMatrixType::isDimensionValid(Dim)) {
17049     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
17050         << Name << ConstantMatrixType::getMaxElementsPerDimension();
17051     return {};
17052   }
17053   return Dim;
17054 }
17055 
17056 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17057                                                   ExprResult CallResult) {
17058   if (!getLangOpts().MatrixTypes) {
17059     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17060     return ExprError();
17061   }
17062 
17063   if (checkArgCount(*this, TheCall, 4))
17064     return ExprError();
17065 
17066   unsigned PtrArgIdx = 0;
17067   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17068   Expr *RowsExpr = TheCall->getArg(1);
17069   Expr *ColumnsExpr = TheCall->getArg(2);
17070   Expr *StrideExpr = TheCall->getArg(3);
17071 
17072   bool ArgError = false;
17073 
17074   // Check pointer argument.
17075   {
17076     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17077     if (PtrConv.isInvalid())
17078       return PtrConv;
17079     PtrExpr = PtrConv.get();
17080     TheCall->setArg(0, PtrExpr);
17081     if (PtrExpr->isTypeDependent()) {
17082       TheCall->setType(Context.DependentTy);
17083       return TheCall;
17084     }
17085   }
17086 
17087   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17088   QualType ElementTy;
17089   if (!PtrTy) {
17090     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17091         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17092     ArgError = true;
17093   } else {
17094     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17095 
17096     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
17097       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17098           << PtrArgIdx + 1 << /* pointer to element ty*/ 2
17099           << PtrExpr->getType();
17100       ArgError = true;
17101     }
17102   }
17103 
17104   // Apply default Lvalue conversions and convert the expression to size_t.
17105   auto ApplyArgumentConversions = [this](Expr *E) {
17106     ExprResult Conv = DefaultLvalueConversion(E);
17107     if (Conv.isInvalid())
17108       return Conv;
17109 
17110     return tryConvertExprToType(Conv.get(), Context.getSizeType());
17111   };
17112 
17113   // Apply conversion to row and column expressions.
17114   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17115   if (!RowsConv.isInvalid()) {
17116     RowsExpr = RowsConv.get();
17117     TheCall->setArg(1, RowsExpr);
17118   } else
17119     RowsExpr = nullptr;
17120 
17121   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17122   if (!ColumnsConv.isInvalid()) {
17123     ColumnsExpr = ColumnsConv.get();
17124     TheCall->setArg(2, ColumnsExpr);
17125   } else
17126     ColumnsExpr = nullptr;
17127 
17128   // If any any part of the result matrix type is still pending, just use
17129   // Context.DependentTy, until all parts are resolved.
17130   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17131       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17132     TheCall->setType(Context.DependentTy);
17133     return CallResult;
17134   }
17135 
17136   // Check row and column dimensions.
17137   llvm::Optional<unsigned> MaybeRows;
17138   if (RowsExpr)
17139     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17140 
17141   llvm::Optional<unsigned> MaybeColumns;
17142   if (ColumnsExpr)
17143     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17144 
17145   // Check stride argument.
17146   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17147   if (StrideConv.isInvalid())
17148     return ExprError();
17149   StrideExpr = StrideConv.get();
17150   TheCall->setArg(3, StrideExpr);
17151 
17152   if (MaybeRows) {
17153     if (Optional<llvm::APSInt> Value =
17154             StrideExpr->getIntegerConstantExpr(Context)) {
17155       uint64_t Stride = Value->getZExtValue();
17156       if (Stride < *MaybeRows) {
17157         Diag(StrideExpr->getBeginLoc(),
17158              diag::err_builtin_matrix_stride_too_small);
17159         ArgError = true;
17160       }
17161     }
17162   }
17163 
17164   if (ArgError || !MaybeRows || !MaybeColumns)
17165     return ExprError();
17166 
17167   TheCall->setType(
17168       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17169   return CallResult;
17170 }
17171 
17172 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17173                                                    ExprResult CallResult) {
17174   if (checkArgCount(*this, TheCall, 3))
17175     return ExprError();
17176 
17177   unsigned PtrArgIdx = 1;
17178   Expr *MatrixExpr = TheCall->getArg(0);
17179   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17180   Expr *StrideExpr = TheCall->getArg(2);
17181 
17182   bool ArgError = false;
17183 
17184   {
17185     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17186     if (MatrixConv.isInvalid())
17187       return MatrixConv;
17188     MatrixExpr = MatrixConv.get();
17189     TheCall->setArg(0, MatrixExpr);
17190   }
17191   if (MatrixExpr->isTypeDependent()) {
17192     TheCall->setType(Context.DependentTy);
17193     return TheCall;
17194   }
17195 
17196   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17197   if (!MatrixTy) {
17198     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17199         << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
17200     ArgError = true;
17201   }
17202 
17203   {
17204     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17205     if (PtrConv.isInvalid())
17206       return PtrConv;
17207     PtrExpr = PtrConv.get();
17208     TheCall->setArg(1, PtrExpr);
17209     if (PtrExpr->isTypeDependent()) {
17210       TheCall->setType(Context.DependentTy);
17211       return TheCall;
17212     }
17213   }
17214 
17215   // Check pointer argument.
17216   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17217   if (!PtrTy) {
17218     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17219         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17220     ArgError = true;
17221   } else {
17222     QualType ElementTy = PtrTy->getPointeeType();
17223     if (ElementTy.isConstQualified()) {
17224       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17225       ArgError = true;
17226     }
17227     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17228     if (MatrixTy &&
17229         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17230       Diag(PtrExpr->getBeginLoc(),
17231            diag::err_builtin_matrix_pointer_arg_mismatch)
17232           << ElementTy << MatrixTy->getElementType();
17233       ArgError = true;
17234     }
17235   }
17236 
17237   // Apply default Lvalue conversions and convert the stride expression to
17238   // size_t.
17239   {
17240     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17241     if (StrideConv.isInvalid())
17242       return StrideConv;
17243 
17244     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17245     if (StrideConv.isInvalid())
17246       return StrideConv;
17247     StrideExpr = StrideConv.get();
17248     TheCall->setArg(2, StrideExpr);
17249   }
17250 
17251   // Check stride argument.
17252   if (MatrixTy) {
17253     if (Optional<llvm::APSInt> Value =
17254             StrideExpr->getIntegerConstantExpr(Context)) {
17255       uint64_t Stride = Value->getZExtValue();
17256       if (Stride < MatrixTy->getNumRows()) {
17257         Diag(StrideExpr->getBeginLoc(),
17258              diag::err_builtin_matrix_stride_too_small);
17259         ArgError = true;
17260       }
17261     }
17262   }
17263 
17264   if (ArgError)
17265     return ExprError();
17266 
17267   return CallResult;
17268 }
17269 
17270 /// \brief Enforce the bounds of a TCB
17271 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
17272 /// directly calls other functions in the same TCB as marked by the enforce_tcb
17273 /// and enforce_tcb_leaf attributes.
17274 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
17275                                const FunctionDecl *Callee) {
17276   const FunctionDecl *Caller = getCurFunctionDecl();
17277 
17278   // Calls to builtins are not enforced.
17279   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
17280       Callee->getBuiltinID() != 0)
17281     return;
17282 
17283   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17284   // all TCBs the callee is a part of.
17285   llvm::StringSet<> CalleeTCBs;
17286   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
17287            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17288   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
17289            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17290 
17291   // Go through the TCBs the caller is a part of and emit warnings if Caller
17292   // is in a TCB that the Callee is not.
17293   for_each(
17294       Caller->specific_attrs<EnforceTCBAttr>(),
17295       [&](const auto *A) {
17296         StringRef CallerTCB = A->getTCBName();
17297         if (CalleeTCBs.count(CallerTCB) == 0) {
17298           this->Diag(TheCall->getExprLoc(),
17299                      diag::warn_tcb_enforcement_violation) << Callee
17300                                                            << CallerTCB;
17301         }
17302       });
17303 }
17304