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 we don't have enough arguments, continue so we can issue better
1683     // diagnostic in checkArgCount(...)
1684     if (ArgNo < TheCall->getNumArgs() &&
1685         SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1686       return true;
1687     ICEArguments &= ~(1 << ArgNo);
1688   }
1689 
1690   switch (BuiltinID) {
1691   case Builtin::BI__builtin___CFStringMakeConstantString:
1692     // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
1693     // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
1694     if (CheckBuiltinTargetNotInUnsupported(
1695             *this, BuiltinID, TheCall,
1696             {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
1697       return ExprError();
1698     assert(TheCall->getNumArgs() == 1 &&
1699            "Wrong # arguments to builtin CFStringMakeConstantString");
1700     if (CheckObjCString(TheCall->getArg(0)))
1701       return ExprError();
1702     break;
1703   case Builtin::BI__builtin_ms_va_start:
1704   case Builtin::BI__builtin_stdarg_start:
1705   case Builtin::BI__builtin_va_start:
1706     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1707       return ExprError();
1708     break;
1709   case Builtin::BI__va_start: {
1710     switch (Context.getTargetInfo().getTriple().getArch()) {
1711     case llvm::Triple::aarch64:
1712     case llvm::Triple::arm:
1713     case llvm::Triple::thumb:
1714       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1715         return ExprError();
1716       break;
1717     default:
1718       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1719         return ExprError();
1720       break;
1721     }
1722     break;
1723   }
1724 
1725   // The acquire, release, and no fence variants are ARM and AArch64 only.
1726   case Builtin::BI_interlockedbittestandset_acq:
1727   case Builtin::BI_interlockedbittestandset_rel:
1728   case Builtin::BI_interlockedbittestandset_nf:
1729   case Builtin::BI_interlockedbittestandreset_acq:
1730   case Builtin::BI_interlockedbittestandreset_rel:
1731   case Builtin::BI_interlockedbittestandreset_nf:
1732     if (CheckBuiltinTargetInSupported(
1733             *this, BuiltinID, TheCall,
1734             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1735       return ExprError();
1736     break;
1737 
1738   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1739   case Builtin::BI_bittest64:
1740   case Builtin::BI_bittestandcomplement64:
1741   case Builtin::BI_bittestandreset64:
1742   case Builtin::BI_bittestandset64:
1743   case Builtin::BI_interlockedbittestandreset64:
1744   case Builtin::BI_interlockedbittestandset64:
1745     if (CheckBuiltinTargetInSupported(*this, BuiltinID, TheCall,
1746                                       {llvm::Triple::x86_64, llvm::Triple::arm,
1747                                        llvm::Triple::thumb,
1748                                        llvm::Triple::aarch64}))
1749       return ExprError();
1750     break;
1751 
1752   case Builtin::BI__builtin_isgreater:
1753   case Builtin::BI__builtin_isgreaterequal:
1754   case Builtin::BI__builtin_isless:
1755   case Builtin::BI__builtin_islessequal:
1756   case Builtin::BI__builtin_islessgreater:
1757   case Builtin::BI__builtin_isunordered:
1758     if (SemaBuiltinUnorderedCompare(TheCall))
1759       return ExprError();
1760     break;
1761   case Builtin::BI__builtin_fpclassify:
1762     if (SemaBuiltinFPClassification(TheCall, 6))
1763       return ExprError();
1764     break;
1765   case Builtin::BI__builtin_isfinite:
1766   case Builtin::BI__builtin_isinf:
1767   case Builtin::BI__builtin_isinf_sign:
1768   case Builtin::BI__builtin_isnan:
1769   case Builtin::BI__builtin_isnormal:
1770   case Builtin::BI__builtin_signbit:
1771   case Builtin::BI__builtin_signbitf:
1772   case Builtin::BI__builtin_signbitl:
1773     if (SemaBuiltinFPClassification(TheCall, 1))
1774       return ExprError();
1775     break;
1776   case Builtin::BI__builtin_shufflevector:
1777     return SemaBuiltinShuffleVector(TheCall);
1778     // TheCall will be freed by the smart pointer here, but that's fine, since
1779     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1780   case Builtin::BI__builtin_prefetch:
1781     if (SemaBuiltinPrefetch(TheCall))
1782       return ExprError();
1783     break;
1784   case Builtin::BI__builtin_alloca_with_align:
1785   case Builtin::BI__builtin_alloca_with_align_uninitialized:
1786     if (SemaBuiltinAllocaWithAlign(TheCall))
1787       return ExprError();
1788     LLVM_FALLTHROUGH;
1789   case Builtin::BI__builtin_alloca:
1790   case Builtin::BI__builtin_alloca_uninitialized:
1791     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1792         << TheCall->getDirectCallee();
1793     break;
1794   case Builtin::BI__arithmetic_fence:
1795     if (SemaBuiltinArithmeticFence(TheCall))
1796       return ExprError();
1797     break;
1798   case Builtin::BI__assume:
1799   case Builtin::BI__builtin_assume:
1800     if (SemaBuiltinAssume(TheCall))
1801       return ExprError();
1802     break;
1803   case Builtin::BI__builtin_assume_aligned:
1804     if (SemaBuiltinAssumeAligned(TheCall))
1805       return ExprError();
1806     break;
1807   case Builtin::BI__builtin_dynamic_object_size:
1808   case Builtin::BI__builtin_object_size:
1809     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1810       return ExprError();
1811     break;
1812   case Builtin::BI__builtin_longjmp:
1813     if (SemaBuiltinLongjmp(TheCall))
1814       return ExprError();
1815     break;
1816   case Builtin::BI__builtin_setjmp:
1817     if (SemaBuiltinSetjmp(TheCall))
1818       return ExprError();
1819     break;
1820   case Builtin::BI__builtin_classify_type:
1821     if (checkArgCount(*this, TheCall, 1)) return true;
1822     TheCall->setType(Context.IntTy);
1823     break;
1824   case Builtin::BI__builtin_complex:
1825     if (SemaBuiltinComplex(TheCall))
1826       return ExprError();
1827     break;
1828   case Builtin::BI__builtin_constant_p: {
1829     if (checkArgCount(*this, TheCall, 1)) return true;
1830     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1831     if (Arg.isInvalid()) return true;
1832     TheCall->setArg(0, Arg.get());
1833     TheCall->setType(Context.IntTy);
1834     break;
1835   }
1836   case Builtin::BI__builtin_launder:
1837     return SemaBuiltinLaunder(*this, TheCall);
1838   case Builtin::BI__sync_fetch_and_add:
1839   case Builtin::BI__sync_fetch_and_add_1:
1840   case Builtin::BI__sync_fetch_and_add_2:
1841   case Builtin::BI__sync_fetch_and_add_4:
1842   case Builtin::BI__sync_fetch_and_add_8:
1843   case Builtin::BI__sync_fetch_and_add_16:
1844   case Builtin::BI__sync_fetch_and_sub:
1845   case Builtin::BI__sync_fetch_and_sub_1:
1846   case Builtin::BI__sync_fetch_and_sub_2:
1847   case Builtin::BI__sync_fetch_and_sub_4:
1848   case Builtin::BI__sync_fetch_and_sub_8:
1849   case Builtin::BI__sync_fetch_and_sub_16:
1850   case Builtin::BI__sync_fetch_and_or:
1851   case Builtin::BI__sync_fetch_and_or_1:
1852   case Builtin::BI__sync_fetch_and_or_2:
1853   case Builtin::BI__sync_fetch_and_or_4:
1854   case Builtin::BI__sync_fetch_and_or_8:
1855   case Builtin::BI__sync_fetch_and_or_16:
1856   case Builtin::BI__sync_fetch_and_and:
1857   case Builtin::BI__sync_fetch_and_and_1:
1858   case Builtin::BI__sync_fetch_and_and_2:
1859   case Builtin::BI__sync_fetch_and_and_4:
1860   case Builtin::BI__sync_fetch_and_and_8:
1861   case Builtin::BI__sync_fetch_and_and_16:
1862   case Builtin::BI__sync_fetch_and_xor:
1863   case Builtin::BI__sync_fetch_and_xor_1:
1864   case Builtin::BI__sync_fetch_and_xor_2:
1865   case Builtin::BI__sync_fetch_and_xor_4:
1866   case Builtin::BI__sync_fetch_and_xor_8:
1867   case Builtin::BI__sync_fetch_and_xor_16:
1868   case Builtin::BI__sync_fetch_and_nand:
1869   case Builtin::BI__sync_fetch_and_nand_1:
1870   case Builtin::BI__sync_fetch_and_nand_2:
1871   case Builtin::BI__sync_fetch_and_nand_4:
1872   case Builtin::BI__sync_fetch_and_nand_8:
1873   case Builtin::BI__sync_fetch_and_nand_16:
1874   case Builtin::BI__sync_add_and_fetch:
1875   case Builtin::BI__sync_add_and_fetch_1:
1876   case Builtin::BI__sync_add_and_fetch_2:
1877   case Builtin::BI__sync_add_and_fetch_4:
1878   case Builtin::BI__sync_add_and_fetch_8:
1879   case Builtin::BI__sync_add_and_fetch_16:
1880   case Builtin::BI__sync_sub_and_fetch:
1881   case Builtin::BI__sync_sub_and_fetch_1:
1882   case Builtin::BI__sync_sub_and_fetch_2:
1883   case Builtin::BI__sync_sub_and_fetch_4:
1884   case Builtin::BI__sync_sub_and_fetch_8:
1885   case Builtin::BI__sync_sub_and_fetch_16:
1886   case Builtin::BI__sync_and_and_fetch:
1887   case Builtin::BI__sync_and_and_fetch_1:
1888   case Builtin::BI__sync_and_and_fetch_2:
1889   case Builtin::BI__sync_and_and_fetch_4:
1890   case Builtin::BI__sync_and_and_fetch_8:
1891   case Builtin::BI__sync_and_and_fetch_16:
1892   case Builtin::BI__sync_or_and_fetch:
1893   case Builtin::BI__sync_or_and_fetch_1:
1894   case Builtin::BI__sync_or_and_fetch_2:
1895   case Builtin::BI__sync_or_and_fetch_4:
1896   case Builtin::BI__sync_or_and_fetch_8:
1897   case Builtin::BI__sync_or_and_fetch_16:
1898   case Builtin::BI__sync_xor_and_fetch:
1899   case Builtin::BI__sync_xor_and_fetch_1:
1900   case Builtin::BI__sync_xor_and_fetch_2:
1901   case Builtin::BI__sync_xor_and_fetch_4:
1902   case Builtin::BI__sync_xor_and_fetch_8:
1903   case Builtin::BI__sync_xor_and_fetch_16:
1904   case Builtin::BI__sync_nand_and_fetch:
1905   case Builtin::BI__sync_nand_and_fetch_1:
1906   case Builtin::BI__sync_nand_and_fetch_2:
1907   case Builtin::BI__sync_nand_and_fetch_4:
1908   case Builtin::BI__sync_nand_and_fetch_8:
1909   case Builtin::BI__sync_nand_and_fetch_16:
1910   case Builtin::BI__sync_val_compare_and_swap:
1911   case Builtin::BI__sync_val_compare_and_swap_1:
1912   case Builtin::BI__sync_val_compare_and_swap_2:
1913   case Builtin::BI__sync_val_compare_and_swap_4:
1914   case Builtin::BI__sync_val_compare_and_swap_8:
1915   case Builtin::BI__sync_val_compare_and_swap_16:
1916   case Builtin::BI__sync_bool_compare_and_swap:
1917   case Builtin::BI__sync_bool_compare_and_swap_1:
1918   case Builtin::BI__sync_bool_compare_and_swap_2:
1919   case Builtin::BI__sync_bool_compare_and_swap_4:
1920   case Builtin::BI__sync_bool_compare_and_swap_8:
1921   case Builtin::BI__sync_bool_compare_and_swap_16:
1922   case Builtin::BI__sync_lock_test_and_set:
1923   case Builtin::BI__sync_lock_test_and_set_1:
1924   case Builtin::BI__sync_lock_test_and_set_2:
1925   case Builtin::BI__sync_lock_test_and_set_4:
1926   case Builtin::BI__sync_lock_test_and_set_8:
1927   case Builtin::BI__sync_lock_test_and_set_16:
1928   case Builtin::BI__sync_lock_release:
1929   case Builtin::BI__sync_lock_release_1:
1930   case Builtin::BI__sync_lock_release_2:
1931   case Builtin::BI__sync_lock_release_4:
1932   case Builtin::BI__sync_lock_release_8:
1933   case Builtin::BI__sync_lock_release_16:
1934   case Builtin::BI__sync_swap:
1935   case Builtin::BI__sync_swap_1:
1936   case Builtin::BI__sync_swap_2:
1937   case Builtin::BI__sync_swap_4:
1938   case Builtin::BI__sync_swap_8:
1939   case Builtin::BI__sync_swap_16:
1940     return SemaBuiltinAtomicOverloaded(TheCallResult);
1941   case Builtin::BI__sync_synchronize:
1942     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1943         << TheCall->getCallee()->getSourceRange();
1944     break;
1945   case Builtin::BI__builtin_nontemporal_load:
1946   case Builtin::BI__builtin_nontemporal_store:
1947     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1948   case Builtin::BI__builtin_memcpy_inline: {
1949     if (checkArgCount(*this, TheCall, 3))
1950       return ExprError();
1951     auto ArgArrayConversionFailed = [&](unsigned Arg) {
1952       ExprResult ArgExpr =
1953           DefaultFunctionArrayLvalueConversion(TheCall->getArg(Arg));
1954       if (ArgExpr.isInvalid())
1955         return true;
1956       TheCall->setArg(Arg, ArgExpr.get());
1957       return false;
1958     };
1959 
1960     if (ArgArrayConversionFailed(0) || ArgArrayConversionFailed(1))
1961       return true;
1962     clang::Expr *SizeOp = TheCall->getArg(2);
1963     // We warn about copying to or from `nullptr` pointers when `size` is
1964     // greater than 0. When `size` is value dependent we cannot evaluate its
1965     // value so we bail out.
1966     if (SizeOp->isValueDependent())
1967       break;
1968     if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
1969       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1970       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1971     }
1972     break;
1973   }
1974 #define BUILTIN(ID, TYPE, ATTRS)
1975 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1976   case Builtin::BI##ID: \
1977     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1978 #include "clang/Basic/Builtins.def"
1979   case Builtin::BI__annotation:
1980     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1981       return ExprError();
1982     break;
1983   case Builtin::BI__builtin_annotation:
1984     if (SemaBuiltinAnnotation(*this, TheCall))
1985       return ExprError();
1986     break;
1987   case Builtin::BI__builtin_addressof:
1988     if (SemaBuiltinAddressof(*this, TheCall))
1989       return ExprError();
1990     break;
1991   case Builtin::BI__builtin_function_start:
1992     if (SemaBuiltinFunctionStart(*this, TheCall))
1993       return ExprError();
1994     break;
1995   case Builtin::BI__builtin_is_aligned:
1996   case Builtin::BI__builtin_align_up:
1997   case Builtin::BI__builtin_align_down:
1998     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1999       return ExprError();
2000     break;
2001   case Builtin::BI__builtin_add_overflow:
2002   case Builtin::BI__builtin_sub_overflow:
2003   case Builtin::BI__builtin_mul_overflow:
2004     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
2005       return ExprError();
2006     break;
2007   case Builtin::BI__builtin_operator_new:
2008   case Builtin::BI__builtin_operator_delete: {
2009     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
2010     ExprResult Res =
2011         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
2012     if (Res.isInvalid())
2013       CorrectDelayedTyposInExpr(TheCallResult.get());
2014     return Res;
2015   }
2016   case Builtin::BI__builtin_dump_struct: {
2017     // We first want to ensure we are called with 2 arguments
2018     if (checkArgCount(*this, TheCall, 2))
2019       return ExprError();
2020     // Ensure that the first argument is of type 'struct XX *'
2021     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
2022     const QualType PtrArgType = PtrArg->getType();
2023     if (!PtrArgType->isPointerType() ||
2024         !PtrArgType->getPointeeType()->isRecordType()) {
2025       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2026           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
2027           << "structure pointer";
2028       return ExprError();
2029     }
2030 
2031     // Ensure that the second argument is of type 'FunctionType'
2032     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
2033     const QualType FnPtrArgType = FnPtrArg->getType();
2034     if (!FnPtrArgType->isPointerType()) {
2035       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2036           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
2037           << FnPtrArgType << "'int (*)(const char *, ...)'";
2038       return ExprError();
2039     }
2040 
2041     const auto *FuncType =
2042         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
2043 
2044     if (!FuncType) {
2045       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2046           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
2047           << FnPtrArgType << "'int (*)(const char *, ...)'";
2048       return ExprError();
2049     }
2050 
2051     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
2052       if (!FT->getNumParams()) {
2053         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2054             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
2055             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
2056         return ExprError();
2057       }
2058       QualType PT = FT->getParamType(0);
2059       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
2060           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
2061           !PT->getPointeeType().isConstQualified()) {
2062         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2063             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
2064             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
2065         return ExprError();
2066       }
2067     }
2068 
2069     TheCall->setType(Context.IntTy);
2070     break;
2071   }
2072   case Builtin::BI__builtin_expect_with_probability: {
2073     // We first want to ensure we are called with 3 arguments
2074     if (checkArgCount(*this, TheCall, 3))
2075       return ExprError();
2076     // then check probability is constant float in range [0.0, 1.0]
2077     const Expr *ProbArg = TheCall->getArg(2);
2078     SmallVector<PartialDiagnosticAt, 8> Notes;
2079     Expr::EvalResult Eval;
2080     Eval.Diag = &Notes;
2081     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
2082         !Eval.Val.isFloat()) {
2083       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
2084           << ProbArg->getSourceRange();
2085       for (const PartialDiagnosticAt &PDiag : Notes)
2086         Diag(PDiag.first, PDiag.second);
2087       return ExprError();
2088     }
2089     llvm::APFloat Probability = Eval.Val.getFloat();
2090     bool LoseInfo = false;
2091     Probability.convert(llvm::APFloat::IEEEdouble(),
2092                         llvm::RoundingMode::Dynamic, &LoseInfo);
2093     if (!(Probability >= llvm::APFloat(0.0) &&
2094           Probability <= llvm::APFloat(1.0))) {
2095       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
2096           << ProbArg->getSourceRange();
2097       return ExprError();
2098     }
2099     break;
2100   }
2101   case Builtin::BI__builtin_preserve_access_index:
2102     if (SemaBuiltinPreserveAI(*this, TheCall))
2103       return ExprError();
2104     break;
2105   case Builtin::BI__builtin_call_with_static_chain:
2106     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
2107       return ExprError();
2108     break;
2109   case Builtin::BI__exception_code:
2110   case Builtin::BI_exception_code:
2111     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
2112                                  diag::err_seh___except_block))
2113       return ExprError();
2114     break;
2115   case Builtin::BI__exception_info:
2116   case Builtin::BI_exception_info:
2117     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
2118                                  diag::err_seh___except_filter))
2119       return ExprError();
2120     break;
2121   case Builtin::BI__GetExceptionInfo:
2122     if (checkArgCount(*this, TheCall, 1))
2123       return ExprError();
2124 
2125     if (CheckCXXThrowOperand(
2126             TheCall->getBeginLoc(),
2127             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
2128             TheCall))
2129       return ExprError();
2130 
2131     TheCall->setType(Context.VoidPtrTy);
2132     break;
2133   // OpenCL v2.0, s6.13.16 - Pipe functions
2134   case Builtin::BIread_pipe:
2135   case Builtin::BIwrite_pipe:
2136     // Since those two functions are declared with var args, we need a semantic
2137     // check for the argument.
2138     if (SemaBuiltinRWPipe(*this, TheCall))
2139       return ExprError();
2140     break;
2141   case Builtin::BIreserve_read_pipe:
2142   case Builtin::BIreserve_write_pipe:
2143   case Builtin::BIwork_group_reserve_read_pipe:
2144   case Builtin::BIwork_group_reserve_write_pipe:
2145     if (SemaBuiltinReserveRWPipe(*this, TheCall))
2146       return ExprError();
2147     break;
2148   case Builtin::BIsub_group_reserve_read_pipe:
2149   case Builtin::BIsub_group_reserve_write_pipe:
2150     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2151         SemaBuiltinReserveRWPipe(*this, TheCall))
2152       return ExprError();
2153     break;
2154   case Builtin::BIcommit_read_pipe:
2155   case Builtin::BIcommit_write_pipe:
2156   case Builtin::BIwork_group_commit_read_pipe:
2157   case Builtin::BIwork_group_commit_write_pipe:
2158     if (SemaBuiltinCommitRWPipe(*this, TheCall))
2159       return ExprError();
2160     break;
2161   case Builtin::BIsub_group_commit_read_pipe:
2162   case Builtin::BIsub_group_commit_write_pipe:
2163     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2164         SemaBuiltinCommitRWPipe(*this, TheCall))
2165       return ExprError();
2166     break;
2167   case Builtin::BIget_pipe_num_packets:
2168   case Builtin::BIget_pipe_max_packets:
2169     if (SemaBuiltinPipePackets(*this, TheCall))
2170       return ExprError();
2171     break;
2172   case Builtin::BIto_global:
2173   case Builtin::BIto_local:
2174   case Builtin::BIto_private:
2175     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
2176       return ExprError();
2177     break;
2178   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
2179   case Builtin::BIenqueue_kernel:
2180     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
2181       return ExprError();
2182     break;
2183   case Builtin::BIget_kernel_work_group_size:
2184   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
2185     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
2186       return ExprError();
2187     break;
2188   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
2189   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
2190     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
2191       return ExprError();
2192     break;
2193   case Builtin::BI__builtin_os_log_format:
2194     Cleanup.setExprNeedsCleanups(true);
2195     LLVM_FALLTHROUGH;
2196   case Builtin::BI__builtin_os_log_format_buffer_size:
2197     if (SemaBuiltinOSLogFormat(TheCall))
2198       return ExprError();
2199     break;
2200   case Builtin::BI__builtin_frame_address:
2201   case Builtin::BI__builtin_return_address: {
2202     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
2203       return ExprError();
2204 
2205     // -Wframe-address warning if non-zero passed to builtin
2206     // return/frame address.
2207     Expr::EvalResult Result;
2208     if (!TheCall->getArg(0)->isValueDependent() &&
2209         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
2210         Result.Val.getInt() != 0)
2211       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
2212           << ((BuiltinID == Builtin::BI__builtin_return_address)
2213                   ? "__builtin_return_address"
2214                   : "__builtin_frame_address")
2215           << TheCall->getSourceRange();
2216     break;
2217   }
2218 
2219   // __builtin_elementwise_abs restricts the element type to signed integers or
2220   // floating point types only.
2221   case Builtin::BI__builtin_elementwise_abs: {
2222     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2223       return ExprError();
2224 
2225     QualType ArgTy = TheCall->getArg(0)->getType();
2226     QualType EltTy = ArgTy;
2227 
2228     if (auto *VecTy = EltTy->getAs<VectorType>())
2229       EltTy = VecTy->getElementType();
2230     if (EltTy->isUnsignedIntegerType()) {
2231       Diag(TheCall->getArg(0)->getBeginLoc(),
2232            diag::err_builtin_invalid_arg_type)
2233           << 1 << /* signed integer or float ty*/ 3 << ArgTy;
2234       return ExprError();
2235     }
2236     break;
2237   }
2238 
2239   // These builtins restrict the element type to floating point
2240   // types only.
2241   case Builtin::BI__builtin_elementwise_ceil:
2242   case Builtin::BI__builtin_elementwise_floor:
2243   case Builtin::BI__builtin_elementwise_roundeven:
2244   case Builtin::BI__builtin_elementwise_trunc: {
2245     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2246       return ExprError();
2247 
2248     QualType ArgTy = TheCall->getArg(0)->getType();
2249     QualType EltTy = ArgTy;
2250 
2251     if (auto *VecTy = EltTy->getAs<VectorType>())
2252       EltTy = VecTy->getElementType();
2253     if (!EltTy->isFloatingType()) {
2254       Diag(TheCall->getArg(0)->getBeginLoc(),
2255            diag::err_builtin_invalid_arg_type)
2256           << 1 << /* float ty*/ 5 << ArgTy;
2257 
2258       return ExprError();
2259     }
2260     break;
2261   }
2262 
2263   // These builtins restrict the element type to integer
2264   // types only.
2265   case Builtin::BI__builtin_elementwise_add_sat:
2266   case Builtin::BI__builtin_elementwise_sub_sat: {
2267     if (SemaBuiltinElementwiseMath(TheCall))
2268       return ExprError();
2269 
2270     const Expr *Arg = TheCall->getArg(0);
2271     QualType ArgTy = Arg->getType();
2272     QualType EltTy = ArgTy;
2273 
2274     if (auto *VecTy = EltTy->getAs<VectorType>())
2275       EltTy = VecTy->getElementType();
2276 
2277     if (!EltTy->isIntegerType()) {
2278       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2279           << 1 << /* integer ty */ 6 << ArgTy;
2280       return ExprError();
2281     }
2282     break;
2283   }
2284 
2285   case Builtin::BI__builtin_elementwise_min:
2286   case Builtin::BI__builtin_elementwise_max:
2287     if (SemaBuiltinElementwiseMath(TheCall))
2288       return ExprError();
2289     break;
2290   case Builtin::BI__builtin_reduce_max:
2291   case Builtin::BI__builtin_reduce_min: {
2292     if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2293       return ExprError();
2294 
2295     const Expr *Arg = TheCall->getArg(0);
2296     const auto *TyA = Arg->getType()->getAs<VectorType>();
2297     if (!TyA) {
2298       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2299           << 1 << /* vector ty*/ 4 << Arg->getType();
2300       return ExprError();
2301     }
2302 
2303     TheCall->setType(TyA->getElementType());
2304     break;
2305   }
2306 
2307   // These builtins support vectors of integers only.
2308   case Builtin::BI__builtin_reduce_xor:
2309   case Builtin::BI__builtin_reduce_or:
2310   case Builtin::BI__builtin_reduce_and: {
2311     if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2312       return ExprError();
2313 
2314     const Expr *Arg = TheCall->getArg(0);
2315     const auto *TyA = Arg->getType()->getAs<VectorType>();
2316     if (!TyA || !TyA->getElementType()->isIntegerType()) {
2317       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2318           << 1  << /* vector of integers */ 6 << Arg->getType();
2319       return ExprError();
2320     }
2321     TheCall->setType(TyA->getElementType());
2322     break;
2323   }
2324 
2325   case Builtin::BI__builtin_matrix_transpose:
2326     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
2327 
2328   case Builtin::BI__builtin_matrix_column_major_load:
2329     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
2330 
2331   case Builtin::BI__builtin_matrix_column_major_store:
2332     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
2333 
2334   case Builtin::BI__builtin_get_device_side_mangled_name: {
2335     auto Check = [](CallExpr *TheCall) {
2336       if (TheCall->getNumArgs() != 1)
2337         return false;
2338       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
2339       if (!DRE)
2340         return false;
2341       auto *D = DRE->getDecl();
2342       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
2343         return false;
2344       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
2345              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2346     };
2347     if (!Check(TheCall)) {
2348       Diag(TheCall->getBeginLoc(),
2349            diag::err_hip_invalid_args_builtin_mangled_name);
2350       return ExprError();
2351     }
2352   }
2353   }
2354 
2355   // Since the target specific builtins for each arch overlap, only check those
2356   // of the arch we are compiling for.
2357   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2358     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2359       assert(Context.getAuxTargetInfo() &&
2360              "Aux Target Builtin, but not an aux target?");
2361 
2362       if (CheckTSBuiltinFunctionCall(
2363               *Context.getAuxTargetInfo(),
2364               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2365         return ExprError();
2366     } else {
2367       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2368                                      TheCall))
2369         return ExprError();
2370     }
2371   }
2372 
2373   return TheCallResult;
2374 }
2375 
2376 // Get the valid immediate range for the specified NEON type code.
2377 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2378   NeonTypeFlags Type(t);
2379   int IsQuad = ForceQuad ? true : Type.isQuad();
2380   switch (Type.getEltType()) {
2381   case NeonTypeFlags::Int8:
2382   case NeonTypeFlags::Poly8:
2383     return shift ? 7 : (8 << IsQuad) - 1;
2384   case NeonTypeFlags::Int16:
2385   case NeonTypeFlags::Poly16:
2386     return shift ? 15 : (4 << IsQuad) - 1;
2387   case NeonTypeFlags::Int32:
2388     return shift ? 31 : (2 << IsQuad) - 1;
2389   case NeonTypeFlags::Int64:
2390   case NeonTypeFlags::Poly64:
2391     return shift ? 63 : (1 << IsQuad) - 1;
2392   case NeonTypeFlags::Poly128:
2393     return shift ? 127 : (1 << IsQuad) - 1;
2394   case NeonTypeFlags::Float16:
2395     assert(!shift && "cannot shift float types!");
2396     return (4 << IsQuad) - 1;
2397   case NeonTypeFlags::Float32:
2398     assert(!shift && "cannot shift float types!");
2399     return (2 << IsQuad) - 1;
2400   case NeonTypeFlags::Float64:
2401     assert(!shift && "cannot shift float types!");
2402     return (1 << IsQuad) - 1;
2403   case NeonTypeFlags::BFloat16:
2404     assert(!shift && "cannot shift float types!");
2405     return (4 << IsQuad) - 1;
2406   }
2407   llvm_unreachable("Invalid NeonTypeFlag!");
2408 }
2409 
2410 /// getNeonEltType - Return the QualType corresponding to the elements of
2411 /// the vector type specified by the NeonTypeFlags.  This is used to check
2412 /// the pointer arguments for Neon load/store intrinsics.
2413 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2414                                bool IsPolyUnsigned, bool IsInt64Long) {
2415   switch (Flags.getEltType()) {
2416   case NeonTypeFlags::Int8:
2417     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2418   case NeonTypeFlags::Int16:
2419     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2420   case NeonTypeFlags::Int32:
2421     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2422   case NeonTypeFlags::Int64:
2423     if (IsInt64Long)
2424       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2425     else
2426       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2427                                 : Context.LongLongTy;
2428   case NeonTypeFlags::Poly8:
2429     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2430   case NeonTypeFlags::Poly16:
2431     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2432   case NeonTypeFlags::Poly64:
2433     if (IsInt64Long)
2434       return Context.UnsignedLongTy;
2435     else
2436       return Context.UnsignedLongLongTy;
2437   case NeonTypeFlags::Poly128:
2438     break;
2439   case NeonTypeFlags::Float16:
2440     return Context.HalfTy;
2441   case NeonTypeFlags::Float32:
2442     return Context.FloatTy;
2443   case NeonTypeFlags::Float64:
2444     return Context.DoubleTy;
2445   case NeonTypeFlags::BFloat16:
2446     return Context.BFloat16Ty;
2447   }
2448   llvm_unreachable("Invalid NeonTypeFlag!");
2449 }
2450 
2451 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2452   // Range check SVE intrinsics that take immediate values.
2453   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2454 
2455   switch (BuiltinID) {
2456   default:
2457     return false;
2458 #define GET_SVE_IMMEDIATE_CHECK
2459 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2460 #undef GET_SVE_IMMEDIATE_CHECK
2461   }
2462 
2463   // Perform all the immediate checks for this builtin call.
2464   bool HasError = false;
2465   for (auto &I : ImmChecks) {
2466     int ArgNum, CheckTy, ElementSizeInBits;
2467     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2468 
2469     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2470 
2471     // Function that checks whether the operand (ArgNum) is an immediate
2472     // that is one of the predefined values.
2473     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2474                                    int ErrDiag) -> bool {
2475       // We can't check the value of a dependent argument.
2476       Expr *Arg = TheCall->getArg(ArgNum);
2477       if (Arg->isTypeDependent() || Arg->isValueDependent())
2478         return false;
2479 
2480       // Check constant-ness first.
2481       llvm::APSInt Imm;
2482       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2483         return true;
2484 
2485       if (!CheckImm(Imm.getSExtValue()))
2486         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2487       return false;
2488     };
2489 
2490     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2491     case SVETypeFlags::ImmCheck0_31:
2492       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2493         HasError = true;
2494       break;
2495     case SVETypeFlags::ImmCheck0_13:
2496       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2497         HasError = true;
2498       break;
2499     case SVETypeFlags::ImmCheck1_16:
2500       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2501         HasError = true;
2502       break;
2503     case SVETypeFlags::ImmCheck0_7:
2504       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2505         HasError = true;
2506       break;
2507     case SVETypeFlags::ImmCheckExtract:
2508       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2509                                       (2048 / ElementSizeInBits) - 1))
2510         HasError = true;
2511       break;
2512     case SVETypeFlags::ImmCheckShiftRight:
2513       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2514         HasError = true;
2515       break;
2516     case SVETypeFlags::ImmCheckShiftRightNarrow:
2517       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2518                                       ElementSizeInBits / 2))
2519         HasError = true;
2520       break;
2521     case SVETypeFlags::ImmCheckShiftLeft:
2522       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2523                                       ElementSizeInBits - 1))
2524         HasError = true;
2525       break;
2526     case SVETypeFlags::ImmCheckLaneIndex:
2527       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2528                                       (128 / (1 * ElementSizeInBits)) - 1))
2529         HasError = true;
2530       break;
2531     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2532       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2533                                       (128 / (2 * ElementSizeInBits)) - 1))
2534         HasError = true;
2535       break;
2536     case SVETypeFlags::ImmCheckLaneIndexDot:
2537       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2538                                       (128 / (4 * ElementSizeInBits)) - 1))
2539         HasError = true;
2540       break;
2541     case SVETypeFlags::ImmCheckComplexRot90_270:
2542       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2543                               diag::err_rotation_argument_to_cadd))
2544         HasError = true;
2545       break;
2546     case SVETypeFlags::ImmCheckComplexRotAll90:
2547       if (CheckImmediateInSet(
2548               [](int64_t V) {
2549                 return V == 0 || V == 90 || V == 180 || V == 270;
2550               },
2551               diag::err_rotation_argument_to_cmla))
2552         HasError = true;
2553       break;
2554     case SVETypeFlags::ImmCheck0_1:
2555       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2556         HasError = true;
2557       break;
2558     case SVETypeFlags::ImmCheck0_2:
2559       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2560         HasError = true;
2561       break;
2562     case SVETypeFlags::ImmCheck0_3:
2563       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2564         HasError = true;
2565       break;
2566     }
2567   }
2568 
2569   return HasError;
2570 }
2571 
2572 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2573                                         unsigned BuiltinID, CallExpr *TheCall) {
2574   llvm::APSInt Result;
2575   uint64_t mask = 0;
2576   unsigned TV = 0;
2577   int PtrArgNum = -1;
2578   bool HasConstPtr = false;
2579   switch (BuiltinID) {
2580 #define GET_NEON_OVERLOAD_CHECK
2581 #include "clang/Basic/arm_neon.inc"
2582 #include "clang/Basic/arm_fp16.inc"
2583 #undef GET_NEON_OVERLOAD_CHECK
2584   }
2585 
2586   // For NEON intrinsics which are overloaded on vector element type, validate
2587   // the immediate which specifies which variant to emit.
2588   unsigned ImmArg = TheCall->getNumArgs()-1;
2589   if (mask) {
2590     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2591       return true;
2592 
2593     TV = Result.getLimitedValue(64);
2594     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2595       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2596              << TheCall->getArg(ImmArg)->getSourceRange();
2597   }
2598 
2599   if (PtrArgNum >= 0) {
2600     // Check that pointer arguments have the specified type.
2601     Expr *Arg = TheCall->getArg(PtrArgNum);
2602     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2603       Arg = ICE->getSubExpr();
2604     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2605     QualType RHSTy = RHS.get()->getType();
2606 
2607     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2608     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2609                           Arch == llvm::Triple::aarch64_32 ||
2610                           Arch == llvm::Triple::aarch64_be;
2611     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2612     QualType EltTy =
2613         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2614     if (HasConstPtr)
2615       EltTy = EltTy.withConst();
2616     QualType LHSTy = Context.getPointerType(EltTy);
2617     AssignConvertType ConvTy;
2618     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2619     if (RHS.isInvalid())
2620       return true;
2621     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2622                                  RHS.get(), AA_Assigning))
2623       return true;
2624   }
2625 
2626   // For NEON intrinsics which take an immediate value as part of the
2627   // instruction, range check them here.
2628   unsigned i = 0, l = 0, u = 0;
2629   switch (BuiltinID) {
2630   default:
2631     return false;
2632   #define GET_NEON_IMMEDIATE_CHECK
2633   #include "clang/Basic/arm_neon.inc"
2634   #include "clang/Basic/arm_fp16.inc"
2635   #undef GET_NEON_IMMEDIATE_CHECK
2636   }
2637 
2638   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2639 }
2640 
2641 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2642   switch (BuiltinID) {
2643   default:
2644     return false;
2645   #include "clang/Basic/arm_mve_builtin_sema.inc"
2646   }
2647 }
2648 
2649 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2650                                        CallExpr *TheCall) {
2651   bool Err = false;
2652   switch (BuiltinID) {
2653   default:
2654     return false;
2655 #include "clang/Basic/arm_cde_builtin_sema.inc"
2656   }
2657 
2658   if (Err)
2659     return true;
2660 
2661   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2662 }
2663 
2664 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2665                                         const Expr *CoprocArg, bool WantCDE) {
2666   if (isConstantEvaluated())
2667     return false;
2668 
2669   // We can't check the value of a dependent argument.
2670   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2671     return false;
2672 
2673   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2674   int64_t CoprocNo = CoprocNoAP.getExtValue();
2675   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2676 
2677   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2678   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2679 
2680   if (IsCDECoproc != WantCDE)
2681     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2682            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2683 
2684   return false;
2685 }
2686 
2687 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2688                                         unsigned MaxWidth) {
2689   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2690           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2691           BuiltinID == ARM::BI__builtin_arm_strex ||
2692           BuiltinID == ARM::BI__builtin_arm_stlex ||
2693           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2694           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2695           BuiltinID == AArch64::BI__builtin_arm_strex ||
2696           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2697          "unexpected ARM builtin");
2698   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2699                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2700                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2701                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2702 
2703   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2704 
2705   // Ensure that we have the proper number of arguments.
2706   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2707     return true;
2708 
2709   // Inspect the pointer argument of the atomic builtin.  This should always be
2710   // a pointer type, whose element is an integral scalar or pointer type.
2711   // Because it is a pointer type, we don't have to worry about any implicit
2712   // casts here.
2713   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2714   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2715   if (PointerArgRes.isInvalid())
2716     return true;
2717   PointerArg = PointerArgRes.get();
2718 
2719   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2720   if (!pointerType) {
2721     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2722         << PointerArg->getType() << PointerArg->getSourceRange();
2723     return true;
2724   }
2725 
2726   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2727   // task is to insert the appropriate casts into the AST. First work out just
2728   // what the appropriate type is.
2729   QualType ValType = pointerType->getPointeeType();
2730   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2731   if (IsLdrex)
2732     AddrType.addConst();
2733 
2734   // Issue a warning if the cast is dodgy.
2735   CastKind CastNeeded = CK_NoOp;
2736   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2737     CastNeeded = CK_BitCast;
2738     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2739         << PointerArg->getType() << Context.getPointerType(AddrType)
2740         << AA_Passing << PointerArg->getSourceRange();
2741   }
2742 
2743   // Finally, do the cast and replace the argument with the corrected version.
2744   AddrType = Context.getPointerType(AddrType);
2745   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2746   if (PointerArgRes.isInvalid())
2747     return true;
2748   PointerArg = PointerArgRes.get();
2749 
2750   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2751 
2752   // In general, we allow ints, floats and pointers to be loaded and stored.
2753   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2754       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2755     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2756         << PointerArg->getType() << PointerArg->getSourceRange();
2757     return true;
2758   }
2759 
2760   // But ARM doesn't have instructions to deal with 128-bit versions.
2761   if (Context.getTypeSize(ValType) > MaxWidth) {
2762     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2763     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2764         << PointerArg->getType() << PointerArg->getSourceRange();
2765     return true;
2766   }
2767 
2768   switch (ValType.getObjCLifetime()) {
2769   case Qualifiers::OCL_None:
2770   case Qualifiers::OCL_ExplicitNone:
2771     // okay
2772     break;
2773 
2774   case Qualifiers::OCL_Weak:
2775   case Qualifiers::OCL_Strong:
2776   case Qualifiers::OCL_Autoreleasing:
2777     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2778         << ValType << PointerArg->getSourceRange();
2779     return true;
2780   }
2781 
2782   if (IsLdrex) {
2783     TheCall->setType(ValType);
2784     return false;
2785   }
2786 
2787   // Initialize the argument to be stored.
2788   ExprResult ValArg = TheCall->getArg(0);
2789   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2790       Context, ValType, /*consume*/ false);
2791   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2792   if (ValArg.isInvalid())
2793     return true;
2794   TheCall->setArg(0, ValArg.get());
2795 
2796   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2797   // but the custom checker bypasses all default analysis.
2798   TheCall->setType(Context.IntTy);
2799   return false;
2800 }
2801 
2802 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2803                                        CallExpr *TheCall) {
2804   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2805       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2806       BuiltinID == ARM::BI__builtin_arm_strex ||
2807       BuiltinID == ARM::BI__builtin_arm_stlex) {
2808     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2809   }
2810 
2811   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2812     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2813       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2814   }
2815 
2816   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2817       BuiltinID == ARM::BI__builtin_arm_wsr64)
2818     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2819 
2820   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2821       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2822       BuiltinID == ARM::BI__builtin_arm_wsr ||
2823       BuiltinID == ARM::BI__builtin_arm_wsrp)
2824     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2825 
2826   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2827     return true;
2828   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2829     return true;
2830   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2831     return true;
2832 
2833   // For intrinsics which take an immediate value as part of the instruction,
2834   // range check them here.
2835   // FIXME: VFP Intrinsics should error if VFP not present.
2836   switch (BuiltinID) {
2837   default: return false;
2838   case ARM::BI__builtin_arm_ssat:
2839     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2840   case ARM::BI__builtin_arm_usat:
2841     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2842   case ARM::BI__builtin_arm_ssat16:
2843     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2844   case ARM::BI__builtin_arm_usat16:
2845     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2846   case ARM::BI__builtin_arm_vcvtr_f:
2847   case ARM::BI__builtin_arm_vcvtr_d:
2848     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2849   case ARM::BI__builtin_arm_dmb:
2850   case ARM::BI__builtin_arm_dsb:
2851   case ARM::BI__builtin_arm_isb:
2852   case ARM::BI__builtin_arm_dbg:
2853     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2854   case ARM::BI__builtin_arm_cdp:
2855   case ARM::BI__builtin_arm_cdp2:
2856   case ARM::BI__builtin_arm_mcr:
2857   case ARM::BI__builtin_arm_mcr2:
2858   case ARM::BI__builtin_arm_mrc:
2859   case ARM::BI__builtin_arm_mrc2:
2860   case ARM::BI__builtin_arm_mcrr:
2861   case ARM::BI__builtin_arm_mcrr2:
2862   case ARM::BI__builtin_arm_mrrc:
2863   case ARM::BI__builtin_arm_mrrc2:
2864   case ARM::BI__builtin_arm_ldc:
2865   case ARM::BI__builtin_arm_ldcl:
2866   case ARM::BI__builtin_arm_ldc2:
2867   case ARM::BI__builtin_arm_ldc2l:
2868   case ARM::BI__builtin_arm_stc:
2869   case ARM::BI__builtin_arm_stcl:
2870   case ARM::BI__builtin_arm_stc2:
2871   case ARM::BI__builtin_arm_stc2l:
2872     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2873            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2874                                         /*WantCDE*/ false);
2875   }
2876 }
2877 
2878 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2879                                            unsigned BuiltinID,
2880                                            CallExpr *TheCall) {
2881   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2882       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2883       BuiltinID == AArch64::BI__builtin_arm_strex ||
2884       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2885     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2886   }
2887 
2888   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2889     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2890       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2891       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2892       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2893   }
2894 
2895   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2896       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2897     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2898 
2899   // Memory Tagging Extensions (MTE) Intrinsics
2900   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2901       BuiltinID == AArch64::BI__builtin_arm_addg ||
2902       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2903       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2904       BuiltinID == AArch64::BI__builtin_arm_stg ||
2905       BuiltinID == AArch64::BI__builtin_arm_subp) {
2906     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2907   }
2908 
2909   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2910       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2911       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2912       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2913     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2914 
2915   // Only check the valid encoding range. Any constant in this range would be
2916   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2917   // an exception for incorrect registers. This matches MSVC behavior.
2918   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2919       BuiltinID == AArch64::BI_WriteStatusReg)
2920     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2921 
2922   if (BuiltinID == AArch64::BI__getReg)
2923     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2924 
2925   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2926     return true;
2927 
2928   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2929     return true;
2930 
2931   // For intrinsics which take an immediate value as part of the instruction,
2932   // range check them here.
2933   unsigned i = 0, l = 0, u = 0;
2934   switch (BuiltinID) {
2935   default: return false;
2936   case AArch64::BI__builtin_arm_dmb:
2937   case AArch64::BI__builtin_arm_dsb:
2938   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2939   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2940   }
2941 
2942   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2943 }
2944 
2945 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2946   if (Arg->getType()->getAsPlaceholderType())
2947     return false;
2948 
2949   // The first argument needs to be a record field access.
2950   // If it is an array element access, we delay decision
2951   // to BPF backend to check whether the access is a
2952   // field access or not.
2953   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2954           isa<MemberExpr>(Arg->IgnoreParens()) ||
2955           isa<ArraySubscriptExpr>(Arg->IgnoreParens()));
2956 }
2957 
2958 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2959                             QualType VectorTy, QualType EltTy) {
2960   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2961   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2962     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2963         << Call->getSourceRange() << VectorEltTy << EltTy;
2964     return false;
2965   }
2966   return true;
2967 }
2968 
2969 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2970   QualType ArgType = Arg->getType();
2971   if (ArgType->getAsPlaceholderType())
2972     return false;
2973 
2974   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2975   // format:
2976   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2977   //   2. <type> var;
2978   //      __builtin_preserve_type_info(var, flag);
2979   if (!isa<DeclRefExpr>(Arg->IgnoreParens()) &&
2980       !isa<UnaryOperator>(Arg->IgnoreParens()))
2981     return false;
2982 
2983   // Typedef type.
2984   if (ArgType->getAs<TypedefType>())
2985     return true;
2986 
2987   // Record type or Enum type.
2988   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2989   if (const auto *RT = Ty->getAs<RecordType>()) {
2990     if (!RT->getDecl()->getDeclName().isEmpty())
2991       return true;
2992   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2993     if (!ET->getDecl()->getDeclName().isEmpty())
2994       return true;
2995   }
2996 
2997   return false;
2998 }
2999 
3000 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
3001   QualType ArgType = Arg->getType();
3002   if (ArgType->getAsPlaceholderType())
3003     return false;
3004 
3005   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
3006   // format:
3007   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
3008   //                                 flag);
3009   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
3010   if (!UO)
3011     return false;
3012 
3013   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
3014   if (!CE)
3015     return false;
3016   if (CE->getCastKind() != CK_IntegralToPointer &&
3017       CE->getCastKind() != CK_NullToPointer)
3018     return false;
3019 
3020   // The integer must be from an EnumConstantDecl.
3021   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
3022   if (!DR)
3023     return false;
3024 
3025   const EnumConstantDecl *Enumerator =
3026       dyn_cast<EnumConstantDecl>(DR->getDecl());
3027   if (!Enumerator)
3028     return false;
3029 
3030   // The type must be EnumType.
3031   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
3032   const auto *ET = Ty->getAs<EnumType>();
3033   if (!ET)
3034     return false;
3035 
3036   // The enum value must be supported.
3037   return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
3038 }
3039 
3040 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
3041                                        CallExpr *TheCall) {
3042   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
3043           BuiltinID == BPF::BI__builtin_btf_type_id ||
3044           BuiltinID == BPF::BI__builtin_preserve_type_info ||
3045           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
3046          "unexpected BPF builtin");
3047 
3048   if (checkArgCount(*this, TheCall, 2))
3049     return true;
3050 
3051   // The second argument needs to be a constant int
3052   Expr *Arg = TheCall->getArg(1);
3053   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
3054   diag::kind kind;
3055   if (!Value) {
3056     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
3057       kind = diag::err_preserve_field_info_not_const;
3058     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
3059       kind = diag::err_btf_type_id_not_const;
3060     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
3061       kind = diag::err_preserve_type_info_not_const;
3062     else
3063       kind = diag::err_preserve_enum_value_not_const;
3064     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
3065     return true;
3066   }
3067 
3068   // The first argument
3069   Arg = TheCall->getArg(0);
3070   bool InvalidArg = false;
3071   bool ReturnUnsignedInt = true;
3072   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
3073     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
3074       InvalidArg = true;
3075       kind = diag::err_preserve_field_info_not_field;
3076     }
3077   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
3078     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
3079       InvalidArg = true;
3080       kind = diag::err_preserve_type_info_invalid;
3081     }
3082   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
3083     if (!isValidBPFPreserveEnumValueArg(Arg)) {
3084       InvalidArg = true;
3085       kind = diag::err_preserve_enum_value_invalid;
3086     }
3087     ReturnUnsignedInt = false;
3088   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
3089     ReturnUnsignedInt = false;
3090   }
3091 
3092   if (InvalidArg) {
3093     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
3094     return true;
3095   }
3096 
3097   if (ReturnUnsignedInt)
3098     TheCall->setType(Context.UnsignedIntTy);
3099   else
3100     TheCall->setType(Context.UnsignedLongTy);
3101   return false;
3102 }
3103 
3104 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3105   struct ArgInfo {
3106     uint8_t OpNum;
3107     bool IsSigned;
3108     uint8_t BitWidth;
3109     uint8_t Align;
3110   };
3111   struct BuiltinInfo {
3112     unsigned BuiltinID;
3113     ArgInfo Infos[2];
3114   };
3115 
3116   static BuiltinInfo Infos[] = {
3117     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
3118     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
3119     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
3120     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
3121     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
3122     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
3123     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
3124     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
3125     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
3126     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
3127     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
3128 
3129     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
3130     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
3131     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
3132     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
3133     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
3134     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
3135     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
3136     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
3137     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
3138     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
3139     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
3140 
3141     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
3142     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
3143     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
3144     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
3145     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
3146     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
3147     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
3148     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
3149     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
3150     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
3151     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
3152     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
3153     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
3154     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
3155     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
3156     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
3157     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
3158     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
3159     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
3160     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
3161     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
3162     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
3163     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
3164     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
3165     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
3166     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
3167     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
3168     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
3169     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
3170     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
3171     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
3172     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
3173     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
3174     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
3175     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
3176     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
3177     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
3178     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
3179     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
3180     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
3181     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
3182     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
3183     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
3184     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
3185     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
3186     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
3187     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
3188     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
3189     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
3190     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
3191     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
3192     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
3193                                                       {{ 1, false, 6,  0 }} },
3194     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
3195     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
3196     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
3197     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
3198     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
3199     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
3200     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
3201                                                       {{ 1, false, 5,  0 }} },
3202     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
3203     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
3204     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
3205     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
3206     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
3207     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
3208                                                        { 2, false, 5,  0 }} },
3209     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
3210                                                        { 2, false, 6,  0 }} },
3211     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
3212                                                        { 3, false, 5,  0 }} },
3213     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
3214                                                        { 3, false, 6,  0 }} },
3215     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
3216     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
3217     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
3218     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
3219     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
3220     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
3221     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
3222     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
3223     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
3224     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
3225     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
3226     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
3227     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
3228     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
3229     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
3230     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
3231                                                       {{ 2, false, 4,  0 },
3232                                                        { 3, false, 5,  0 }} },
3233     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
3234                                                       {{ 2, false, 4,  0 },
3235                                                        { 3, false, 5,  0 }} },
3236     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
3237                                                       {{ 2, false, 4,  0 },
3238                                                        { 3, false, 5,  0 }} },
3239     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
3240                                                       {{ 2, false, 4,  0 },
3241                                                        { 3, false, 5,  0 }} },
3242     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
3243     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
3244     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
3245     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
3246     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
3247     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
3248     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
3249     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
3250     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
3251     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
3252     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
3253                                                        { 2, false, 5,  0 }} },
3254     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
3255                                                        { 2, false, 6,  0 }} },
3256     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
3257     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
3258     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
3259     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
3260     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
3261     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
3262     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
3263     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
3264     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
3265                                                       {{ 1, false, 4,  0 }} },
3266     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
3267     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
3268                                                       {{ 1, false, 4,  0 }} },
3269     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
3270     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
3271     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
3272     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
3273     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
3274     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
3275     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
3276     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
3277     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
3278     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
3279     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
3280     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
3281     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
3282     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
3283     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
3284     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
3285     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
3286     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
3287     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
3288     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
3289                                                       {{ 3, false, 1,  0 }} },
3290     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
3291     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
3292     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
3293     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
3294                                                       {{ 3, false, 1,  0 }} },
3295     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
3296     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
3297     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
3298     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
3299                                                       {{ 3, false, 1,  0 }} },
3300   };
3301 
3302   // Use a dynamically initialized static to sort the table exactly once on
3303   // first run.
3304   static const bool SortOnce =
3305       (llvm::sort(Infos,
3306                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
3307                    return LHS.BuiltinID < RHS.BuiltinID;
3308                  }),
3309        true);
3310   (void)SortOnce;
3311 
3312   const BuiltinInfo *F = llvm::partition_point(
3313       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
3314   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
3315     return false;
3316 
3317   bool Error = false;
3318 
3319   for (const ArgInfo &A : F->Infos) {
3320     // Ignore empty ArgInfo elements.
3321     if (A.BitWidth == 0)
3322       continue;
3323 
3324     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
3325     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
3326     if (!A.Align) {
3327       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3328     } else {
3329       unsigned M = 1 << A.Align;
3330       Min *= M;
3331       Max *= M;
3332       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3333       Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
3334     }
3335   }
3336   return Error;
3337 }
3338 
3339 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
3340                                            CallExpr *TheCall) {
3341   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3342 }
3343 
3344 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
3345                                         unsigned BuiltinID, CallExpr *TheCall) {
3346   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
3347          CheckMipsBuiltinArgument(BuiltinID, TheCall);
3348 }
3349 
3350 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
3351                                CallExpr *TheCall) {
3352 
3353   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3354       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3355     if (!TI.hasFeature("dsp"))
3356       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3357   }
3358 
3359   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3360       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3361     if (!TI.hasFeature("dspr2"))
3362       return Diag(TheCall->getBeginLoc(),
3363                   diag::err_mips_builtin_requires_dspr2);
3364   }
3365 
3366   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3367       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3368     if (!TI.hasFeature("msa"))
3369       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3370   }
3371 
3372   return false;
3373 }
3374 
3375 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3376 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3377 // ordering for DSP is unspecified. MSA is ordered by the data format used
3378 // by the underlying instruction i.e., df/m, df/n and then by size.
3379 //
3380 // FIXME: The size tests here should instead be tablegen'd along with the
3381 //        definitions from include/clang/Basic/BuiltinsMips.def.
3382 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3383 //        be too.
3384 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3385   unsigned i = 0, l = 0, u = 0, m = 0;
3386   switch (BuiltinID) {
3387   default: return false;
3388   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3389   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3390   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3391   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3392   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3393   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3394   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3395   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3396   // df/m field.
3397   // These intrinsics take an unsigned 3 bit immediate.
3398   case Mips::BI__builtin_msa_bclri_b:
3399   case Mips::BI__builtin_msa_bnegi_b:
3400   case Mips::BI__builtin_msa_bseti_b:
3401   case Mips::BI__builtin_msa_sat_s_b:
3402   case Mips::BI__builtin_msa_sat_u_b:
3403   case Mips::BI__builtin_msa_slli_b:
3404   case Mips::BI__builtin_msa_srai_b:
3405   case Mips::BI__builtin_msa_srari_b:
3406   case Mips::BI__builtin_msa_srli_b:
3407   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3408   case Mips::BI__builtin_msa_binsli_b:
3409   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3410   // These intrinsics take an unsigned 4 bit immediate.
3411   case Mips::BI__builtin_msa_bclri_h:
3412   case Mips::BI__builtin_msa_bnegi_h:
3413   case Mips::BI__builtin_msa_bseti_h:
3414   case Mips::BI__builtin_msa_sat_s_h:
3415   case Mips::BI__builtin_msa_sat_u_h:
3416   case Mips::BI__builtin_msa_slli_h:
3417   case Mips::BI__builtin_msa_srai_h:
3418   case Mips::BI__builtin_msa_srari_h:
3419   case Mips::BI__builtin_msa_srli_h:
3420   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3421   case Mips::BI__builtin_msa_binsli_h:
3422   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3423   // These intrinsics take an unsigned 5 bit immediate.
3424   // The first block of intrinsics actually have an unsigned 5 bit field,
3425   // not a df/n field.
3426   case Mips::BI__builtin_msa_cfcmsa:
3427   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3428   case Mips::BI__builtin_msa_clei_u_b:
3429   case Mips::BI__builtin_msa_clei_u_h:
3430   case Mips::BI__builtin_msa_clei_u_w:
3431   case Mips::BI__builtin_msa_clei_u_d:
3432   case Mips::BI__builtin_msa_clti_u_b:
3433   case Mips::BI__builtin_msa_clti_u_h:
3434   case Mips::BI__builtin_msa_clti_u_w:
3435   case Mips::BI__builtin_msa_clti_u_d:
3436   case Mips::BI__builtin_msa_maxi_u_b:
3437   case Mips::BI__builtin_msa_maxi_u_h:
3438   case Mips::BI__builtin_msa_maxi_u_w:
3439   case Mips::BI__builtin_msa_maxi_u_d:
3440   case Mips::BI__builtin_msa_mini_u_b:
3441   case Mips::BI__builtin_msa_mini_u_h:
3442   case Mips::BI__builtin_msa_mini_u_w:
3443   case Mips::BI__builtin_msa_mini_u_d:
3444   case Mips::BI__builtin_msa_addvi_b:
3445   case Mips::BI__builtin_msa_addvi_h:
3446   case Mips::BI__builtin_msa_addvi_w:
3447   case Mips::BI__builtin_msa_addvi_d:
3448   case Mips::BI__builtin_msa_bclri_w:
3449   case Mips::BI__builtin_msa_bnegi_w:
3450   case Mips::BI__builtin_msa_bseti_w:
3451   case Mips::BI__builtin_msa_sat_s_w:
3452   case Mips::BI__builtin_msa_sat_u_w:
3453   case Mips::BI__builtin_msa_slli_w:
3454   case Mips::BI__builtin_msa_srai_w:
3455   case Mips::BI__builtin_msa_srari_w:
3456   case Mips::BI__builtin_msa_srli_w:
3457   case Mips::BI__builtin_msa_srlri_w:
3458   case Mips::BI__builtin_msa_subvi_b:
3459   case Mips::BI__builtin_msa_subvi_h:
3460   case Mips::BI__builtin_msa_subvi_w:
3461   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3462   case Mips::BI__builtin_msa_binsli_w:
3463   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3464   // These intrinsics take an unsigned 6 bit immediate.
3465   case Mips::BI__builtin_msa_bclri_d:
3466   case Mips::BI__builtin_msa_bnegi_d:
3467   case Mips::BI__builtin_msa_bseti_d:
3468   case Mips::BI__builtin_msa_sat_s_d:
3469   case Mips::BI__builtin_msa_sat_u_d:
3470   case Mips::BI__builtin_msa_slli_d:
3471   case Mips::BI__builtin_msa_srai_d:
3472   case Mips::BI__builtin_msa_srari_d:
3473   case Mips::BI__builtin_msa_srli_d:
3474   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3475   case Mips::BI__builtin_msa_binsli_d:
3476   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3477   // These intrinsics take a signed 5 bit immediate.
3478   case Mips::BI__builtin_msa_ceqi_b:
3479   case Mips::BI__builtin_msa_ceqi_h:
3480   case Mips::BI__builtin_msa_ceqi_w:
3481   case Mips::BI__builtin_msa_ceqi_d:
3482   case Mips::BI__builtin_msa_clti_s_b:
3483   case Mips::BI__builtin_msa_clti_s_h:
3484   case Mips::BI__builtin_msa_clti_s_w:
3485   case Mips::BI__builtin_msa_clti_s_d:
3486   case Mips::BI__builtin_msa_clei_s_b:
3487   case Mips::BI__builtin_msa_clei_s_h:
3488   case Mips::BI__builtin_msa_clei_s_w:
3489   case Mips::BI__builtin_msa_clei_s_d:
3490   case Mips::BI__builtin_msa_maxi_s_b:
3491   case Mips::BI__builtin_msa_maxi_s_h:
3492   case Mips::BI__builtin_msa_maxi_s_w:
3493   case Mips::BI__builtin_msa_maxi_s_d:
3494   case Mips::BI__builtin_msa_mini_s_b:
3495   case Mips::BI__builtin_msa_mini_s_h:
3496   case Mips::BI__builtin_msa_mini_s_w:
3497   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3498   // These intrinsics take an unsigned 8 bit immediate.
3499   case Mips::BI__builtin_msa_andi_b:
3500   case Mips::BI__builtin_msa_nori_b:
3501   case Mips::BI__builtin_msa_ori_b:
3502   case Mips::BI__builtin_msa_shf_b:
3503   case Mips::BI__builtin_msa_shf_h:
3504   case Mips::BI__builtin_msa_shf_w:
3505   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3506   case Mips::BI__builtin_msa_bseli_b:
3507   case Mips::BI__builtin_msa_bmnzi_b:
3508   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3509   // df/n format
3510   // These intrinsics take an unsigned 4 bit immediate.
3511   case Mips::BI__builtin_msa_copy_s_b:
3512   case Mips::BI__builtin_msa_copy_u_b:
3513   case Mips::BI__builtin_msa_insve_b:
3514   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3515   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3516   // These intrinsics take an unsigned 3 bit immediate.
3517   case Mips::BI__builtin_msa_copy_s_h:
3518   case Mips::BI__builtin_msa_copy_u_h:
3519   case Mips::BI__builtin_msa_insve_h:
3520   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3521   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3522   // These intrinsics take an unsigned 2 bit immediate.
3523   case Mips::BI__builtin_msa_copy_s_w:
3524   case Mips::BI__builtin_msa_copy_u_w:
3525   case Mips::BI__builtin_msa_insve_w:
3526   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3527   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3528   // These intrinsics take an unsigned 1 bit immediate.
3529   case Mips::BI__builtin_msa_copy_s_d:
3530   case Mips::BI__builtin_msa_copy_u_d:
3531   case Mips::BI__builtin_msa_insve_d:
3532   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3533   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3534   // Memory offsets and immediate loads.
3535   // These intrinsics take a signed 10 bit immediate.
3536   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3537   case Mips::BI__builtin_msa_ldi_h:
3538   case Mips::BI__builtin_msa_ldi_w:
3539   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3540   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3541   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3542   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3543   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3544   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3545   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3546   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3547   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3548   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3549   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3550   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3551   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3552   }
3553 
3554   if (!m)
3555     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3556 
3557   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3558          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3559 }
3560 
3561 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3562 /// advancing the pointer over the consumed characters. The decoded type is
3563 /// returned. If the decoded type represents a constant integer with a
3564 /// constraint on its value then Mask is set to that value. The type descriptors
3565 /// used in Str are specific to PPC MMA builtins and are documented in the file
3566 /// defining the PPC builtins.
3567 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3568                                         unsigned &Mask) {
3569   bool RequireICE = false;
3570   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3571   switch (*Str++) {
3572   case 'V':
3573     return Context.getVectorType(Context.UnsignedCharTy, 16,
3574                                  VectorType::VectorKind::AltiVecVector);
3575   case 'i': {
3576     char *End;
3577     unsigned size = strtoul(Str, &End, 10);
3578     assert(End != Str && "Missing constant parameter constraint");
3579     Str = End;
3580     Mask = size;
3581     return Context.IntTy;
3582   }
3583   case 'W': {
3584     char *End;
3585     unsigned size = strtoul(Str, &End, 10);
3586     assert(End != Str && "Missing PowerPC MMA type size");
3587     Str = End;
3588     QualType Type;
3589     switch (size) {
3590   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3591     case size: Type = Context.Id##Ty; break;
3592   #include "clang/Basic/PPCTypes.def"
3593     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3594     }
3595     bool CheckVectorArgs = false;
3596     while (!CheckVectorArgs) {
3597       switch (*Str++) {
3598       case '*':
3599         Type = Context.getPointerType(Type);
3600         break;
3601       case 'C':
3602         Type = Type.withConst();
3603         break;
3604       default:
3605         CheckVectorArgs = true;
3606         --Str;
3607         break;
3608       }
3609     }
3610     return Type;
3611   }
3612   default:
3613     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3614   }
3615 }
3616 
3617 static bool isPPC_64Builtin(unsigned BuiltinID) {
3618   // These builtins only work on PPC 64bit targets.
3619   switch (BuiltinID) {
3620   case PPC::BI__builtin_divde:
3621   case PPC::BI__builtin_divdeu:
3622   case PPC::BI__builtin_bpermd:
3623   case PPC::BI__builtin_pdepd:
3624   case PPC::BI__builtin_pextd:
3625   case PPC::BI__builtin_ppc_ldarx:
3626   case PPC::BI__builtin_ppc_stdcx:
3627   case PPC::BI__builtin_ppc_tdw:
3628   case PPC::BI__builtin_ppc_trapd:
3629   case PPC::BI__builtin_ppc_cmpeqb:
3630   case PPC::BI__builtin_ppc_setb:
3631   case PPC::BI__builtin_ppc_mulhd:
3632   case PPC::BI__builtin_ppc_mulhdu:
3633   case PPC::BI__builtin_ppc_maddhd:
3634   case PPC::BI__builtin_ppc_maddhdu:
3635   case PPC::BI__builtin_ppc_maddld:
3636   case PPC::BI__builtin_ppc_load8r:
3637   case PPC::BI__builtin_ppc_store8r:
3638   case PPC::BI__builtin_ppc_insert_exp:
3639   case PPC::BI__builtin_ppc_extract_sig:
3640   case PPC::BI__builtin_ppc_addex:
3641   case PPC::BI__builtin_darn:
3642   case PPC::BI__builtin_darn_raw:
3643   case PPC::BI__builtin_ppc_compare_and_swaplp:
3644   case PPC::BI__builtin_ppc_fetch_and_addlp:
3645   case PPC::BI__builtin_ppc_fetch_and_andlp:
3646   case PPC::BI__builtin_ppc_fetch_and_orlp:
3647   case PPC::BI__builtin_ppc_fetch_and_swaplp:
3648     return true;
3649   }
3650   return false;
3651 }
3652 
3653 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3654                              StringRef FeatureToCheck, unsigned DiagID,
3655                              StringRef DiagArg = "") {
3656   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3657     return false;
3658 
3659   if (DiagArg.empty())
3660     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3661   else
3662     S.Diag(TheCall->getBeginLoc(), DiagID)
3663         << DiagArg << TheCall->getSourceRange();
3664 
3665   return true;
3666 }
3667 
3668 /// Returns true if the argument consists of one contiguous run of 1s with any
3669 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3670 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3671 /// since all 1s are not contiguous.
3672 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3673   llvm::APSInt Result;
3674   // We can't check the value of a dependent argument.
3675   Expr *Arg = TheCall->getArg(ArgNum);
3676   if (Arg->isTypeDependent() || Arg->isValueDependent())
3677     return false;
3678 
3679   // Check constant-ness first.
3680   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3681     return true;
3682 
3683   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3684   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3685     return false;
3686 
3687   return Diag(TheCall->getBeginLoc(),
3688               diag::err_argument_not_contiguous_bit_field)
3689          << ArgNum << Arg->getSourceRange();
3690 }
3691 
3692 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3693                                        CallExpr *TheCall) {
3694   unsigned i = 0, l = 0, u = 0;
3695   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3696   llvm::APSInt Result;
3697 
3698   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3699     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3700            << TheCall->getSourceRange();
3701 
3702   switch (BuiltinID) {
3703   default: return false;
3704   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3705   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3706     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3707            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3708   case PPC::BI__builtin_altivec_dss:
3709     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3710   case PPC::BI__builtin_tbegin:
3711   case PPC::BI__builtin_tend:
3712     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 1) ||
3713            SemaFeatureCheck(*this, TheCall, "htm",
3714                             diag::err_ppc_builtin_requires_htm);
3715   case PPC::BI__builtin_tsr:
3716     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3717            SemaFeatureCheck(*this, TheCall, "htm",
3718                             diag::err_ppc_builtin_requires_htm);
3719   case PPC::BI__builtin_tabortwc:
3720   case PPC::BI__builtin_tabortdc:
3721     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3722            SemaFeatureCheck(*this, TheCall, "htm",
3723                             diag::err_ppc_builtin_requires_htm);
3724   case PPC::BI__builtin_tabortwci:
3725   case PPC::BI__builtin_tabortdci:
3726     return SemaFeatureCheck(*this, TheCall, "htm",
3727                             diag::err_ppc_builtin_requires_htm) ||
3728            (SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3729             SemaBuiltinConstantArgRange(TheCall, 2, 0, 31));
3730   case PPC::BI__builtin_tabort:
3731   case PPC::BI__builtin_tcheck:
3732   case PPC::BI__builtin_treclaim:
3733   case PPC::BI__builtin_trechkpt:
3734   case PPC::BI__builtin_tendall:
3735   case PPC::BI__builtin_tresume:
3736   case PPC::BI__builtin_tsuspend:
3737   case PPC::BI__builtin_get_texasr:
3738   case PPC::BI__builtin_get_texasru:
3739   case PPC::BI__builtin_get_tfhar:
3740   case PPC::BI__builtin_get_tfiar:
3741   case PPC::BI__builtin_set_texasr:
3742   case PPC::BI__builtin_set_texasru:
3743   case PPC::BI__builtin_set_tfhar:
3744   case PPC::BI__builtin_set_tfiar:
3745   case PPC::BI__builtin_ttest:
3746     return SemaFeatureCheck(*this, TheCall, "htm",
3747                             diag::err_ppc_builtin_requires_htm);
3748   // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05',
3749   // __builtin_(un)pack_longdouble are available only if long double uses IBM
3750   // extended double representation.
3751   case PPC::BI__builtin_unpack_longdouble:
3752     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1))
3753       return true;
3754     LLVM_FALLTHROUGH;
3755   case PPC::BI__builtin_pack_longdouble:
3756     if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble())
3757       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi)
3758              << "ibmlongdouble";
3759     return false;
3760   case PPC::BI__builtin_altivec_dst:
3761   case PPC::BI__builtin_altivec_dstt:
3762   case PPC::BI__builtin_altivec_dstst:
3763   case PPC::BI__builtin_altivec_dststt:
3764     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3765   case PPC::BI__builtin_vsx_xxpermdi:
3766   case PPC::BI__builtin_vsx_xxsldwi:
3767     return SemaBuiltinVSX(TheCall);
3768   case PPC::BI__builtin_divwe:
3769   case PPC::BI__builtin_divweu:
3770   case PPC::BI__builtin_divde:
3771   case PPC::BI__builtin_divdeu:
3772     return SemaFeatureCheck(*this, TheCall, "extdiv",
3773                             diag::err_ppc_builtin_only_on_arch, "7");
3774   case PPC::BI__builtin_bpermd:
3775     return SemaFeatureCheck(*this, TheCall, "bpermd",
3776                             diag::err_ppc_builtin_only_on_arch, "7");
3777   case PPC::BI__builtin_unpack_vector_int128:
3778     return SemaFeatureCheck(*this, TheCall, "vsx",
3779                             diag::err_ppc_builtin_only_on_arch, "7") ||
3780            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3781   case PPC::BI__builtin_pack_vector_int128:
3782     return SemaFeatureCheck(*this, TheCall, "vsx",
3783                             diag::err_ppc_builtin_only_on_arch, "7");
3784   case PPC::BI__builtin_pdepd:
3785   case PPC::BI__builtin_pextd:
3786     return SemaFeatureCheck(*this, TheCall, "isa-v31-instructions",
3787                             diag::err_ppc_builtin_only_on_arch, "10");
3788   case PPC::BI__builtin_altivec_vgnb:
3789      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3790   case PPC::BI__builtin_altivec_vec_replace_elt:
3791   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3792     QualType VecTy = TheCall->getArg(0)->getType();
3793     QualType EltTy = TheCall->getArg(1)->getType();
3794     unsigned Width = Context.getIntWidth(EltTy);
3795     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3796            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3797   }
3798   case PPC::BI__builtin_vsx_xxeval:
3799      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3800   case PPC::BI__builtin_altivec_vsldbi:
3801      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3802   case PPC::BI__builtin_altivec_vsrdbi:
3803      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3804   case PPC::BI__builtin_vsx_xxpermx:
3805      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3806   case PPC::BI__builtin_ppc_tw:
3807   case PPC::BI__builtin_ppc_tdw:
3808     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3809   case PPC::BI__builtin_ppc_cmpeqb:
3810   case PPC::BI__builtin_ppc_setb:
3811   case PPC::BI__builtin_ppc_maddhd:
3812   case PPC::BI__builtin_ppc_maddhdu:
3813   case PPC::BI__builtin_ppc_maddld:
3814     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3815                             diag::err_ppc_builtin_only_on_arch, "9");
3816   case PPC::BI__builtin_ppc_cmprb:
3817     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3818                             diag::err_ppc_builtin_only_on_arch, "9") ||
3819            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3820   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3821   // be a constant that represents a contiguous bit field.
3822   case PPC::BI__builtin_ppc_rlwnm:
3823     return SemaValueIsRunOfOnes(TheCall, 2);
3824   case PPC::BI__builtin_ppc_rlwimi:
3825   case PPC::BI__builtin_ppc_rldimi:
3826     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3827            SemaValueIsRunOfOnes(TheCall, 3);
3828   case PPC::BI__builtin_ppc_extract_exp:
3829   case PPC::BI__builtin_ppc_extract_sig:
3830   case PPC::BI__builtin_ppc_insert_exp:
3831     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3832                             diag::err_ppc_builtin_only_on_arch, "9");
3833   case PPC::BI__builtin_ppc_addex: {
3834     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3835                          diag::err_ppc_builtin_only_on_arch, "9") ||
3836         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
3837       return true;
3838     // Output warning for reserved values 1 to 3.
3839     int ArgValue =
3840         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
3841     if (ArgValue != 0)
3842       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
3843           << ArgValue;
3844     return false;
3845   }
3846   case PPC::BI__builtin_ppc_mtfsb0:
3847   case PPC::BI__builtin_ppc_mtfsb1:
3848     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3849   case PPC::BI__builtin_ppc_mtfsf:
3850     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3851   case PPC::BI__builtin_ppc_mtfsfi:
3852     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3853            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3854   case PPC::BI__builtin_ppc_alignx:
3855     return SemaBuiltinConstantArgPower2(TheCall, 0);
3856   case PPC::BI__builtin_ppc_rdlam:
3857     return SemaValueIsRunOfOnes(TheCall, 2);
3858   case PPC::BI__builtin_ppc_icbt:
3859   case PPC::BI__builtin_ppc_sthcx:
3860   case PPC::BI__builtin_ppc_stbcx:
3861   case PPC::BI__builtin_ppc_lharx:
3862   case PPC::BI__builtin_ppc_lbarx:
3863     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3864                             diag::err_ppc_builtin_only_on_arch, "8");
3865   case PPC::BI__builtin_vsx_ldrmb:
3866   case PPC::BI__builtin_vsx_strmb:
3867     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3868                             diag::err_ppc_builtin_only_on_arch, "8") ||
3869            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3870   case PPC::BI__builtin_altivec_vcntmbb:
3871   case PPC::BI__builtin_altivec_vcntmbh:
3872   case PPC::BI__builtin_altivec_vcntmbw:
3873   case PPC::BI__builtin_altivec_vcntmbd:
3874     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3875   case PPC::BI__builtin_darn:
3876   case PPC::BI__builtin_darn_raw:
3877   case PPC::BI__builtin_darn_32:
3878     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3879                             diag::err_ppc_builtin_only_on_arch, "9");
3880   case PPC::BI__builtin_vsx_xxgenpcvbm:
3881   case PPC::BI__builtin_vsx_xxgenpcvhm:
3882   case PPC::BI__builtin_vsx_xxgenpcvwm:
3883   case PPC::BI__builtin_vsx_xxgenpcvdm:
3884     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3885   case PPC::BI__builtin_ppc_compare_exp_uo:
3886   case PPC::BI__builtin_ppc_compare_exp_lt:
3887   case PPC::BI__builtin_ppc_compare_exp_gt:
3888   case PPC::BI__builtin_ppc_compare_exp_eq:
3889     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3890                             diag::err_ppc_builtin_only_on_arch, "9") ||
3891            SemaFeatureCheck(*this, TheCall, "vsx",
3892                             diag::err_ppc_builtin_requires_vsx);
3893   case PPC::BI__builtin_ppc_test_data_class: {
3894     // Check if the first argument of the __builtin_ppc_test_data_class call is
3895     // valid. The argument must be either a 'float' or a 'double'.
3896     QualType ArgType = TheCall->getArg(0)->getType();
3897     if (ArgType != QualType(Context.FloatTy) &&
3898         ArgType != QualType(Context.DoubleTy))
3899       return Diag(TheCall->getBeginLoc(),
3900                   diag::err_ppc_invalid_test_data_class_type);
3901     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3902                             diag::err_ppc_builtin_only_on_arch, "9") ||
3903            SemaFeatureCheck(*this, TheCall, "vsx",
3904                             diag::err_ppc_builtin_requires_vsx) ||
3905            SemaBuiltinConstantArgRange(TheCall, 1, 0, 127);
3906   }
3907   case PPC::BI__builtin_ppc_load8r:
3908   case PPC::BI__builtin_ppc_store8r:
3909     return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions",
3910                             diag::err_ppc_builtin_only_on_arch, "7");
3911 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc)                                 \
3912   case PPC::BI__builtin_##Name:                                                \
3913     return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types);
3914 #include "clang/Basic/BuiltinsPPC.def"
3915   }
3916   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3917 }
3918 
3919 // Check if the given type is a non-pointer PPC MMA type. This function is used
3920 // in Sema to prevent invalid uses of restricted PPC MMA types.
3921 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3922   if (Type->isPointerType() || Type->isArrayType())
3923     return false;
3924 
3925   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3926 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3927   if (false
3928 #include "clang/Basic/PPCTypes.def"
3929      ) {
3930     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3931     return true;
3932   }
3933   return false;
3934 }
3935 
3936 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3937                                           CallExpr *TheCall) {
3938   // position of memory order and scope arguments in the builtin
3939   unsigned OrderIndex, ScopeIndex;
3940   switch (BuiltinID) {
3941   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3942   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3943   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3944   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3945     OrderIndex = 2;
3946     ScopeIndex = 3;
3947     break;
3948   case AMDGPU::BI__builtin_amdgcn_fence:
3949     OrderIndex = 0;
3950     ScopeIndex = 1;
3951     break;
3952   default:
3953     return false;
3954   }
3955 
3956   ExprResult Arg = TheCall->getArg(OrderIndex);
3957   auto ArgExpr = Arg.get();
3958   Expr::EvalResult ArgResult;
3959 
3960   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3961     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3962            << ArgExpr->getType();
3963   auto Ord = ArgResult.Val.getInt().getZExtValue();
3964 
3965   // Check validity of memory ordering as per C11 / C++11's memody model.
3966   // Only fence needs check. Atomic dec/inc allow all memory orders.
3967   if (!llvm::isValidAtomicOrderingCABI(Ord))
3968     return Diag(ArgExpr->getBeginLoc(),
3969                 diag::warn_atomic_op_has_invalid_memory_order)
3970            << ArgExpr->getSourceRange();
3971   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3972   case llvm::AtomicOrderingCABI::relaxed:
3973   case llvm::AtomicOrderingCABI::consume:
3974     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3975       return Diag(ArgExpr->getBeginLoc(),
3976                   diag::warn_atomic_op_has_invalid_memory_order)
3977              << ArgExpr->getSourceRange();
3978     break;
3979   case llvm::AtomicOrderingCABI::acquire:
3980   case llvm::AtomicOrderingCABI::release:
3981   case llvm::AtomicOrderingCABI::acq_rel:
3982   case llvm::AtomicOrderingCABI::seq_cst:
3983     break;
3984   }
3985 
3986   Arg = TheCall->getArg(ScopeIndex);
3987   ArgExpr = Arg.get();
3988   Expr::EvalResult ArgResult1;
3989   // Check that sync scope is a constant literal
3990   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3991     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3992            << ArgExpr->getType();
3993 
3994   return false;
3995 }
3996 
3997 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3998   llvm::APSInt Result;
3999 
4000   // We can't check the value of a dependent argument.
4001   Expr *Arg = TheCall->getArg(ArgNum);
4002   if (Arg->isTypeDependent() || Arg->isValueDependent())
4003     return false;
4004 
4005   // Check constant-ness first.
4006   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4007     return true;
4008 
4009   int64_t Val = Result.getSExtValue();
4010   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
4011     return false;
4012 
4013   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
4014          << Arg->getSourceRange();
4015 }
4016 
4017 static bool isRISCV32Builtin(unsigned BuiltinID) {
4018   // These builtins only work on riscv32 targets.
4019   switch (BuiltinID) {
4020   case RISCV::BI__builtin_riscv_zip_32:
4021   case RISCV::BI__builtin_riscv_unzip_32:
4022   case RISCV::BI__builtin_riscv_aes32dsi_32:
4023   case RISCV::BI__builtin_riscv_aes32dsmi_32:
4024   case RISCV::BI__builtin_riscv_aes32esi_32:
4025   case RISCV::BI__builtin_riscv_aes32esmi_32:
4026   case RISCV::BI__builtin_riscv_sha512sig0h_32:
4027   case RISCV::BI__builtin_riscv_sha512sig0l_32:
4028   case RISCV::BI__builtin_riscv_sha512sig1h_32:
4029   case RISCV::BI__builtin_riscv_sha512sig1l_32:
4030   case RISCV::BI__builtin_riscv_sha512sum0r_32:
4031   case RISCV::BI__builtin_riscv_sha512sum1r_32:
4032     return true;
4033   }
4034 
4035   return false;
4036 }
4037 
4038 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
4039                                          unsigned BuiltinID,
4040                                          CallExpr *TheCall) {
4041   // CodeGenFunction can also detect this, but this gives a better error
4042   // message.
4043   bool FeatureMissing = false;
4044   SmallVector<StringRef> ReqFeatures;
4045   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
4046   Features.split(ReqFeatures, ',');
4047 
4048   // Check for 32-bit only builtins on a 64-bit target.
4049   const llvm::Triple &TT = TI.getTriple();
4050   if (TT.getArch() != llvm::Triple::riscv32 && isRISCV32Builtin(BuiltinID))
4051     return Diag(TheCall->getCallee()->getBeginLoc(),
4052                 diag::err_32_bit_builtin_64_bit_tgt);
4053 
4054   // Check if each required feature is included
4055   for (StringRef F : ReqFeatures) {
4056     SmallVector<StringRef> ReqOpFeatures;
4057     F.split(ReqOpFeatures, '|');
4058     bool HasFeature = false;
4059     for (StringRef OF : ReqOpFeatures) {
4060       if (TI.hasFeature(OF)) {
4061         HasFeature = true;
4062         continue;
4063       }
4064     }
4065 
4066     if (!HasFeature) {
4067       std::string FeatureStrs;
4068       for (StringRef OF : ReqOpFeatures) {
4069         // If the feature is 64bit, alter the string so it will print better in
4070         // the diagnostic.
4071         if (OF == "64bit")
4072           OF = "RV64";
4073 
4074         // Convert features like "zbr" and "experimental-zbr" to "Zbr".
4075         OF.consume_front("experimental-");
4076         std::string FeatureStr = OF.str();
4077         FeatureStr[0] = std::toupper(FeatureStr[0]);
4078         // Combine strings.
4079         FeatureStrs += FeatureStrs == "" ? "" : ", ";
4080         FeatureStrs += "'";
4081         FeatureStrs += FeatureStr;
4082         FeatureStrs += "'";
4083       }
4084       // Error message
4085       FeatureMissing = true;
4086       Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
4087           << TheCall->getSourceRange() << StringRef(FeatureStrs);
4088     }
4089   }
4090 
4091   if (FeatureMissing)
4092     return true;
4093 
4094   switch (BuiltinID) {
4095   case RISCVVector::BI__builtin_rvv_vsetvli:
4096     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
4097            CheckRISCVLMUL(TheCall, 2);
4098   case RISCVVector::BI__builtin_rvv_vsetvlimax:
4099     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
4100            CheckRISCVLMUL(TheCall, 1);
4101   // Check if byteselect is in [0, 3]
4102   case RISCV::BI__builtin_riscv_aes32dsi_32:
4103   case RISCV::BI__builtin_riscv_aes32dsmi_32:
4104   case RISCV::BI__builtin_riscv_aes32esi_32:
4105   case RISCV::BI__builtin_riscv_aes32esmi_32:
4106   case RISCV::BI__builtin_riscv_sm4ks:
4107   case RISCV::BI__builtin_riscv_sm4ed:
4108     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
4109   // Check if rnum is in [0, 10]
4110   case RISCV::BI__builtin_riscv_aes64ks1i_64:
4111     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 10);
4112   }
4113 
4114   return false;
4115 }
4116 
4117 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
4118                                            CallExpr *TheCall) {
4119   if (BuiltinID == SystemZ::BI__builtin_tabort) {
4120     Expr *Arg = TheCall->getArg(0);
4121     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
4122       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
4123         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
4124                << Arg->getSourceRange();
4125   }
4126 
4127   // For intrinsics which take an immediate value as part of the instruction,
4128   // range check them here.
4129   unsigned i = 0, l = 0, u = 0;
4130   switch (BuiltinID) {
4131   default: return false;
4132   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
4133   case SystemZ::BI__builtin_s390_verimb:
4134   case SystemZ::BI__builtin_s390_verimh:
4135   case SystemZ::BI__builtin_s390_verimf:
4136   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
4137   case SystemZ::BI__builtin_s390_vfaeb:
4138   case SystemZ::BI__builtin_s390_vfaeh:
4139   case SystemZ::BI__builtin_s390_vfaef:
4140   case SystemZ::BI__builtin_s390_vfaebs:
4141   case SystemZ::BI__builtin_s390_vfaehs:
4142   case SystemZ::BI__builtin_s390_vfaefs:
4143   case SystemZ::BI__builtin_s390_vfaezb:
4144   case SystemZ::BI__builtin_s390_vfaezh:
4145   case SystemZ::BI__builtin_s390_vfaezf:
4146   case SystemZ::BI__builtin_s390_vfaezbs:
4147   case SystemZ::BI__builtin_s390_vfaezhs:
4148   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
4149   case SystemZ::BI__builtin_s390_vfisb:
4150   case SystemZ::BI__builtin_s390_vfidb:
4151     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
4152            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
4153   case SystemZ::BI__builtin_s390_vftcisb:
4154   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
4155   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
4156   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
4157   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
4158   case SystemZ::BI__builtin_s390_vstrcb:
4159   case SystemZ::BI__builtin_s390_vstrch:
4160   case SystemZ::BI__builtin_s390_vstrcf:
4161   case SystemZ::BI__builtin_s390_vstrczb:
4162   case SystemZ::BI__builtin_s390_vstrczh:
4163   case SystemZ::BI__builtin_s390_vstrczf:
4164   case SystemZ::BI__builtin_s390_vstrcbs:
4165   case SystemZ::BI__builtin_s390_vstrchs:
4166   case SystemZ::BI__builtin_s390_vstrcfs:
4167   case SystemZ::BI__builtin_s390_vstrczbs:
4168   case SystemZ::BI__builtin_s390_vstrczhs:
4169   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
4170   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
4171   case SystemZ::BI__builtin_s390_vfminsb:
4172   case SystemZ::BI__builtin_s390_vfmaxsb:
4173   case SystemZ::BI__builtin_s390_vfmindb:
4174   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
4175   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
4176   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
4177   case SystemZ::BI__builtin_s390_vclfnhs:
4178   case SystemZ::BI__builtin_s390_vclfnls:
4179   case SystemZ::BI__builtin_s390_vcfn:
4180   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
4181   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
4182   }
4183   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
4184 }
4185 
4186 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
4187 /// This checks that the target supports __builtin_cpu_supports and
4188 /// that the string argument is constant and valid.
4189 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
4190                                    CallExpr *TheCall) {
4191   Expr *Arg = TheCall->getArg(0);
4192 
4193   // Check if the argument is a string literal.
4194   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4195     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4196            << Arg->getSourceRange();
4197 
4198   // Check the contents of the string.
4199   StringRef Feature =
4200       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4201   if (!TI.validateCpuSupports(Feature))
4202     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
4203            << Arg->getSourceRange();
4204   return false;
4205 }
4206 
4207 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
4208 /// This checks that the target supports __builtin_cpu_is and
4209 /// that the string argument is constant and valid.
4210 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
4211   Expr *Arg = TheCall->getArg(0);
4212 
4213   // Check if the argument is a string literal.
4214   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4215     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4216            << Arg->getSourceRange();
4217 
4218   // Check the contents of the string.
4219   StringRef Feature =
4220       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4221   if (!TI.validateCpuIs(Feature))
4222     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
4223            << Arg->getSourceRange();
4224   return false;
4225 }
4226 
4227 // Check if the rounding mode is legal.
4228 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
4229   // Indicates if this instruction has rounding control or just SAE.
4230   bool HasRC = false;
4231 
4232   unsigned ArgNum = 0;
4233   switch (BuiltinID) {
4234   default:
4235     return false;
4236   case X86::BI__builtin_ia32_vcvttsd2si32:
4237   case X86::BI__builtin_ia32_vcvttsd2si64:
4238   case X86::BI__builtin_ia32_vcvttsd2usi32:
4239   case X86::BI__builtin_ia32_vcvttsd2usi64:
4240   case X86::BI__builtin_ia32_vcvttss2si32:
4241   case X86::BI__builtin_ia32_vcvttss2si64:
4242   case X86::BI__builtin_ia32_vcvttss2usi32:
4243   case X86::BI__builtin_ia32_vcvttss2usi64:
4244   case X86::BI__builtin_ia32_vcvttsh2si32:
4245   case X86::BI__builtin_ia32_vcvttsh2si64:
4246   case X86::BI__builtin_ia32_vcvttsh2usi32:
4247   case X86::BI__builtin_ia32_vcvttsh2usi64:
4248     ArgNum = 1;
4249     break;
4250   case X86::BI__builtin_ia32_maxpd512:
4251   case X86::BI__builtin_ia32_maxps512:
4252   case X86::BI__builtin_ia32_minpd512:
4253   case X86::BI__builtin_ia32_minps512:
4254   case X86::BI__builtin_ia32_maxph512:
4255   case X86::BI__builtin_ia32_minph512:
4256     ArgNum = 2;
4257     break;
4258   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
4259   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
4260   case X86::BI__builtin_ia32_cvtps2pd512_mask:
4261   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
4262   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
4263   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
4264   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
4265   case X86::BI__builtin_ia32_cvttps2dq512_mask:
4266   case X86::BI__builtin_ia32_cvttps2qq512_mask:
4267   case X86::BI__builtin_ia32_cvttps2udq512_mask:
4268   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
4269   case X86::BI__builtin_ia32_vcvttph2w512_mask:
4270   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
4271   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
4272   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
4273   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
4274   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
4275   case X86::BI__builtin_ia32_exp2pd_mask:
4276   case X86::BI__builtin_ia32_exp2ps_mask:
4277   case X86::BI__builtin_ia32_getexppd512_mask:
4278   case X86::BI__builtin_ia32_getexpps512_mask:
4279   case X86::BI__builtin_ia32_getexpph512_mask:
4280   case X86::BI__builtin_ia32_rcp28pd_mask:
4281   case X86::BI__builtin_ia32_rcp28ps_mask:
4282   case X86::BI__builtin_ia32_rsqrt28pd_mask:
4283   case X86::BI__builtin_ia32_rsqrt28ps_mask:
4284   case X86::BI__builtin_ia32_vcomisd:
4285   case X86::BI__builtin_ia32_vcomiss:
4286   case X86::BI__builtin_ia32_vcomish:
4287   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
4288     ArgNum = 3;
4289     break;
4290   case X86::BI__builtin_ia32_cmppd512_mask:
4291   case X86::BI__builtin_ia32_cmpps512_mask:
4292   case X86::BI__builtin_ia32_cmpsd_mask:
4293   case X86::BI__builtin_ia32_cmpss_mask:
4294   case X86::BI__builtin_ia32_cmpsh_mask:
4295   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
4296   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
4297   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
4298   case X86::BI__builtin_ia32_getexpsd128_round_mask:
4299   case X86::BI__builtin_ia32_getexpss128_round_mask:
4300   case X86::BI__builtin_ia32_getexpsh128_round_mask:
4301   case X86::BI__builtin_ia32_getmantpd512_mask:
4302   case X86::BI__builtin_ia32_getmantps512_mask:
4303   case X86::BI__builtin_ia32_getmantph512_mask:
4304   case X86::BI__builtin_ia32_maxsd_round_mask:
4305   case X86::BI__builtin_ia32_maxss_round_mask:
4306   case X86::BI__builtin_ia32_maxsh_round_mask:
4307   case X86::BI__builtin_ia32_minsd_round_mask:
4308   case X86::BI__builtin_ia32_minss_round_mask:
4309   case X86::BI__builtin_ia32_minsh_round_mask:
4310   case X86::BI__builtin_ia32_rcp28sd_round_mask:
4311   case X86::BI__builtin_ia32_rcp28ss_round_mask:
4312   case X86::BI__builtin_ia32_reducepd512_mask:
4313   case X86::BI__builtin_ia32_reduceps512_mask:
4314   case X86::BI__builtin_ia32_reduceph512_mask:
4315   case X86::BI__builtin_ia32_rndscalepd_mask:
4316   case X86::BI__builtin_ia32_rndscaleps_mask:
4317   case X86::BI__builtin_ia32_rndscaleph_mask:
4318   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
4319   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
4320     ArgNum = 4;
4321     break;
4322   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4323   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4324   case X86::BI__builtin_ia32_fixupimmps512_mask:
4325   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4326   case X86::BI__builtin_ia32_fixupimmsd_mask:
4327   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4328   case X86::BI__builtin_ia32_fixupimmss_mask:
4329   case X86::BI__builtin_ia32_fixupimmss_maskz:
4330   case X86::BI__builtin_ia32_getmantsd_round_mask:
4331   case X86::BI__builtin_ia32_getmantss_round_mask:
4332   case X86::BI__builtin_ia32_getmantsh_round_mask:
4333   case X86::BI__builtin_ia32_rangepd512_mask:
4334   case X86::BI__builtin_ia32_rangeps512_mask:
4335   case X86::BI__builtin_ia32_rangesd128_round_mask:
4336   case X86::BI__builtin_ia32_rangess128_round_mask:
4337   case X86::BI__builtin_ia32_reducesd_mask:
4338   case X86::BI__builtin_ia32_reducess_mask:
4339   case X86::BI__builtin_ia32_reducesh_mask:
4340   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4341   case X86::BI__builtin_ia32_rndscaless_round_mask:
4342   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4343     ArgNum = 5;
4344     break;
4345   case X86::BI__builtin_ia32_vcvtsd2si64:
4346   case X86::BI__builtin_ia32_vcvtsd2si32:
4347   case X86::BI__builtin_ia32_vcvtsd2usi32:
4348   case X86::BI__builtin_ia32_vcvtsd2usi64:
4349   case X86::BI__builtin_ia32_vcvtss2si32:
4350   case X86::BI__builtin_ia32_vcvtss2si64:
4351   case X86::BI__builtin_ia32_vcvtss2usi32:
4352   case X86::BI__builtin_ia32_vcvtss2usi64:
4353   case X86::BI__builtin_ia32_vcvtsh2si32:
4354   case X86::BI__builtin_ia32_vcvtsh2si64:
4355   case X86::BI__builtin_ia32_vcvtsh2usi32:
4356   case X86::BI__builtin_ia32_vcvtsh2usi64:
4357   case X86::BI__builtin_ia32_sqrtpd512:
4358   case X86::BI__builtin_ia32_sqrtps512:
4359   case X86::BI__builtin_ia32_sqrtph512:
4360     ArgNum = 1;
4361     HasRC = true;
4362     break;
4363   case X86::BI__builtin_ia32_addph512:
4364   case X86::BI__builtin_ia32_divph512:
4365   case X86::BI__builtin_ia32_mulph512:
4366   case X86::BI__builtin_ia32_subph512:
4367   case X86::BI__builtin_ia32_addpd512:
4368   case X86::BI__builtin_ia32_addps512:
4369   case X86::BI__builtin_ia32_divpd512:
4370   case X86::BI__builtin_ia32_divps512:
4371   case X86::BI__builtin_ia32_mulpd512:
4372   case X86::BI__builtin_ia32_mulps512:
4373   case X86::BI__builtin_ia32_subpd512:
4374   case X86::BI__builtin_ia32_subps512:
4375   case X86::BI__builtin_ia32_cvtsi2sd64:
4376   case X86::BI__builtin_ia32_cvtsi2ss32:
4377   case X86::BI__builtin_ia32_cvtsi2ss64:
4378   case X86::BI__builtin_ia32_cvtusi2sd64:
4379   case X86::BI__builtin_ia32_cvtusi2ss32:
4380   case X86::BI__builtin_ia32_cvtusi2ss64:
4381   case X86::BI__builtin_ia32_vcvtusi2sh:
4382   case X86::BI__builtin_ia32_vcvtusi642sh:
4383   case X86::BI__builtin_ia32_vcvtsi2sh:
4384   case X86::BI__builtin_ia32_vcvtsi642sh:
4385     ArgNum = 2;
4386     HasRC = true;
4387     break;
4388   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
4389   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
4390   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
4391   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
4392   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
4393   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
4394   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
4395   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
4396   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
4397   case X86::BI__builtin_ia32_cvtps2dq512_mask:
4398   case X86::BI__builtin_ia32_cvtps2qq512_mask:
4399   case X86::BI__builtin_ia32_cvtps2udq512_mask:
4400   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
4401   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
4402   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
4403   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
4404   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
4405   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
4406   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
4407   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
4408   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
4409   case X86::BI__builtin_ia32_vcvtph2w512_mask:
4410   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
4411   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
4412   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
4413   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
4414   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
4415   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
4416   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
4417     ArgNum = 3;
4418     HasRC = true;
4419     break;
4420   case X86::BI__builtin_ia32_addsh_round_mask:
4421   case X86::BI__builtin_ia32_addss_round_mask:
4422   case X86::BI__builtin_ia32_addsd_round_mask:
4423   case X86::BI__builtin_ia32_divsh_round_mask:
4424   case X86::BI__builtin_ia32_divss_round_mask:
4425   case X86::BI__builtin_ia32_divsd_round_mask:
4426   case X86::BI__builtin_ia32_mulsh_round_mask:
4427   case X86::BI__builtin_ia32_mulss_round_mask:
4428   case X86::BI__builtin_ia32_mulsd_round_mask:
4429   case X86::BI__builtin_ia32_subsh_round_mask:
4430   case X86::BI__builtin_ia32_subss_round_mask:
4431   case X86::BI__builtin_ia32_subsd_round_mask:
4432   case X86::BI__builtin_ia32_scalefph512_mask:
4433   case X86::BI__builtin_ia32_scalefpd512_mask:
4434   case X86::BI__builtin_ia32_scalefps512_mask:
4435   case X86::BI__builtin_ia32_scalefsd_round_mask:
4436   case X86::BI__builtin_ia32_scalefss_round_mask:
4437   case X86::BI__builtin_ia32_scalefsh_round_mask:
4438   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4439   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4440   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4441   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4442   case X86::BI__builtin_ia32_sqrtss_round_mask:
4443   case X86::BI__builtin_ia32_sqrtsh_round_mask:
4444   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4445   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4446   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4447   case X86::BI__builtin_ia32_vfmaddss3_mask:
4448   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4449   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4450   case X86::BI__builtin_ia32_vfmaddsh3_mask:
4451   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4452   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4453   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4454   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4455   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4456   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4457   case X86::BI__builtin_ia32_vfmaddps512_mask:
4458   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4459   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4460   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4461   case X86::BI__builtin_ia32_vfmaddph512_mask:
4462   case X86::BI__builtin_ia32_vfmaddph512_maskz:
4463   case X86::BI__builtin_ia32_vfmaddph512_mask3:
4464   case X86::BI__builtin_ia32_vfmsubph512_mask3:
4465   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4466   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4467   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4468   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4469   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4470   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4471   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4472   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4473   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4474   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4475   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4476   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4477   case X86::BI__builtin_ia32_vfmaddcsh_mask:
4478   case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
4479   case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
4480   case X86::BI__builtin_ia32_vfmaddcph512_mask:
4481   case X86::BI__builtin_ia32_vfmaddcph512_maskz:
4482   case X86::BI__builtin_ia32_vfmaddcph512_mask3:
4483   case X86::BI__builtin_ia32_vfcmaddcsh_mask:
4484   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
4485   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
4486   case X86::BI__builtin_ia32_vfcmaddcph512_mask:
4487   case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
4488   case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
4489   case X86::BI__builtin_ia32_vfmulcsh_mask:
4490   case X86::BI__builtin_ia32_vfmulcph512_mask:
4491   case X86::BI__builtin_ia32_vfcmulcsh_mask:
4492   case X86::BI__builtin_ia32_vfcmulcph512_mask:
4493     ArgNum = 4;
4494     HasRC = true;
4495     break;
4496   }
4497 
4498   llvm::APSInt Result;
4499 
4500   // We can't check the value of a dependent argument.
4501   Expr *Arg = TheCall->getArg(ArgNum);
4502   if (Arg->isTypeDependent() || Arg->isValueDependent())
4503     return false;
4504 
4505   // Check constant-ness first.
4506   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4507     return true;
4508 
4509   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4510   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4511   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4512   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4513   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4514       Result == 8/*ROUND_NO_EXC*/ ||
4515       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4516       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4517     return false;
4518 
4519   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4520          << Arg->getSourceRange();
4521 }
4522 
4523 // Check if the gather/scatter scale is legal.
4524 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4525                                              CallExpr *TheCall) {
4526   unsigned ArgNum = 0;
4527   switch (BuiltinID) {
4528   default:
4529     return false;
4530   case X86::BI__builtin_ia32_gatherpfdpd:
4531   case X86::BI__builtin_ia32_gatherpfdps:
4532   case X86::BI__builtin_ia32_gatherpfqpd:
4533   case X86::BI__builtin_ia32_gatherpfqps:
4534   case X86::BI__builtin_ia32_scatterpfdpd:
4535   case X86::BI__builtin_ia32_scatterpfdps:
4536   case X86::BI__builtin_ia32_scatterpfqpd:
4537   case X86::BI__builtin_ia32_scatterpfqps:
4538     ArgNum = 3;
4539     break;
4540   case X86::BI__builtin_ia32_gatherd_pd:
4541   case X86::BI__builtin_ia32_gatherd_pd256:
4542   case X86::BI__builtin_ia32_gatherq_pd:
4543   case X86::BI__builtin_ia32_gatherq_pd256:
4544   case X86::BI__builtin_ia32_gatherd_ps:
4545   case X86::BI__builtin_ia32_gatherd_ps256:
4546   case X86::BI__builtin_ia32_gatherq_ps:
4547   case X86::BI__builtin_ia32_gatherq_ps256:
4548   case X86::BI__builtin_ia32_gatherd_q:
4549   case X86::BI__builtin_ia32_gatherd_q256:
4550   case X86::BI__builtin_ia32_gatherq_q:
4551   case X86::BI__builtin_ia32_gatherq_q256:
4552   case X86::BI__builtin_ia32_gatherd_d:
4553   case X86::BI__builtin_ia32_gatherd_d256:
4554   case X86::BI__builtin_ia32_gatherq_d:
4555   case X86::BI__builtin_ia32_gatherq_d256:
4556   case X86::BI__builtin_ia32_gather3div2df:
4557   case X86::BI__builtin_ia32_gather3div2di:
4558   case X86::BI__builtin_ia32_gather3div4df:
4559   case X86::BI__builtin_ia32_gather3div4di:
4560   case X86::BI__builtin_ia32_gather3div4sf:
4561   case X86::BI__builtin_ia32_gather3div4si:
4562   case X86::BI__builtin_ia32_gather3div8sf:
4563   case X86::BI__builtin_ia32_gather3div8si:
4564   case X86::BI__builtin_ia32_gather3siv2df:
4565   case X86::BI__builtin_ia32_gather3siv2di:
4566   case X86::BI__builtin_ia32_gather3siv4df:
4567   case X86::BI__builtin_ia32_gather3siv4di:
4568   case X86::BI__builtin_ia32_gather3siv4sf:
4569   case X86::BI__builtin_ia32_gather3siv4si:
4570   case X86::BI__builtin_ia32_gather3siv8sf:
4571   case X86::BI__builtin_ia32_gather3siv8si:
4572   case X86::BI__builtin_ia32_gathersiv8df:
4573   case X86::BI__builtin_ia32_gathersiv16sf:
4574   case X86::BI__builtin_ia32_gatherdiv8df:
4575   case X86::BI__builtin_ia32_gatherdiv16sf:
4576   case X86::BI__builtin_ia32_gathersiv8di:
4577   case X86::BI__builtin_ia32_gathersiv16si:
4578   case X86::BI__builtin_ia32_gatherdiv8di:
4579   case X86::BI__builtin_ia32_gatherdiv16si:
4580   case X86::BI__builtin_ia32_scatterdiv2df:
4581   case X86::BI__builtin_ia32_scatterdiv2di:
4582   case X86::BI__builtin_ia32_scatterdiv4df:
4583   case X86::BI__builtin_ia32_scatterdiv4di:
4584   case X86::BI__builtin_ia32_scatterdiv4sf:
4585   case X86::BI__builtin_ia32_scatterdiv4si:
4586   case X86::BI__builtin_ia32_scatterdiv8sf:
4587   case X86::BI__builtin_ia32_scatterdiv8si:
4588   case X86::BI__builtin_ia32_scattersiv2df:
4589   case X86::BI__builtin_ia32_scattersiv2di:
4590   case X86::BI__builtin_ia32_scattersiv4df:
4591   case X86::BI__builtin_ia32_scattersiv4di:
4592   case X86::BI__builtin_ia32_scattersiv4sf:
4593   case X86::BI__builtin_ia32_scattersiv4si:
4594   case X86::BI__builtin_ia32_scattersiv8sf:
4595   case X86::BI__builtin_ia32_scattersiv8si:
4596   case X86::BI__builtin_ia32_scattersiv8df:
4597   case X86::BI__builtin_ia32_scattersiv16sf:
4598   case X86::BI__builtin_ia32_scatterdiv8df:
4599   case X86::BI__builtin_ia32_scatterdiv16sf:
4600   case X86::BI__builtin_ia32_scattersiv8di:
4601   case X86::BI__builtin_ia32_scattersiv16si:
4602   case X86::BI__builtin_ia32_scatterdiv8di:
4603   case X86::BI__builtin_ia32_scatterdiv16si:
4604     ArgNum = 4;
4605     break;
4606   }
4607 
4608   llvm::APSInt Result;
4609 
4610   // We can't check the value of a dependent argument.
4611   Expr *Arg = TheCall->getArg(ArgNum);
4612   if (Arg->isTypeDependent() || Arg->isValueDependent())
4613     return false;
4614 
4615   // Check constant-ness first.
4616   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4617     return true;
4618 
4619   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4620     return false;
4621 
4622   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4623          << Arg->getSourceRange();
4624 }
4625 
4626 enum { TileRegLow = 0, TileRegHigh = 7 };
4627 
4628 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4629                                              ArrayRef<int> ArgNums) {
4630   for (int ArgNum : ArgNums) {
4631     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4632       return true;
4633   }
4634   return false;
4635 }
4636 
4637 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4638                                         ArrayRef<int> ArgNums) {
4639   // Because the max number of tile register is TileRegHigh + 1, so here we use
4640   // each bit to represent the usage of them in bitset.
4641   std::bitset<TileRegHigh + 1> ArgValues;
4642   for (int ArgNum : ArgNums) {
4643     Expr *Arg = TheCall->getArg(ArgNum);
4644     if (Arg->isTypeDependent() || Arg->isValueDependent())
4645       continue;
4646 
4647     llvm::APSInt Result;
4648     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4649       return true;
4650     int ArgExtValue = Result.getExtValue();
4651     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4652            "Incorrect tile register num.");
4653     if (ArgValues.test(ArgExtValue))
4654       return Diag(TheCall->getBeginLoc(),
4655                   diag::err_x86_builtin_tile_arg_duplicate)
4656              << TheCall->getArg(ArgNum)->getSourceRange();
4657     ArgValues.set(ArgExtValue);
4658   }
4659   return false;
4660 }
4661 
4662 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4663                                                 ArrayRef<int> ArgNums) {
4664   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4665          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4666 }
4667 
4668 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4669   switch (BuiltinID) {
4670   default:
4671     return false;
4672   case X86::BI__builtin_ia32_tileloadd64:
4673   case X86::BI__builtin_ia32_tileloaddt164:
4674   case X86::BI__builtin_ia32_tilestored64:
4675   case X86::BI__builtin_ia32_tilezero:
4676     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4677   case X86::BI__builtin_ia32_tdpbssd:
4678   case X86::BI__builtin_ia32_tdpbsud:
4679   case X86::BI__builtin_ia32_tdpbusd:
4680   case X86::BI__builtin_ia32_tdpbuud:
4681   case X86::BI__builtin_ia32_tdpbf16ps:
4682     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4683   }
4684 }
4685 static bool isX86_32Builtin(unsigned BuiltinID) {
4686   // These builtins only work on x86-32 targets.
4687   switch (BuiltinID) {
4688   case X86::BI__builtin_ia32_readeflags_u32:
4689   case X86::BI__builtin_ia32_writeeflags_u32:
4690     return true;
4691   }
4692 
4693   return false;
4694 }
4695 
4696 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4697                                        CallExpr *TheCall) {
4698   if (BuiltinID == X86::BI__builtin_cpu_supports)
4699     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4700 
4701   if (BuiltinID == X86::BI__builtin_cpu_is)
4702     return SemaBuiltinCpuIs(*this, TI, TheCall);
4703 
4704   // Check for 32-bit only builtins on a 64-bit target.
4705   const llvm::Triple &TT = TI.getTriple();
4706   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4707     return Diag(TheCall->getCallee()->getBeginLoc(),
4708                 diag::err_32_bit_builtin_64_bit_tgt);
4709 
4710   // If the intrinsic has rounding or SAE make sure its valid.
4711   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4712     return true;
4713 
4714   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4715   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4716     return true;
4717 
4718   // If the intrinsic has a tile arguments, make sure they are valid.
4719   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4720     return true;
4721 
4722   // For intrinsics which take an immediate value as part of the instruction,
4723   // range check them here.
4724   int i = 0, l = 0, u = 0;
4725   switch (BuiltinID) {
4726   default:
4727     return false;
4728   case X86::BI__builtin_ia32_vec_ext_v2si:
4729   case X86::BI__builtin_ia32_vec_ext_v2di:
4730   case X86::BI__builtin_ia32_vextractf128_pd256:
4731   case X86::BI__builtin_ia32_vextractf128_ps256:
4732   case X86::BI__builtin_ia32_vextractf128_si256:
4733   case X86::BI__builtin_ia32_extract128i256:
4734   case X86::BI__builtin_ia32_extractf64x4_mask:
4735   case X86::BI__builtin_ia32_extracti64x4_mask:
4736   case X86::BI__builtin_ia32_extractf32x8_mask:
4737   case X86::BI__builtin_ia32_extracti32x8_mask:
4738   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4739   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4740   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4741   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4742     i = 1; l = 0; u = 1;
4743     break;
4744   case X86::BI__builtin_ia32_vec_set_v2di:
4745   case X86::BI__builtin_ia32_vinsertf128_pd256:
4746   case X86::BI__builtin_ia32_vinsertf128_ps256:
4747   case X86::BI__builtin_ia32_vinsertf128_si256:
4748   case X86::BI__builtin_ia32_insert128i256:
4749   case X86::BI__builtin_ia32_insertf32x8:
4750   case X86::BI__builtin_ia32_inserti32x8:
4751   case X86::BI__builtin_ia32_insertf64x4:
4752   case X86::BI__builtin_ia32_inserti64x4:
4753   case X86::BI__builtin_ia32_insertf64x2_256:
4754   case X86::BI__builtin_ia32_inserti64x2_256:
4755   case X86::BI__builtin_ia32_insertf32x4_256:
4756   case X86::BI__builtin_ia32_inserti32x4_256:
4757     i = 2; l = 0; u = 1;
4758     break;
4759   case X86::BI__builtin_ia32_vpermilpd:
4760   case X86::BI__builtin_ia32_vec_ext_v4hi:
4761   case X86::BI__builtin_ia32_vec_ext_v4si:
4762   case X86::BI__builtin_ia32_vec_ext_v4sf:
4763   case X86::BI__builtin_ia32_vec_ext_v4di:
4764   case X86::BI__builtin_ia32_extractf32x4_mask:
4765   case X86::BI__builtin_ia32_extracti32x4_mask:
4766   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4767   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4768     i = 1; l = 0; u = 3;
4769     break;
4770   case X86::BI_mm_prefetch:
4771   case X86::BI__builtin_ia32_vec_ext_v8hi:
4772   case X86::BI__builtin_ia32_vec_ext_v8si:
4773     i = 1; l = 0; u = 7;
4774     break;
4775   case X86::BI__builtin_ia32_sha1rnds4:
4776   case X86::BI__builtin_ia32_blendpd:
4777   case X86::BI__builtin_ia32_shufpd:
4778   case X86::BI__builtin_ia32_vec_set_v4hi:
4779   case X86::BI__builtin_ia32_vec_set_v4si:
4780   case X86::BI__builtin_ia32_vec_set_v4di:
4781   case X86::BI__builtin_ia32_shuf_f32x4_256:
4782   case X86::BI__builtin_ia32_shuf_f64x2_256:
4783   case X86::BI__builtin_ia32_shuf_i32x4_256:
4784   case X86::BI__builtin_ia32_shuf_i64x2_256:
4785   case X86::BI__builtin_ia32_insertf64x2_512:
4786   case X86::BI__builtin_ia32_inserti64x2_512:
4787   case X86::BI__builtin_ia32_insertf32x4:
4788   case X86::BI__builtin_ia32_inserti32x4:
4789     i = 2; l = 0; u = 3;
4790     break;
4791   case X86::BI__builtin_ia32_vpermil2pd:
4792   case X86::BI__builtin_ia32_vpermil2pd256:
4793   case X86::BI__builtin_ia32_vpermil2ps:
4794   case X86::BI__builtin_ia32_vpermil2ps256:
4795     i = 3; l = 0; u = 3;
4796     break;
4797   case X86::BI__builtin_ia32_cmpb128_mask:
4798   case X86::BI__builtin_ia32_cmpw128_mask:
4799   case X86::BI__builtin_ia32_cmpd128_mask:
4800   case X86::BI__builtin_ia32_cmpq128_mask:
4801   case X86::BI__builtin_ia32_cmpb256_mask:
4802   case X86::BI__builtin_ia32_cmpw256_mask:
4803   case X86::BI__builtin_ia32_cmpd256_mask:
4804   case X86::BI__builtin_ia32_cmpq256_mask:
4805   case X86::BI__builtin_ia32_cmpb512_mask:
4806   case X86::BI__builtin_ia32_cmpw512_mask:
4807   case X86::BI__builtin_ia32_cmpd512_mask:
4808   case X86::BI__builtin_ia32_cmpq512_mask:
4809   case X86::BI__builtin_ia32_ucmpb128_mask:
4810   case X86::BI__builtin_ia32_ucmpw128_mask:
4811   case X86::BI__builtin_ia32_ucmpd128_mask:
4812   case X86::BI__builtin_ia32_ucmpq128_mask:
4813   case X86::BI__builtin_ia32_ucmpb256_mask:
4814   case X86::BI__builtin_ia32_ucmpw256_mask:
4815   case X86::BI__builtin_ia32_ucmpd256_mask:
4816   case X86::BI__builtin_ia32_ucmpq256_mask:
4817   case X86::BI__builtin_ia32_ucmpb512_mask:
4818   case X86::BI__builtin_ia32_ucmpw512_mask:
4819   case X86::BI__builtin_ia32_ucmpd512_mask:
4820   case X86::BI__builtin_ia32_ucmpq512_mask:
4821   case X86::BI__builtin_ia32_vpcomub:
4822   case X86::BI__builtin_ia32_vpcomuw:
4823   case X86::BI__builtin_ia32_vpcomud:
4824   case X86::BI__builtin_ia32_vpcomuq:
4825   case X86::BI__builtin_ia32_vpcomb:
4826   case X86::BI__builtin_ia32_vpcomw:
4827   case X86::BI__builtin_ia32_vpcomd:
4828   case X86::BI__builtin_ia32_vpcomq:
4829   case X86::BI__builtin_ia32_vec_set_v8hi:
4830   case X86::BI__builtin_ia32_vec_set_v8si:
4831     i = 2; l = 0; u = 7;
4832     break;
4833   case X86::BI__builtin_ia32_vpermilpd256:
4834   case X86::BI__builtin_ia32_roundps:
4835   case X86::BI__builtin_ia32_roundpd:
4836   case X86::BI__builtin_ia32_roundps256:
4837   case X86::BI__builtin_ia32_roundpd256:
4838   case X86::BI__builtin_ia32_getmantpd128_mask:
4839   case X86::BI__builtin_ia32_getmantpd256_mask:
4840   case X86::BI__builtin_ia32_getmantps128_mask:
4841   case X86::BI__builtin_ia32_getmantps256_mask:
4842   case X86::BI__builtin_ia32_getmantpd512_mask:
4843   case X86::BI__builtin_ia32_getmantps512_mask:
4844   case X86::BI__builtin_ia32_getmantph128_mask:
4845   case X86::BI__builtin_ia32_getmantph256_mask:
4846   case X86::BI__builtin_ia32_getmantph512_mask:
4847   case X86::BI__builtin_ia32_vec_ext_v16qi:
4848   case X86::BI__builtin_ia32_vec_ext_v16hi:
4849     i = 1; l = 0; u = 15;
4850     break;
4851   case X86::BI__builtin_ia32_pblendd128:
4852   case X86::BI__builtin_ia32_blendps:
4853   case X86::BI__builtin_ia32_blendpd256:
4854   case X86::BI__builtin_ia32_shufpd256:
4855   case X86::BI__builtin_ia32_roundss:
4856   case X86::BI__builtin_ia32_roundsd:
4857   case X86::BI__builtin_ia32_rangepd128_mask:
4858   case X86::BI__builtin_ia32_rangepd256_mask:
4859   case X86::BI__builtin_ia32_rangepd512_mask:
4860   case X86::BI__builtin_ia32_rangeps128_mask:
4861   case X86::BI__builtin_ia32_rangeps256_mask:
4862   case X86::BI__builtin_ia32_rangeps512_mask:
4863   case X86::BI__builtin_ia32_getmantsd_round_mask:
4864   case X86::BI__builtin_ia32_getmantss_round_mask:
4865   case X86::BI__builtin_ia32_getmantsh_round_mask:
4866   case X86::BI__builtin_ia32_vec_set_v16qi:
4867   case X86::BI__builtin_ia32_vec_set_v16hi:
4868     i = 2; l = 0; u = 15;
4869     break;
4870   case X86::BI__builtin_ia32_vec_ext_v32qi:
4871     i = 1; l = 0; u = 31;
4872     break;
4873   case X86::BI__builtin_ia32_cmpps:
4874   case X86::BI__builtin_ia32_cmpss:
4875   case X86::BI__builtin_ia32_cmppd:
4876   case X86::BI__builtin_ia32_cmpsd:
4877   case X86::BI__builtin_ia32_cmpps256:
4878   case X86::BI__builtin_ia32_cmppd256:
4879   case X86::BI__builtin_ia32_cmpps128_mask:
4880   case X86::BI__builtin_ia32_cmppd128_mask:
4881   case X86::BI__builtin_ia32_cmpps256_mask:
4882   case X86::BI__builtin_ia32_cmppd256_mask:
4883   case X86::BI__builtin_ia32_cmpps512_mask:
4884   case X86::BI__builtin_ia32_cmppd512_mask:
4885   case X86::BI__builtin_ia32_cmpsd_mask:
4886   case X86::BI__builtin_ia32_cmpss_mask:
4887   case X86::BI__builtin_ia32_vec_set_v32qi:
4888     i = 2; l = 0; u = 31;
4889     break;
4890   case X86::BI__builtin_ia32_permdf256:
4891   case X86::BI__builtin_ia32_permdi256:
4892   case X86::BI__builtin_ia32_permdf512:
4893   case X86::BI__builtin_ia32_permdi512:
4894   case X86::BI__builtin_ia32_vpermilps:
4895   case X86::BI__builtin_ia32_vpermilps256:
4896   case X86::BI__builtin_ia32_vpermilpd512:
4897   case X86::BI__builtin_ia32_vpermilps512:
4898   case X86::BI__builtin_ia32_pshufd:
4899   case X86::BI__builtin_ia32_pshufd256:
4900   case X86::BI__builtin_ia32_pshufd512:
4901   case X86::BI__builtin_ia32_pshufhw:
4902   case X86::BI__builtin_ia32_pshufhw256:
4903   case X86::BI__builtin_ia32_pshufhw512:
4904   case X86::BI__builtin_ia32_pshuflw:
4905   case X86::BI__builtin_ia32_pshuflw256:
4906   case X86::BI__builtin_ia32_pshuflw512:
4907   case X86::BI__builtin_ia32_vcvtps2ph:
4908   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4909   case X86::BI__builtin_ia32_vcvtps2ph256:
4910   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4911   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4912   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4913   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4914   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4915   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4916   case X86::BI__builtin_ia32_rndscaleps_mask:
4917   case X86::BI__builtin_ia32_rndscalepd_mask:
4918   case X86::BI__builtin_ia32_rndscaleph_mask:
4919   case X86::BI__builtin_ia32_reducepd128_mask:
4920   case X86::BI__builtin_ia32_reducepd256_mask:
4921   case X86::BI__builtin_ia32_reducepd512_mask:
4922   case X86::BI__builtin_ia32_reduceps128_mask:
4923   case X86::BI__builtin_ia32_reduceps256_mask:
4924   case X86::BI__builtin_ia32_reduceps512_mask:
4925   case X86::BI__builtin_ia32_reduceph128_mask:
4926   case X86::BI__builtin_ia32_reduceph256_mask:
4927   case X86::BI__builtin_ia32_reduceph512_mask:
4928   case X86::BI__builtin_ia32_prold512:
4929   case X86::BI__builtin_ia32_prolq512:
4930   case X86::BI__builtin_ia32_prold128:
4931   case X86::BI__builtin_ia32_prold256:
4932   case X86::BI__builtin_ia32_prolq128:
4933   case X86::BI__builtin_ia32_prolq256:
4934   case X86::BI__builtin_ia32_prord512:
4935   case X86::BI__builtin_ia32_prorq512:
4936   case X86::BI__builtin_ia32_prord128:
4937   case X86::BI__builtin_ia32_prord256:
4938   case X86::BI__builtin_ia32_prorq128:
4939   case X86::BI__builtin_ia32_prorq256:
4940   case X86::BI__builtin_ia32_fpclasspd128_mask:
4941   case X86::BI__builtin_ia32_fpclasspd256_mask:
4942   case X86::BI__builtin_ia32_fpclassps128_mask:
4943   case X86::BI__builtin_ia32_fpclassps256_mask:
4944   case X86::BI__builtin_ia32_fpclassps512_mask:
4945   case X86::BI__builtin_ia32_fpclasspd512_mask:
4946   case X86::BI__builtin_ia32_fpclassph128_mask:
4947   case X86::BI__builtin_ia32_fpclassph256_mask:
4948   case X86::BI__builtin_ia32_fpclassph512_mask:
4949   case X86::BI__builtin_ia32_fpclasssd_mask:
4950   case X86::BI__builtin_ia32_fpclassss_mask:
4951   case X86::BI__builtin_ia32_fpclasssh_mask:
4952   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4953   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4954   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4955   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4956   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4957   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4958   case X86::BI__builtin_ia32_kshiftliqi:
4959   case X86::BI__builtin_ia32_kshiftlihi:
4960   case X86::BI__builtin_ia32_kshiftlisi:
4961   case X86::BI__builtin_ia32_kshiftlidi:
4962   case X86::BI__builtin_ia32_kshiftriqi:
4963   case X86::BI__builtin_ia32_kshiftrihi:
4964   case X86::BI__builtin_ia32_kshiftrisi:
4965   case X86::BI__builtin_ia32_kshiftridi:
4966     i = 1; l = 0; u = 255;
4967     break;
4968   case X86::BI__builtin_ia32_vperm2f128_pd256:
4969   case X86::BI__builtin_ia32_vperm2f128_ps256:
4970   case X86::BI__builtin_ia32_vperm2f128_si256:
4971   case X86::BI__builtin_ia32_permti256:
4972   case X86::BI__builtin_ia32_pblendw128:
4973   case X86::BI__builtin_ia32_pblendw256:
4974   case X86::BI__builtin_ia32_blendps256:
4975   case X86::BI__builtin_ia32_pblendd256:
4976   case X86::BI__builtin_ia32_palignr128:
4977   case X86::BI__builtin_ia32_palignr256:
4978   case X86::BI__builtin_ia32_palignr512:
4979   case X86::BI__builtin_ia32_alignq512:
4980   case X86::BI__builtin_ia32_alignd512:
4981   case X86::BI__builtin_ia32_alignd128:
4982   case X86::BI__builtin_ia32_alignd256:
4983   case X86::BI__builtin_ia32_alignq128:
4984   case X86::BI__builtin_ia32_alignq256:
4985   case X86::BI__builtin_ia32_vcomisd:
4986   case X86::BI__builtin_ia32_vcomiss:
4987   case X86::BI__builtin_ia32_shuf_f32x4:
4988   case X86::BI__builtin_ia32_shuf_f64x2:
4989   case X86::BI__builtin_ia32_shuf_i32x4:
4990   case X86::BI__builtin_ia32_shuf_i64x2:
4991   case X86::BI__builtin_ia32_shufpd512:
4992   case X86::BI__builtin_ia32_shufps:
4993   case X86::BI__builtin_ia32_shufps256:
4994   case X86::BI__builtin_ia32_shufps512:
4995   case X86::BI__builtin_ia32_dbpsadbw128:
4996   case X86::BI__builtin_ia32_dbpsadbw256:
4997   case X86::BI__builtin_ia32_dbpsadbw512:
4998   case X86::BI__builtin_ia32_vpshldd128:
4999   case X86::BI__builtin_ia32_vpshldd256:
5000   case X86::BI__builtin_ia32_vpshldd512:
5001   case X86::BI__builtin_ia32_vpshldq128:
5002   case X86::BI__builtin_ia32_vpshldq256:
5003   case X86::BI__builtin_ia32_vpshldq512:
5004   case X86::BI__builtin_ia32_vpshldw128:
5005   case X86::BI__builtin_ia32_vpshldw256:
5006   case X86::BI__builtin_ia32_vpshldw512:
5007   case X86::BI__builtin_ia32_vpshrdd128:
5008   case X86::BI__builtin_ia32_vpshrdd256:
5009   case X86::BI__builtin_ia32_vpshrdd512:
5010   case X86::BI__builtin_ia32_vpshrdq128:
5011   case X86::BI__builtin_ia32_vpshrdq256:
5012   case X86::BI__builtin_ia32_vpshrdq512:
5013   case X86::BI__builtin_ia32_vpshrdw128:
5014   case X86::BI__builtin_ia32_vpshrdw256:
5015   case X86::BI__builtin_ia32_vpshrdw512:
5016     i = 2; l = 0; u = 255;
5017     break;
5018   case X86::BI__builtin_ia32_fixupimmpd512_mask:
5019   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
5020   case X86::BI__builtin_ia32_fixupimmps512_mask:
5021   case X86::BI__builtin_ia32_fixupimmps512_maskz:
5022   case X86::BI__builtin_ia32_fixupimmsd_mask:
5023   case X86::BI__builtin_ia32_fixupimmsd_maskz:
5024   case X86::BI__builtin_ia32_fixupimmss_mask:
5025   case X86::BI__builtin_ia32_fixupimmss_maskz:
5026   case X86::BI__builtin_ia32_fixupimmpd128_mask:
5027   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
5028   case X86::BI__builtin_ia32_fixupimmpd256_mask:
5029   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
5030   case X86::BI__builtin_ia32_fixupimmps128_mask:
5031   case X86::BI__builtin_ia32_fixupimmps128_maskz:
5032   case X86::BI__builtin_ia32_fixupimmps256_mask:
5033   case X86::BI__builtin_ia32_fixupimmps256_maskz:
5034   case X86::BI__builtin_ia32_pternlogd512_mask:
5035   case X86::BI__builtin_ia32_pternlogd512_maskz:
5036   case X86::BI__builtin_ia32_pternlogq512_mask:
5037   case X86::BI__builtin_ia32_pternlogq512_maskz:
5038   case X86::BI__builtin_ia32_pternlogd128_mask:
5039   case X86::BI__builtin_ia32_pternlogd128_maskz:
5040   case X86::BI__builtin_ia32_pternlogd256_mask:
5041   case X86::BI__builtin_ia32_pternlogd256_maskz:
5042   case X86::BI__builtin_ia32_pternlogq128_mask:
5043   case X86::BI__builtin_ia32_pternlogq128_maskz:
5044   case X86::BI__builtin_ia32_pternlogq256_mask:
5045   case X86::BI__builtin_ia32_pternlogq256_maskz:
5046     i = 3; l = 0; u = 255;
5047     break;
5048   case X86::BI__builtin_ia32_gatherpfdpd:
5049   case X86::BI__builtin_ia32_gatherpfdps:
5050   case X86::BI__builtin_ia32_gatherpfqpd:
5051   case X86::BI__builtin_ia32_gatherpfqps:
5052   case X86::BI__builtin_ia32_scatterpfdpd:
5053   case X86::BI__builtin_ia32_scatterpfdps:
5054   case X86::BI__builtin_ia32_scatterpfqpd:
5055   case X86::BI__builtin_ia32_scatterpfqps:
5056     i = 4; l = 2; u = 3;
5057     break;
5058   case X86::BI__builtin_ia32_reducesd_mask:
5059   case X86::BI__builtin_ia32_reducess_mask:
5060   case X86::BI__builtin_ia32_rndscalesd_round_mask:
5061   case X86::BI__builtin_ia32_rndscaless_round_mask:
5062   case X86::BI__builtin_ia32_rndscalesh_round_mask:
5063   case X86::BI__builtin_ia32_reducesh_mask:
5064     i = 4; l = 0; u = 255;
5065     break;
5066   }
5067 
5068   // Note that we don't force a hard error on the range check here, allowing
5069   // template-generated or macro-generated dead code to potentially have out-of-
5070   // range values. These need to code generate, but don't need to necessarily
5071   // make any sense. We use a warning that defaults to an error.
5072   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
5073 }
5074 
5075 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
5076 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
5077 /// Returns true when the format fits the function and the FormatStringInfo has
5078 /// been populated.
5079 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
5080                                FormatStringInfo *FSI) {
5081   FSI->HasVAListArg = Format->getFirstArg() == 0;
5082   FSI->FormatIdx = Format->getFormatIdx() - 1;
5083   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
5084 
5085   // The way the format attribute works in GCC, the implicit this argument
5086   // of member functions is counted. However, it doesn't appear in our own
5087   // lists, so decrement format_idx in that case.
5088   if (IsCXXMember) {
5089     if(FSI->FormatIdx == 0)
5090       return false;
5091     --FSI->FormatIdx;
5092     if (FSI->FirstDataArg != 0)
5093       --FSI->FirstDataArg;
5094   }
5095   return true;
5096 }
5097 
5098 /// Checks if a the given expression evaluates to null.
5099 ///
5100 /// Returns true if the value evaluates to null.
5101 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
5102   // If the expression has non-null type, it doesn't evaluate to null.
5103   if (auto nullability
5104         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
5105     if (*nullability == NullabilityKind::NonNull)
5106       return false;
5107   }
5108 
5109   // As a special case, transparent unions initialized with zero are
5110   // considered null for the purposes of the nonnull attribute.
5111   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
5112     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
5113       if (const CompoundLiteralExpr *CLE =
5114           dyn_cast<CompoundLiteralExpr>(Expr))
5115         if (const InitListExpr *ILE =
5116             dyn_cast<InitListExpr>(CLE->getInitializer()))
5117           Expr = ILE->getInit(0);
5118   }
5119 
5120   bool Result;
5121   return (!Expr->isValueDependent() &&
5122           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
5123           !Result);
5124 }
5125 
5126 static void CheckNonNullArgument(Sema &S,
5127                                  const Expr *ArgExpr,
5128                                  SourceLocation CallSiteLoc) {
5129   if (CheckNonNullExpr(S, ArgExpr))
5130     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
5131                           S.PDiag(diag::warn_null_arg)
5132                               << ArgExpr->getSourceRange());
5133 }
5134 
5135 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
5136   FormatStringInfo FSI;
5137   if ((GetFormatStringType(Format) == FST_NSString) &&
5138       getFormatStringInfo(Format, false, &FSI)) {
5139     Idx = FSI.FormatIdx;
5140     return true;
5141   }
5142   return false;
5143 }
5144 
5145 /// Diagnose use of %s directive in an NSString which is being passed
5146 /// as formatting string to formatting method.
5147 static void
5148 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
5149                                         const NamedDecl *FDecl,
5150                                         Expr **Args,
5151                                         unsigned NumArgs) {
5152   unsigned Idx = 0;
5153   bool Format = false;
5154   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
5155   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
5156     Idx = 2;
5157     Format = true;
5158   }
5159   else
5160     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5161       if (S.GetFormatNSStringIdx(I, Idx)) {
5162         Format = true;
5163         break;
5164       }
5165     }
5166   if (!Format || NumArgs <= Idx)
5167     return;
5168   const Expr *FormatExpr = Args[Idx];
5169   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
5170     FormatExpr = CSCE->getSubExpr();
5171   const StringLiteral *FormatString;
5172   if (const ObjCStringLiteral *OSL =
5173       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
5174     FormatString = OSL->getString();
5175   else
5176     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
5177   if (!FormatString)
5178     return;
5179   if (S.FormatStringHasSArg(FormatString)) {
5180     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
5181       << "%s" << 1 << 1;
5182     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
5183       << FDecl->getDeclName();
5184   }
5185 }
5186 
5187 /// Determine whether the given type has a non-null nullability annotation.
5188 static bool isNonNullType(ASTContext &ctx, QualType type) {
5189   if (auto nullability = type->getNullability(ctx))
5190     return *nullability == NullabilityKind::NonNull;
5191 
5192   return false;
5193 }
5194 
5195 static void CheckNonNullArguments(Sema &S,
5196                                   const NamedDecl *FDecl,
5197                                   const FunctionProtoType *Proto,
5198                                   ArrayRef<const Expr *> Args,
5199                                   SourceLocation CallSiteLoc) {
5200   assert((FDecl || Proto) && "Need a function declaration or prototype");
5201 
5202   // Already checked by by constant evaluator.
5203   if (S.isConstantEvaluated())
5204     return;
5205   // Check the attributes attached to the method/function itself.
5206   llvm::SmallBitVector NonNullArgs;
5207   if (FDecl) {
5208     // Handle the nonnull attribute on the function/method declaration itself.
5209     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
5210       if (!NonNull->args_size()) {
5211         // Easy case: all pointer arguments are nonnull.
5212         for (const auto *Arg : Args)
5213           if (S.isValidPointerAttrType(Arg->getType()))
5214             CheckNonNullArgument(S, Arg, CallSiteLoc);
5215         return;
5216       }
5217 
5218       for (const ParamIdx &Idx : NonNull->args()) {
5219         unsigned IdxAST = Idx.getASTIndex();
5220         if (IdxAST >= Args.size())
5221           continue;
5222         if (NonNullArgs.empty())
5223           NonNullArgs.resize(Args.size());
5224         NonNullArgs.set(IdxAST);
5225       }
5226     }
5227   }
5228 
5229   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
5230     // Handle the nonnull attribute on the parameters of the
5231     // function/method.
5232     ArrayRef<ParmVarDecl*> parms;
5233     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
5234       parms = FD->parameters();
5235     else
5236       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
5237 
5238     unsigned ParamIndex = 0;
5239     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
5240          I != E; ++I, ++ParamIndex) {
5241       const ParmVarDecl *PVD = *I;
5242       if (PVD->hasAttr<NonNullAttr>() ||
5243           isNonNullType(S.Context, PVD->getType())) {
5244         if (NonNullArgs.empty())
5245           NonNullArgs.resize(Args.size());
5246 
5247         NonNullArgs.set(ParamIndex);
5248       }
5249     }
5250   } else {
5251     // If we have a non-function, non-method declaration but no
5252     // function prototype, try to dig out the function prototype.
5253     if (!Proto) {
5254       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
5255         QualType type = VD->getType().getNonReferenceType();
5256         if (auto pointerType = type->getAs<PointerType>())
5257           type = pointerType->getPointeeType();
5258         else if (auto blockType = type->getAs<BlockPointerType>())
5259           type = blockType->getPointeeType();
5260         // FIXME: data member pointers?
5261 
5262         // Dig out the function prototype, if there is one.
5263         Proto = type->getAs<FunctionProtoType>();
5264       }
5265     }
5266 
5267     // Fill in non-null argument information from the nullability
5268     // information on the parameter types (if we have them).
5269     if (Proto) {
5270       unsigned Index = 0;
5271       for (auto paramType : Proto->getParamTypes()) {
5272         if (isNonNullType(S.Context, paramType)) {
5273           if (NonNullArgs.empty())
5274             NonNullArgs.resize(Args.size());
5275 
5276           NonNullArgs.set(Index);
5277         }
5278 
5279         ++Index;
5280       }
5281     }
5282   }
5283 
5284   // Check for non-null arguments.
5285   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
5286        ArgIndex != ArgIndexEnd; ++ArgIndex) {
5287     if (NonNullArgs[ArgIndex])
5288       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
5289   }
5290 }
5291 
5292 /// Warn if a pointer or reference argument passed to a function points to an
5293 /// object that is less aligned than the parameter. This can happen when
5294 /// creating a typedef with a lower alignment than the original type and then
5295 /// calling functions defined in terms of the original type.
5296 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
5297                              StringRef ParamName, QualType ArgTy,
5298                              QualType ParamTy) {
5299 
5300   // If a function accepts a pointer or reference type
5301   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
5302     return;
5303 
5304   // If the parameter is a pointer type, get the pointee type for the
5305   // argument too. If the parameter is a reference type, don't try to get
5306   // the pointee type for the argument.
5307   if (ParamTy->isPointerType())
5308     ArgTy = ArgTy->getPointeeType();
5309 
5310   // Remove reference or pointer
5311   ParamTy = ParamTy->getPointeeType();
5312 
5313   // Find expected alignment, and the actual alignment of the passed object.
5314   // getTypeAlignInChars requires complete types
5315   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
5316       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
5317       ArgTy->isUndeducedType())
5318     return;
5319 
5320   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
5321   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
5322 
5323   // If the argument is less aligned than the parameter, there is a
5324   // potential alignment issue.
5325   if (ArgAlign < ParamAlign)
5326     Diag(Loc, diag::warn_param_mismatched_alignment)
5327         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
5328         << ParamName << (FDecl != nullptr) << FDecl;
5329 }
5330 
5331 /// Handles the checks for format strings, non-POD arguments to vararg
5332 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
5333 /// attributes.
5334 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
5335                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
5336                      bool IsMemberFunction, SourceLocation Loc,
5337                      SourceRange Range, VariadicCallType CallType) {
5338   // FIXME: We should check as much as we can in the template definition.
5339   if (CurContext->isDependentContext())
5340     return;
5341 
5342   // Printf and scanf checking.
5343   llvm::SmallBitVector CheckedVarArgs;
5344   if (FDecl) {
5345     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5346       // Only create vector if there are format attributes.
5347       CheckedVarArgs.resize(Args.size());
5348 
5349       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
5350                            CheckedVarArgs);
5351     }
5352   }
5353 
5354   // Refuse POD arguments that weren't caught by the format string
5355   // checks above.
5356   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
5357   if (CallType != VariadicDoesNotApply &&
5358       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
5359     unsigned NumParams = Proto ? Proto->getNumParams()
5360                        : FDecl && isa<FunctionDecl>(FDecl)
5361                            ? cast<FunctionDecl>(FDecl)->getNumParams()
5362                        : FDecl && isa<ObjCMethodDecl>(FDecl)
5363                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
5364                        : 0;
5365 
5366     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
5367       // Args[ArgIdx] can be null in malformed code.
5368       if (const Expr *Arg = Args[ArgIdx]) {
5369         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
5370           checkVariadicArgument(Arg, CallType);
5371       }
5372     }
5373   }
5374 
5375   if (FDecl || Proto) {
5376     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
5377 
5378     // Type safety checking.
5379     if (FDecl) {
5380       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
5381         CheckArgumentWithTypeTag(I, Args, Loc);
5382     }
5383   }
5384 
5385   // Check that passed arguments match the alignment of original arguments.
5386   // Try to get the missing prototype from the declaration.
5387   if (!Proto && FDecl) {
5388     const auto *FT = FDecl->getFunctionType();
5389     if (isa_and_nonnull<FunctionProtoType>(FT))
5390       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
5391   }
5392   if (Proto) {
5393     // For variadic functions, we may have more args than parameters.
5394     // For some K&R functions, we may have less args than parameters.
5395     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
5396     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
5397       // Args[ArgIdx] can be null in malformed code.
5398       if (const Expr *Arg = Args[ArgIdx]) {
5399         if (Arg->containsErrors())
5400           continue;
5401 
5402         QualType ParamTy = Proto->getParamType(ArgIdx);
5403         QualType ArgTy = Arg->getType();
5404         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
5405                           ArgTy, ParamTy);
5406       }
5407     }
5408   }
5409 
5410   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
5411     auto *AA = FDecl->getAttr<AllocAlignAttr>();
5412     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
5413     if (!Arg->isValueDependent()) {
5414       Expr::EvalResult Align;
5415       if (Arg->EvaluateAsInt(Align, Context)) {
5416         const llvm::APSInt &I = Align.Val.getInt();
5417         if (!I.isPowerOf2())
5418           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
5419               << Arg->getSourceRange();
5420 
5421         if (I > Sema::MaximumAlignment)
5422           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
5423               << Arg->getSourceRange() << Sema::MaximumAlignment;
5424       }
5425     }
5426   }
5427 
5428   if (FD)
5429     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
5430 }
5431 
5432 /// CheckConstructorCall - Check a constructor call for correctness and safety
5433 /// properties not enforced by the C type system.
5434 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5435                                 ArrayRef<const Expr *> Args,
5436                                 const FunctionProtoType *Proto,
5437                                 SourceLocation Loc) {
5438   VariadicCallType CallType =
5439       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5440 
5441   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5442   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5443                     Context.getPointerType(Ctor->getThisObjectType()));
5444 
5445   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5446             Loc, SourceRange(), CallType);
5447 }
5448 
5449 /// CheckFunctionCall - Check a direct function call for various correctness
5450 /// and safety properties not strictly enforced by the C type system.
5451 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5452                              const FunctionProtoType *Proto) {
5453   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5454                               isa<CXXMethodDecl>(FDecl);
5455   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5456                           IsMemberOperatorCall;
5457   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5458                                                   TheCall->getCallee());
5459   Expr** Args = TheCall->getArgs();
5460   unsigned NumArgs = TheCall->getNumArgs();
5461 
5462   Expr *ImplicitThis = nullptr;
5463   if (IsMemberOperatorCall) {
5464     // If this is a call to a member operator, hide the first argument
5465     // from checkCall.
5466     // FIXME: Our choice of AST representation here is less than ideal.
5467     ImplicitThis = Args[0];
5468     ++Args;
5469     --NumArgs;
5470   } else if (IsMemberFunction)
5471     ImplicitThis =
5472         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5473 
5474   if (ImplicitThis) {
5475     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5476     // used.
5477     QualType ThisType = ImplicitThis->getType();
5478     if (!ThisType->isPointerType()) {
5479       assert(!ThisType->isReferenceType());
5480       ThisType = Context.getPointerType(ThisType);
5481     }
5482 
5483     QualType ThisTypeFromDecl =
5484         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5485 
5486     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5487                       ThisTypeFromDecl);
5488   }
5489 
5490   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5491             IsMemberFunction, TheCall->getRParenLoc(),
5492             TheCall->getCallee()->getSourceRange(), CallType);
5493 
5494   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5495   // None of the checks below are needed for functions that don't have
5496   // simple names (e.g., C++ conversion functions).
5497   if (!FnInfo)
5498     return false;
5499 
5500   // Enforce TCB except for builtin calls, which are always allowed.
5501   if (FDecl->getBuiltinID() == 0)
5502     CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
5503 
5504   CheckAbsoluteValueFunction(TheCall, FDecl);
5505   CheckMaxUnsignedZero(TheCall, FDecl);
5506 
5507   if (getLangOpts().ObjC)
5508     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5509 
5510   unsigned CMId = FDecl->getMemoryFunctionKind();
5511 
5512   // Handle memory setting and copying functions.
5513   switch (CMId) {
5514   case 0:
5515     return false;
5516   case Builtin::BIstrlcpy: // fallthrough
5517   case Builtin::BIstrlcat:
5518     CheckStrlcpycatArguments(TheCall, FnInfo);
5519     break;
5520   case Builtin::BIstrncat:
5521     CheckStrncatArguments(TheCall, FnInfo);
5522     break;
5523   case Builtin::BIfree:
5524     CheckFreeArguments(TheCall);
5525     break;
5526   default:
5527     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5528   }
5529 
5530   return false;
5531 }
5532 
5533 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5534                                ArrayRef<const Expr *> Args) {
5535   VariadicCallType CallType =
5536       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5537 
5538   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5539             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5540             CallType);
5541 
5542   CheckTCBEnforcement(lbrac, Method);
5543 
5544   return false;
5545 }
5546 
5547 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5548                             const FunctionProtoType *Proto) {
5549   QualType Ty;
5550   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5551     Ty = V->getType().getNonReferenceType();
5552   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5553     Ty = F->getType().getNonReferenceType();
5554   else
5555     return false;
5556 
5557   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5558       !Ty->isFunctionProtoType())
5559     return false;
5560 
5561   VariadicCallType CallType;
5562   if (!Proto || !Proto->isVariadic()) {
5563     CallType = VariadicDoesNotApply;
5564   } else if (Ty->isBlockPointerType()) {
5565     CallType = VariadicBlock;
5566   } else { // Ty->isFunctionPointerType()
5567     CallType = VariadicFunction;
5568   }
5569 
5570   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5571             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5572             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5573             TheCall->getCallee()->getSourceRange(), CallType);
5574 
5575   return false;
5576 }
5577 
5578 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5579 /// such as function pointers returned from functions.
5580 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5581   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5582                                                   TheCall->getCallee());
5583   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5584             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5585             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5586             TheCall->getCallee()->getSourceRange(), CallType);
5587 
5588   return false;
5589 }
5590 
5591 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5592   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5593     return false;
5594 
5595   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5596   switch (Op) {
5597   case AtomicExpr::AO__c11_atomic_init:
5598   case AtomicExpr::AO__opencl_atomic_init:
5599     llvm_unreachable("There is no ordering argument for an init");
5600 
5601   case AtomicExpr::AO__c11_atomic_load:
5602   case AtomicExpr::AO__opencl_atomic_load:
5603   case AtomicExpr::AO__hip_atomic_load:
5604   case AtomicExpr::AO__atomic_load_n:
5605   case AtomicExpr::AO__atomic_load:
5606     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5607            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5608 
5609   case AtomicExpr::AO__c11_atomic_store:
5610   case AtomicExpr::AO__opencl_atomic_store:
5611   case AtomicExpr::AO__hip_atomic_store:
5612   case AtomicExpr::AO__atomic_store:
5613   case AtomicExpr::AO__atomic_store_n:
5614     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5615            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5616            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5617 
5618   default:
5619     return true;
5620   }
5621 }
5622 
5623 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5624                                          AtomicExpr::AtomicOp Op) {
5625   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5626   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5627   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5628   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5629                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5630                          Op);
5631 }
5632 
5633 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5634                                  SourceLocation RParenLoc, MultiExprArg Args,
5635                                  AtomicExpr::AtomicOp Op,
5636                                  AtomicArgumentOrder ArgOrder) {
5637   // All the non-OpenCL operations take one of the following forms.
5638   // The OpenCL operations take the __c11 forms with one extra argument for
5639   // synchronization scope.
5640   enum {
5641     // C    __c11_atomic_init(A *, C)
5642     Init,
5643 
5644     // C    __c11_atomic_load(A *, int)
5645     Load,
5646 
5647     // void __atomic_load(A *, CP, int)
5648     LoadCopy,
5649 
5650     // void __atomic_store(A *, CP, int)
5651     Copy,
5652 
5653     // C    __c11_atomic_add(A *, M, int)
5654     Arithmetic,
5655 
5656     // C    __atomic_exchange_n(A *, CP, int)
5657     Xchg,
5658 
5659     // void __atomic_exchange(A *, C *, CP, int)
5660     GNUXchg,
5661 
5662     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5663     C11CmpXchg,
5664 
5665     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5666     GNUCmpXchg
5667   } Form = Init;
5668 
5669   const unsigned NumForm = GNUCmpXchg + 1;
5670   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5671   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5672   // where:
5673   //   C is an appropriate type,
5674   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5675   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5676   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5677   //   the int parameters are for orderings.
5678 
5679   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5680       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5681       "need to update code for modified forms");
5682   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5683                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5684                         AtomicExpr::AO__atomic_load,
5685                 "need to update code for modified C11 atomics");
5686   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5687                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5688   bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load &&
5689                Op <= AtomicExpr::AO__hip_atomic_fetch_max;
5690   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5691                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5692                IsOpenCL;
5693   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5694              Op == AtomicExpr::AO__atomic_store_n ||
5695              Op == AtomicExpr::AO__atomic_exchange_n ||
5696              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5697   bool IsAddSub = false;
5698 
5699   switch (Op) {
5700   case AtomicExpr::AO__c11_atomic_init:
5701   case AtomicExpr::AO__opencl_atomic_init:
5702     Form = Init;
5703     break;
5704 
5705   case AtomicExpr::AO__c11_atomic_load:
5706   case AtomicExpr::AO__opencl_atomic_load:
5707   case AtomicExpr::AO__hip_atomic_load:
5708   case AtomicExpr::AO__atomic_load_n:
5709     Form = Load;
5710     break;
5711 
5712   case AtomicExpr::AO__atomic_load:
5713     Form = LoadCopy;
5714     break;
5715 
5716   case AtomicExpr::AO__c11_atomic_store:
5717   case AtomicExpr::AO__opencl_atomic_store:
5718   case AtomicExpr::AO__hip_atomic_store:
5719   case AtomicExpr::AO__atomic_store:
5720   case AtomicExpr::AO__atomic_store_n:
5721     Form = Copy;
5722     break;
5723   case AtomicExpr::AO__hip_atomic_fetch_add:
5724   case AtomicExpr::AO__hip_atomic_fetch_min:
5725   case AtomicExpr::AO__hip_atomic_fetch_max:
5726   case AtomicExpr::AO__c11_atomic_fetch_add:
5727   case AtomicExpr::AO__c11_atomic_fetch_sub:
5728   case AtomicExpr::AO__opencl_atomic_fetch_add:
5729   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5730   case AtomicExpr::AO__atomic_fetch_add:
5731   case AtomicExpr::AO__atomic_fetch_sub:
5732   case AtomicExpr::AO__atomic_add_fetch:
5733   case AtomicExpr::AO__atomic_sub_fetch:
5734     IsAddSub = true;
5735     Form = Arithmetic;
5736     break;
5737   case AtomicExpr::AO__c11_atomic_fetch_and:
5738   case AtomicExpr::AO__c11_atomic_fetch_or:
5739   case AtomicExpr::AO__c11_atomic_fetch_xor:
5740   case AtomicExpr::AO__hip_atomic_fetch_and:
5741   case AtomicExpr::AO__hip_atomic_fetch_or:
5742   case AtomicExpr::AO__hip_atomic_fetch_xor:
5743   case AtomicExpr::AO__c11_atomic_fetch_nand:
5744   case AtomicExpr::AO__opencl_atomic_fetch_and:
5745   case AtomicExpr::AO__opencl_atomic_fetch_or:
5746   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5747   case AtomicExpr::AO__atomic_fetch_and:
5748   case AtomicExpr::AO__atomic_fetch_or:
5749   case AtomicExpr::AO__atomic_fetch_xor:
5750   case AtomicExpr::AO__atomic_fetch_nand:
5751   case AtomicExpr::AO__atomic_and_fetch:
5752   case AtomicExpr::AO__atomic_or_fetch:
5753   case AtomicExpr::AO__atomic_xor_fetch:
5754   case AtomicExpr::AO__atomic_nand_fetch:
5755     Form = Arithmetic;
5756     break;
5757   case AtomicExpr::AO__c11_atomic_fetch_min:
5758   case AtomicExpr::AO__c11_atomic_fetch_max:
5759   case AtomicExpr::AO__opencl_atomic_fetch_min:
5760   case AtomicExpr::AO__opencl_atomic_fetch_max:
5761   case AtomicExpr::AO__atomic_min_fetch:
5762   case AtomicExpr::AO__atomic_max_fetch:
5763   case AtomicExpr::AO__atomic_fetch_min:
5764   case AtomicExpr::AO__atomic_fetch_max:
5765     Form = Arithmetic;
5766     break;
5767 
5768   case AtomicExpr::AO__c11_atomic_exchange:
5769   case AtomicExpr::AO__hip_atomic_exchange:
5770   case AtomicExpr::AO__opencl_atomic_exchange:
5771   case AtomicExpr::AO__atomic_exchange_n:
5772     Form = Xchg;
5773     break;
5774 
5775   case AtomicExpr::AO__atomic_exchange:
5776     Form = GNUXchg;
5777     break;
5778 
5779   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5780   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5781   case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5782   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5783   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5784   case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5785     Form = C11CmpXchg;
5786     break;
5787 
5788   case AtomicExpr::AO__atomic_compare_exchange:
5789   case AtomicExpr::AO__atomic_compare_exchange_n:
5790     Form = GNUCmpXchg;
5791     break;
5792   }
5793 
5794   unsigned AdjustedNumArgs = NumArgs[Form];
5795   if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init)
5796     ++AdjustedNumArgs;
5797   // Check we have the right number of arguments.
5798   if (Args.size() < AdjustedNumArgs) {
5799     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5800         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5801         << ExprRange;
5802     return ExprError();
5803   } else if (Args.size() > AdjustedNumArgs) {
5804     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5805          diag::err_typecheck_call_too_many_args)
5806         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5807         << ExprRange;
5808     return ExprError();
5809   }
5810 
5811   // Inspect the first argument of the atomic operation.
5812   Expr *Ptr = Args[0];
5813   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5814   if (ConvertedPtr.isInvalid())
5815     return ExprError();
5816 
5817   Ptr = ConvertedPtr.get();
5818   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5819   if (!pointerType) {
5820     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5821         << Ptr->getType() << Ptr->getSourceRange();
5822     return ExprError();
5823   }
5824 
5825   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5826   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5827   QualType ValType = AtomTy; // 'C'
5828   if (IsC11) {
5829     if (!AtomTy->isAtomicType()) {
5830       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5831           << Ptr->getType() << Ptr->getSourceRange();
5832       return ExprError();
5833     }
5834     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5835         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5836       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5837           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5838           << Ptr->getSourceRange();
5839       return ExprError();
5840     }
5841     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5842   } else if (Form != Load && Form != LoadCopy) {
5843     if (ValType.isConstQualified()) {
5844       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5845           << Ptr->getType() << Ptr->getSourceRange();
5846       return ExprError();
5847     }
5848   }
5849 
5850   // For an arithmetic operation, the implied arithmetic must be well-formed.
5851   if (Form == Arithmetic) {
5852     // GCC does not enforce these rules for GNU atomics, but we do to help catch
5853     // trivial type errors.
5854     auto IsAllowedValueType = [&](QualType ValType) {
5855       if (ValType->isIntegerType())
5856         return true;
5857       if (ValType->isPointerType())
5858         return true;
5859       if (!ValType->isFloatingType())
5860         return false;
5861       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5862       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5863           &Context.getTargetInfo().getLongDoubleFormat() ==
5864               &llvm::APFloat::x87DoubleExtended())
5865         return false;
5866       return true;
5867     };
5868     if (IsAddSub && !IsAllowedValueType(ValType)) {
5869       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5870           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5871       return ExprError();
5872     }
5873     if (!IsAddSub && !ValType->isIntegerType()) {
5874       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5875           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5876       return ExprError();
5877     }
5878     if (IsC11 && ValType->isPointerType() &&
5879         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5880                             diag::err_incomplete_type)) {
5881       return ExprError();
5882     }
5883   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5884     // For __atomic_*_n operations, the value type must be a scalar integral or
5885     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5886     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5887         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5888     return ExprError();
5889   }
5890 
5891   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5892       !AtomTy->isScalarType()) {
5893     // For GNU atomics, require a trivially-copyable type. This is not part of
5894     // the GNU atomics specification but we enforce it for consistency with
5895     // other atomics which generally all require a trivially-copyable type. This
5896     // is because atomics just copy bits.
5897     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5898         << Ptr->getType() << Ptr->getSourceRange();
5899     return ExprError();
5900   }
5901 
5902   switch (ValType.getObjCLifetime()) {
5903   case Qualifiers::OCL_None:
5904   case Qualifiers::OCL_ExplicitNone:
5905     // okay
5906     break;
5907 
5908   case Qualifiers::OCL_Weak:
5909   case Qualifiers::OCL_Strong:
5910   case Qualifiers::OCL_Autoreleasing:
5911     // FIXME: Can this happen? By this point, ValType should be known
5912     // to be trivially copyable.
5913     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5914         << ValType << Ptr->getSourceRange();
5915     return ExprError();
5916   }
5917 
5918   // All atomic operations have an overload which takes a pointer to a volatile
5919   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5920   // into the result or the other operands. Similarly atomic_load takes a
5921   // pointer to a const 'A'.
5922   ValType.removeLocalVolatile();
5923   ValType.removeLocalConst();
5924   QualType ResultType = ValType;
5925   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5926       Form == Init)
5927     ResultType = Context.VoidTy;
5928   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5929     ResultType = Context.BoolTy;
5930 
5931   // The type of a parameter passed 'by value'. In the GNU atomics, such
5932   // arguments are actually passed as pointers.
5933   QualType ByValType = ValType; // 'CP'
5934   bool IsPassedByAddress = false;
5935   if (!IsC11 && !IsHIP && !IsN) {
5936     ByValType = Ptr->getType();
5937     IsPassedByAddress = true;
5938   }
5939 
5940   SmallVector<Expr *, 5> APIOrderedArgs;
5941   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5942     APIOrderedArgs.push_back(Args[0]);
5943     switch (Form) {
5944     case Init:
5945     case Load:
5946       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5947       break;
5948     case LoadCopy:
5949     case Copy:
5950     case Arithmetic:
5951     case Xchg:
5952       APIOrderedArgs.push_back(Args[2]); // Val1
5953       APIOrderedArgs.push_back(Args[1]); // Order
5954       break;
5955     case GNUXchg:
5956       APIOrderedArgs.push_back(Args[2]); // Val1
5957       APIOrderedArgs.push_back(Args[3]); // Val2
5958       APIOrderedArgs.push_back(Args[1]); // Order
5959       break;
5960     case C11CmpXchg:
5961       APIOrderedArgs.push_back(Args[2]); // Val1
5962       APIOrderedArgs.push_back(Args[4]); // Val2
5963       APIOrderedArgs.push_back(Args[1]); // Order
5964       APIOrderedArgs.push_back(Args[3]); // OrderFail
5965       break;
5966     case GNUCmpXchg:
5967       APIOrderedArgs.push_back(Args[2]); // Val1
5968       APIOrderedArgs.push_back(Args[4]); // Val2
5969       APIOrderedArgs.push_back(Args[5]); // Weak
5970       APIOrderedArgs.push_back(Args[1]); // Order
5971       APIOrderedArgs.push_back(Args[3]); // OrderFail
5972       break;
5973     }
5974   } else
5975     APIOrderedArgs.append(Args.begin(), Args.end());
5976 
5977   // The first argument's non-CV pointer type is used to deduce the type of
5978   // subsequent arguments, except for:
5979   //  - weak flag (always converted to bool)
5980   //  - memory order (always converted to int)
5981   //  - scope  (always converted to int)
5982   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5983     QualType Ty;
5984     if (i < NumVals[Form] + 1) {
5985       switch (i) {
5986       case 0:
5987         // The first argument is always a pointer. It has a fixed type.
5988         // It is always dereferenced, a nullptr is undefined.
5989         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5990         // Nothing else to do: we already know all we want about this pointer.
5991         continue;
5992       case 1:
5993         // The second argument is the non-atomic operand. For arithmetic, this
5994         // is always passed by value, and for a compare_exchange it is always
5995         // passed by address. For the rest, GNU uses by-address and C11 uses
5996         // by-value.
5997         assert(Form != Load);
5998         if (Form == Arithmetic && ValType->isPointerType())
5999           Ty = Context.getPointerDiffType();
6000         else if (Form == Init || Form == Arithmetic)
6001           Ty = ValType;
6002         else if (Form == Copy || Form == Xchg) {
6003           if (IsPassedByAddress) {
6004             // The value pointer is always dereferenced, a nullptr is undefined.
6005             CheckNonNullArgument(*this, APIOrderedArgs[i],
6006                                  ExprRange.getBegin());
6007           }
6008           Ty = ByValType;
6009         } else {
6010           Expr *ValArg = APIOrderedArgs[i];
6011           // The value pointer is always dereferenced, a nullptr is undefined.
6012           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
6013           LangAS AS = LangAS::Default;
6014           // Keep address space of non-atomic pointer type.
6015           if (const PointerType *PtrTy =
6016                   ValArg->getType()->getAs<PointerType>()) {
6017             AS = PtrTy->getPointeeType().getAddressSpace();
6018           }
6019           Ty = Context.getPointerType(
6020               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
6021         }
6022         break;
6023       case 2:
6024         // The third argument to compare_exchange / GNU exchange is the desired
6025         // value, either by-value (for the C11 and *_n variant) or as a pointer.
6026         if (IsPassedByAddress)
6027           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
6028         Ty = ByValType;
6029         break;
6030       case 3:
6031         // The fourth argument to GNU compare_exchange is a 'weak' flag.
6032         Ty = Context.BoolTy;
6033         break;
6034       }
6035     } else {
6036       // The order(s) and scope are always converted to int.
6037       Ty = Context.IntTy;
6038     }
6039 
6040     InitializedEntity Entity =
6041         InitializedEntity::InitializeParameter(Context, Ty, false);
6042     ExprResult Arg = APIOrderedArgs[i];
6043     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6044     if (Arg.isInvalid())
6045       return true;
6046     APIOrderedArgs[i] = Arg.get();
6047   }
6048 
6049   // Permute the arguments into a 'consistent' order.
6050   SmallVector<Expr*, 5> SubExprs;
6051   SubExprs.push_back(Ptr);
6052   switch (Form) {
6053   case Init:
6054     // Note, AtomicExpr::getVal1() has a special case for this atomic.
6055     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6056     break;
6057   case Load:
6058     SubExprs.push_back(APIOrderedArgs[1]); // Order
6059     break;
6060   case LoadCopy:
6061   case Copy:
6062   case Arithmetic:
6063   case Xchg:
6064     SubExprs.push_back(APIOrderedArgs[2]); // Order
6065     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6066     break;
6067   case GNUXchg:
6068     // Note, AtomicExpr::getVal2() has a special case for this atomic.
6069     SubExprs.push_back(APIOrderedArgs[3]); // Order
6070     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6071     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6072     break;
6073   case C11CmpXchg:
6074     SubExprs.push_back(APIOrderedArgs[3]); // Order
6075     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6076     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
6077     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6078     break;
6079   case GNUCmpXchg:
6080     SubExprs.push_back(APIOrderedArgs[4]); // Order
6081     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6082     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
6083     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6084     SubExprs.push_back(APIOrderedArgs[3]); // Weak
6085     break;
6086   }
6087 
6088   if (SubExprs.size() >= 2 && Form != Init) {
6089     if (Optional<llvm::APSInt> Result =
6090             SubExprs[1]->getIntegerConstantExpr(Context))
6091       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
6092         Diag(SubExprs[1]->getBeginLoc(),
6093              diag::warn_atomic_op_has_invalid_memory_order)
6094             << SubExprs[1]->getSourceRange();
6095   }
6096 
6097   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
6098     auto *Scope = Args[Args.size() - 1];
6099     if (Optional<llvm::APSInt> Result =
6100             Scope->getIntegerConstantExpr(Context)) {
6101       if (!ScopeModel->isValid(Result->getZExtValue()))
6102         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
6103             << Scope->getSourceRange();
6104     }
6105     SubExprs.push_back(Scope);
6106   }
6107 
6108   AtomicExpr *AE = new (Context)
6109       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
6110 
6111   if ((Op == AtomicExpr::AO__c11_atomic_load ||
6112        Op == AtomicExpr::AO__c11_atomic_store ||
6113        Op == AtomicExpr::AO__opencl_atomic_load ||
6114        Op == AtomicExpr::AO__hip_atomic_load ||
6115        Op == AtomicExpr::AO__opencl_atomic_store ||
6116        Op == AtomicExpr::AO__hip_atomic_store) &&
6117       Context.AtomicUsesUnsupportedLibcall(AE))
6118     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
6119         << ((Op == AtomicExpr::AO__c11_atomic_load ||
6120              Op == AtomicExpr::AO__opencl_atomic_load ||
6121              Op == AtomicExpr::AO__hip_atomic_load)
6122                 ? 0
6123                 : 1);
6124 
6125   if (ValType->isBitIntType()) {
6126     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
6127     return ExprError();
6128   }
6129 
6130   return AE;
6131 }
6132 
6133 /// checkBuiltinArgument - Given a call to a builtin function, perform
6134 /// normal type-checking on the given argument, updating the call in
6135 /// place.  This is useful when a builtin function requires custom
6136 /// type-checking for some of its arguments but not necessarily all of
6137 /// them.
6138 ///
6139 /// Returns true on error.
6140 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
6141   FunctionDecl *Fn = E->getDirectCallee();
6142   assert(Fn && "builtin call without direct callee!");
6143 
6144   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
6145   InitializedEntity Entity =
6146     InitializedEntity::InitializeParameter(S.Context, Param);
6147 
6148   ExprResult Arg = E->getArg(0);
6149   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
6150   if (Arg.isInvalid())
6151     return true;
6152 
6153   E->setArg(ArgIndex, Arg.get());
6154   return false;
6155 }
6156 
6157 /// We have a call to a function like __sync_fetch_and_add, which is an
6158 /// overloaded function based on the pointer type of its first argument.
6159 /// The main BuildCallExpr routines have already promoted the types of
6160 /// arguments because all of these calls are prototyped as void(...).
6161 ///
6162 /// This function goes through and does final semantic checking for these
6163 /// builtins, as well as generating any warnings.
6164 ExprResult
6165 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
6166   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
6167   Expr *Callee = TheCall->getCallee();
6168   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
6169   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6170 
6171   // Ensure that we have at least one argument to do type inference from.
6172   if (TheCall->getNumArgs() < 1) {
6173     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6174         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
6175     return ExprError();
6176   }
6177 
6178   // Inspect the first argument of the atomic builtin.  This should always be
6179   // a pointer type, whose element is an integral scalar or pointer type.
6180   // Because it is a pointer type, we don't have to worry about any implicit
6181   // casts here.
6182   // FIXME: We don't allow floating point scalars as input.
6183   Expr *FirstArg = TheCall->getArg(0);
6184   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
6185   if (FirstArgResult.isInvalid())
6186     return ExprError();
6187   FirstArg = FirstArgResult.get();
6188   TheCall->setArg(0, FirstArg);
6189 
6190   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
6191   if (!pointerType) {
6192     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
6193         << FirstArg->getType() << FirstArg->getSourceRange();
6194     return ExprError();
6195   }
6196 
6197   QualType ValType = pointerType->getPointeeType();
6198   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6199       !ValType->isBlockPointerType()) {
6200     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
6201         << FirstArg->getType() << FirstArg->getSourceRange();
6202     return ExprError();
6203   }
6204 
6205   if (ValType.isConstQualified()) {
6206     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
6207         << FirstArg->getType() << FirstArg->getSourceRange();
6208     return ExprError();
6209   }
6210 
6211   switch (ValType.getObjCLifetime()) {
6212   case Qualifiers::OCL_None:
6213   case Qualifiers::OCL_ExplicitNone:
6214     // okay
6215     break;
6216 
6217   case Qualifiers::OCL_Weak:
6218   case Qualifiers::OCL_Strong:
6219   case Qualifiers::OCL_Autoreleasing:
6220     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
6221         << ValType << FirstArg->getSourceRange();
6222     return ExprError();
6223   }
6224 
6225   // Strip any qualifiers off ValType.
6226   ValType = ValType.getUnqualifiedType();
6227 
6228   // The majority of builtins return a value, but a few have special return
6229   // types, so allow them to override appropriately below.
6230   QualType ResultType = ValType;
6231 
6232   // We need to figure out which concrete builtin this maps onto.  For example,
6233   // __sync_fetch_and_add with a 2 byte object turns into
6234   // __sync_fetch_and_add_2.
6235 #define BUILTIN_ROW(x) \
6236   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
6237     Builtin::BI##x##_8, Builtin::BI##x##_16 }
6238 
6239   static const unsigned BuiltinIndices[][5] = {
6240     BUILTIN_ROW(__sync_fetch_and_add),
6241     BUILTIN_ROW(__sync_fetch_and_sub),
6242     BUILTIN_ROW(__sync_fetch_and_or),
6243     BUILTIN_ROW(__sync_fetch_and_and),
6244     BUILTIN_ROW(__sync_fetch_and_xor),
6245     BUILTIN_ROW(__sync_fetch_and_nand),
6246 
6247     BUILTIN_ROW(__sync_add_and_fetch),
6248     BUILTIN_ROW(__sync_sub_and_fetch),
6249     BUILTIN_ROW(__sync_and_and_fetch),
6250     BUILTIN_ROW(__sync_or_and_fetch),
6251     BUILTIN_ROW(__sync_xor_and_fetch),
6252     BUILTIN_ROW(__sync_nand_and_fetch),
6253 
6254     BUILTIN_ROW(__sync_val_compare_and_swap),
6255     BUILTIN_ROW(__sync_bool_compare_and_swap),
6256     BUILTIN_ROW(__sync_lock_test_and_set),
6257     BUILTIN_ROW(__sync_lock_release),
6258     BUILTIN_ROW(__sync_swap)
6259   };
6260 #undef BUILTIN_ROW
6261 
6262   // Determine the index of the size.
6263   unsigned SizeIndex;
6264   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
6265   case 1: SizeIndex = 0; break;
6266   case 2: SizeIndex = 1; break;
6267   case 4: SizeIndex = 2; break;
6268   case 8: SizeIndex = 3; break;
6269   case 16: SizeIndex = 4; break;
6270   default:
6271     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
6272         << FirstArg->getType() << FirstArg->getSourceRange();
6273     return ExprError();
6274   }
6275 
6276   // Each of these builtins has one pointer argument, followed by some number of
6277   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
6278   // that we ignore.  Find out which row of BuiltinIndices to read from as well
6279   // as the number of fixed args.
6280   unsigned BuiltinID = FDecl->getBuiltinID();
6281   unsigned BuiltinIndex, NumFixed = 1;
6282   bool WarnAboutSemanticsChange = false;
6283   switch (BuiltinID) {
6284   default: llvm_unreachable("Unknown overloaded atomic builtin!");
6285   case Builtin::BI__sync_fetch_and_add:
6286   case Builtin::BI__sync_fetch_and_add_1:
6287   case Builtin::BI__sync_fetch_and_add_2:
6288   case Builtin::BI__sync_fetch_and_add_4:
6289   case Builtin::BI__sync_fetch_and_add_8:
6290   case Builtin::BI__sync_fetch_and_add_16:
6291     BuiltinIndex = 0;
6292     break;
6293 
6294   case Builtin::BI__sync_fetch_and_sub:
6295   case Builtin::BI__sync_fetch_and_sub_1:
6296   case Builtin::BI__sync_fetch_and_sub_2:
6297   case Builtin::BI__sync_fetch_and_sub_4:
6298   case Builtin::BI__sync_fetch_and_sub_8:
6299   case Builtin::BI__sync_fetch_and_sub_16:
6300     BuiltinIndex = 1;
6301     break;
6302 
6303   case Builtin::BI__sync_fetch_and_or:
6304   case Builtin::BI__sync_fetch_and_or_1:
6305   case Builtin::BI__sync_fetch_and_or_2:
6306   case Builtin::BI__sync_fetch_and_or_4:
6307   case Builtin::BI__sync_fetch_and_or_8:
6308   case Builtin::BI__sync_fetch_and_or_16:
6309     BuiltinIndex = 2;
6310     break;
6311 
6312   case Builtin::BI__sync_fetch_and_and:
6313   case Builtin::BI__sync_fetch_and_and_1:
6314   case Builtin::BI__sync_fetch_and_and_2:
6315   case Builtin::BI__sync_fetch_and_and_4:
6316   case Builtin::BI__sync_fetch_and_and_8:
6317   case Builtin::BI__sync_fetch_and_and_16:
6318     BuiltinIndex = 3;
6319     break;
6320 
6321   case Builtin::BI__sync_fetch_and_xor:
6322   case Builtin::BI__sync_fetch_and_xor_1:
6323   case Builtin::BI__sync_fetch_and_xor_2:
6324   case Builtin::BI__sync_fetch_and_xor_4:
6325   case Builtin::BI__sync_fetch_and_xor_8:
6326   case Builtin::BI__sync_fetch_and_xor_16:
6327     BuiltinIndex = 4;
6328     break;
6329 
6330   case Builtin::BI__sync_fetch_and_nand:
6331   case Builtin::BI__sync_fetch_and_nand_1:
6332   case Builtin::BI__sync_fetch_and_nand_2:
6333   case Builtin::BI__sync_fetch_and_nand_4:
6334   case Builtin::BI__sync_fetch_and_nand_8:
6335   case Builtin::BI__sync_fetch_and_nand_16:
6336     BuiltinIndex = 5;
6337     WarnAboutSemanticsChange = true;
6338     break;
6339 
6340   case Builtin::BI__sync_add_and_fetch:
6341   case Builtin::BI__sync_add_and_fetch_1:
6342   case Builtin::BI__sync_add_and_fetch_2:
6343   case Builtin::BI__sync_add_and_fetch_4:
6344   case Builtin::BI__sync_add_and_fetch_8:
6345   case Builtin::BI__sync_add_and_fetch_16:
6346     BuiltinIndex = 6;
6347     break;
6348 
6349   case Builtin::BI__sync_sub_and_fetch:
6350   case Builtin::BI__sync_sub_and_fetch_1:
6351   case Builtin::BI__sync_sub_and_fetch_2:
6352   case Builtin::BI__sync_sub_and_fetch_4:
6353   case Builtin::BI__sync_sub_and_fetch_8:
6354   case Builtin::BI__sync_sub_and_fetch_16:
6355     BuiltinIndex = 7;
6356     break;
6357 
6358   case Builtin::BI__sync_and_and_fetch:
6359   case Builtin::BI__sync_and_and_fetch_1:
6360   case Builtin::BI__sync_and_and_fetch_2:
6361   case Builtin::BI__sync_and_and_fetch_4:
6362   case Builtin::BI__sync_and_and_fetch_8:
6363   case Builtin::BI__sync_and_and_fetch_16:
6364     BuiltinIndex = 8;
6365     break;
6366 
6367   case Builtin::BI__sync_or_and_fetch:
6368   case Builtin::BI__sync_or_and_fetch_1:
6369   case Builtin::BI__sync_or_and_fetch_2:
6370   case Builtin::BI__sync_or_and_fetch_4:
6371   case Builtin::BI__sync_or_and_fetch_8:
6372   case Builtin::BI__sync_or_and_fetch_16:
6373     BuiltinIndex = 9;
6374     break;
6375 
6376   case Builtin::BI__sync_xor_and_fetch:
6377   case Builtin::BI__sync_xor_and_fetch_1:
6378   case Builtin::BI__sync_xor_and_fetch_2:
6379   case Builtin::BI__sync_xor_and_fetch_4:
6380   case Builtin::BI__sync_xor_and_fetch_8:
6381   case Builtin::BI__sync_xor_and_fetch_16:
6382     BuiltinIndex = 10;
6383     break;
6384 
6385   case Builtin::BI__sync_nand_and_fetch:
6386   case Builtin::BI__sync_nand_and_fetch_1:
6387   case Builtin::BI__sync_nand_and_fetch_2:
6388   case Builtin::BI__sync_nand_and_fetch_4:
6389   case Builtin::BI__sync_nand_and_fetch_8:
6390   case Builtin::BI__sync_nand_and_fetch_16:
6391     BuiltinIndex = 11;
6392     WarnAboutSemanticsChange = true;
6393     break;
6394 
6395   case Builtin::BI__sync_val_compare_and_swap:
6396   case Builtin::BI__sync_val_compare_and_swap_1:
6397   case Builtin::BI__sync_val_compare_and_swap_2:
6398   case Builtin::BI__sync_val_compare_and_swap_4:
6399   case Builtin::BI__sync_val_compare_and_swap_8:
6400   case Builtin::BI__sync_val_compare_and_swap_16:
6401     BuiltinIndex = 12;
6402     NumFixed = 2;
6403     break;
6404 
6405   case Builtin::BI__sync_bool_compare_and_swap:
6406   case Builtin::BI__sync_bool_compare_and_swap_1:
6407   case Builtin::BI__sync_bool_compare_and_swap_2:
6408   case Builtin::BI__sync_bool_compare_and_swap_4:
6409   case Builtin::BI__sync_bool_compare_and_swap_8:
6410   case Builtin::BI__sync_bool_compare_and_swap_16:
6411     BuiltinIndex = 13;
6412     NumFixed = 2;
6413     ResultType = Context.BoolTy;
6414     break;
6415 
6416   case Builtin::BI__sync_lock_test_and_set:
6417   case Builtin::BI__sync_lock_test_and_set_1:
6418   case Builtin::BI__sync_lock_test_and_set_2:
6419   case Builtin::BI__sync_lock_test_and_set_4:
6420   case Builtin::BI__sync_lock_test_and_set_8:
6421   case Builtin::BI__sync_lock_test_and_set_16:
6422     BuiltinIndex = 14;
6423     break;
6424 
6425   case Builtin::BI__sync_lock_release:
6426   case Builtin::BI__sync_lock_release_1:
6427   case Builtin::BI__sync_lock_release_2:
6428   case Builtin::BI__sync_lock_release_4:
6429   case Builtin::BI__sync_lock_release_8:
6430   case Builtin::BI__sync_lock_release_16:
6431     BuiltinIndex = 15;
6432     NumFixed = 0;
6433     ResultType = Context.VoidTy;
6434     break;
6435 
6436   case Builtin::BI__sync_swap:
6437   case Builtin::BI__sync_swap_1:
6438   case Builtin::BI__sync_swap_2:
6439   case Builtin::BI__sync_swap_4:
6440   case Builtin::BI__sync_swap_8:
6441   case Builtin::BI__sync_swap_16:
6442     BuiltinIndex = 16;
6443     break;
6444   }
6445 
6446   // Now that we know how many fixed arguments we expect, first check that we
6447   // have at least that many.
6448   if (TheCall->getNumArgs() < 1+NumFixed) {
6449     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6450         << 0 << 1 + NumFixed << TheCall->getNumArgs()
6451         << Callee->getSourceRange();
6452     return ExprError();
6453   }
6454 
6455   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6456       << Callee->getSourceRange();
6457 
6458   if (WarnAboutSemanticsChange) {
6459     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6460         << Callee->getSourceRange();
6461   }
6462 
6463   // Get the decl for the concrete builtin from this, we can tell what the
6464   // concrete integer type we should convert to is.
6465   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6466   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6467   FunctionDecl *NewBuiltinDecl;
6468   if (NewBuiltinID == BuiltinID)
6469     NewBuiltinDecl = FDecl;
6470   else {
6471     // Perform builtin lookup to avoid redeclaring it.
6472     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6473     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6474     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6475     assert(Res.getFoundDecl());
6476     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6477     if (!NewBuiltinDecl)
6478       return ExprError();
6479   }
6480 
6481   // The first argument --- the pointer --- has a fixed type; we
6482   // deduce the types of the rest of the arguments accordingly.  Walk
6483   // the remaining arguments, converting them to the deduced value type.
6484   for (unsigned i = 0; i != NumFixed; ++i) {
6485     ExprResult Arg = TheCall->getArg(i+1);
6486 
6487     // GCC does an implicit conversion to the pointer or integer ValType.  This
6488     // can fail in some cases (1i -> int**), check for this error case now.
6489     // Initialize the argument.
6490     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6491                                                    ValType, /*consume*/ false);
6492     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6493     if (Arg.isInvalid())
6494       return ExprError();
6495 
6496     // Okay, we have something that *can* be converted to the right type.  Check
6497     // to see if there is a potentially weird extension going on here.  This can
6498     // happen when you do an atomic operation on something like an char* and
6499     // pass in 42.  The 42 gets converted to char.  This is even more strange
6500     // for things like 45.123 -> char, etc.
6501     // FIXME: Do this check.
6502     TheCall->setArg(i+1, Arg.get());
6503   }
6504 
6505   // Create a new DeclRefExpr to refer to the new decl.
6506   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6507       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6508       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6509       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6510 
6511   // Set the callee in the CallExpr.
6512   // FIXME: This loses syntactic information.
6513   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6514   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6515                                               CK_BuiltinFnToFnPtr);
6516   TheCall->setCallee(PromotedCall.get());
6517 
6518   // Change the result type of the call to match the original value type. This
6519   // is arbitrary, but the codegen for these builtins ins design to handle it
6520   // gracefully.
6521   TheCall->setType(ResultType);
6522 
6523   // Prohibit problematic uses of bit-precise integer types with atomic
6524   // builtins. The arguments would have already been converted to the first
6525   // argument's type, so only need to check the first argument.
6526   const auto *BitIntValType = ValType->getAs<BitIntType>();
6527   if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
6528     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6529     return ExprError();
6530   }
6531 
6532   return TheCallResult;
6533 }
6534 
6535 /// SemaBuiltinNontemporalOverloaded - We have a call to
6536 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6537 /// overloaded function based on the pointer type of its last argument.
6538 ///
6539 /// This function goes through and does final semantic checking for these
6540 /// builtins.
6541 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6542   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6543   DeclRefExpr *DRE =
6544       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6545   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6546   unsigned BuiltinID = FDecl->getBuiltinID();
6547   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6548           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6549          "Unexpected nontemporal load/store builtin!");
6550   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6551   unsigned numArgs = isStore ? 2 : 1;
6552 
6553   // Ensure that we have the proper number of arguments.
6554   if (checkArgCount(*this, TheCall, numArgs))
6555     return ExprError();
6556 
6557   // Inspect the last argument of the nontemporal builtin.  This should always
6558   // be a pointer type, from which we imply the type of the memory access.
6559   // Because it is a pointer type, we don't have to worry about any implicit
6560   // casts here.
6561   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6562   ExprResult PointerArgResult =
6563       DefaultFunctionArrayLvalueConversion(PointerArg);
6564 
6565   if (PointerArgResult.isInvalid())
6566     return ExprError();
6567   PointerArg = PointerArgResult.get();
6568   TheCall->setArg(numArgs - 1, PointerArg);
6569 
6570   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6571   if (!pointerType) {
6572     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6573         << PointerArg->getType() << PointerArg->getSourceRange();
6574     return ExprError();
6575   }
6576 
6577   QualType ValType = pointerType->getPointeeType();
6578 
6579   // Strip any qualifiers off ValType.
6580   ValType = ValType.getUnqualifiedType();
6581   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6582       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6583       !ValType->isVectorType()) {
6584     Diag(DRE->getBeginLoc(),
6585          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6586         << PointerArg->getType() << PointerArg->getSourceRange();
6587     return ExprError();
6588   }
6589 
6590   if (!isStore) {
6591     TheCall->setType(ValType);
6592     return TheCallResult;
6593   }
6594 
6595   ExprResult ValArg = TheCall->getArg(0);
6596   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6597       Context, ValType, /*consume*/ false);
6598   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6599   if (ValArg.isInvalid())
6600     return ExprError();
6601 
6602   TheCall->setArg(0, ValArg.get());
6603   TheCall->setType(Context.VoidTy);
6604   return TheCallResult;
6605 }
6606 
6607 /// CheckObjCString - Checks that the argument to the builtin
6608 /// CFString constructor is correct
6609 /// Note: It might also make sense to do the UTF-16 conversion here (would
6610 /// simplify the backend).
6611 bool Sema::CheckObjCString(Expr *Arg) {
6612   Arg = Arg->IgnoreParenCasts();
6613   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6614 
6615   if (!Literal || !Literal->isAscii()) {
6616     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6617         << Arg->getSourceRange();
6618     return true;
6619   }
6620 
6621   if (Literal->containsNonAsciiOrNull()) {
6622     StringRef String = Literal->getString();
6623     unsigned NumBytes = String.size();
6624     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6625     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6626     llvm::UTF16 *ToPtr = &ToBuf[0];
6627 
6628     llvm::ConversionResult Result =
6629         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6630                                  ToPtr + NumBytes, llvm::strictConversion);
6631     // Check for conversion failure.
6632     if (Result != llvm::conversionOK)
6633       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6634           << Arg->getSourceRange();
6635   }
6636   return false;
6637 }
6638 
6639 /// CheckObjCString - Checks that the format string argument to the os_log()
6640 /// and os_trace() functions is correct, and converts it to const char *.
6641 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6642   Arg = Arg->IgnoreParenCasts();
6643   auto *Literal = dyn_cast<StringLiteral>(Arg);
6644   if (!Literal) {
6645     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6646       Literal = ObjcLiteral->getString();
6647     }
6648   }
6649 
6650   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6651     return ExprError(
6652         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6653         << Arg->getSourceRange());
6654   }
6655 
6656   ExprResult Result(Literal);
6657   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6658   InitializedEntity Entity =
6659       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6660   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6661   return Result;
6662 }
6663 
6664 /// Check that the user is calling the appropriate va_start builtin for the
6665 /// target and calling convention.
6666 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6667   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6668   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6669   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6670                     TT.getArch() == llvm::Triple::aarch64_32);
6671   bool IsWindows = TT.isOSWindows();
6672   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6673   if (IsX64 || IsAArch64) {
6674     CallingConv CC = CC_C;
6675     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6676       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6677     if (IsMSVAStart) {
6678       // Don't allow this in System V ABI functions.
6679       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6680         return S.Diag(Fn->getBeginLoc(),
6681                       diag::err_ms_va_start_used_in_sysv_function);
6682     } else {
6683       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6684       // On x64 Windows, don't allow this in System V ABI functions.
6685       // (Yes, that means there's no corresponding way to support variadic
6686       // System V ABI functions on Windows.)
6687       if ((IsWindows && CC == CC_X86_64SysV) ||
6688           (!IsWindows && CC == CC_Win64))
6689         return S.Diag(Fn->getBeginLoc(),
6690                       diag::err_va_start_used_in_wrong_abi_function)
6691                << !IsWindows;
6692     }
6693     return false;
6694   }
6695 
6696   if (IsMSVAStart)
6697     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6698   return false;
6699 }
6700 
6701 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6702                                              ParmVarDecl **LastParam = nullptr) {
6703   // Determine whether the current function, block, or obj-c method is variadic
6704   // and get its parameter list.
6705   bool IsVariadic = false;
6706   ArrayRef<ParmVarDecl *> Params;
6707   DeclContext *Caller = S.CurContext;
6708   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6709     IsVariadic = Block->isVariadic();
6710     Params = Block->parameters();
6711   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6712     IsVariadic = FD->isVariadic();
6713     Params = FD->parameters();
6714   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6715     IsVariadic = MD->isVariadic();
6716     // FIXME: This isn't correct for methods (results in bogus warning).
6717     Params = MD->parameters();
6718   } else if (isa<CapturedDecl>(Caller)) {
6719     // We don't support va_start in a CapturedDecl.
6720     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6721     return true;
6722   } else {
6723     // This must be some other declcontext that parses exprs.
6724     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6725     return true;
6726   }
6727 
6728   if (!IsVariadic) {
6729     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6730     return true;
6731   }
6732 
6733   if (LastParam)
6734     *LastParam = Params.empty() ? nullptr : Params.back();
6735 
6736   return false;
6737 }
6738 
6739 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6740 /// for validity.  Emit an error and return true on failure; return false
6741 /// on success.
6742 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6743   Expr *Fn = TheCall->getCallee();
6744 
6745   if (checkVAStartABI(*this, BuiltinID, Fn))
6746     return true;
6747 
6748   if (checkArgCount(*this, TheCall, 2))
6749     return true;
6750 
6751   // Type-check the first argument normally.
6752   if (checkBuiltinArgument(*this, TheCall, 0))
6753     return true;
6754 
6755   // Check that the current function is variadic, and get its last parameter.
6756   ParmVarDecl *LastParam;
6757   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6758     return true;
6759 
6760   // Verify that the second argument to the builtin is the last argument of the
6761   // current function or method.
6762   bool SecondArgIsLastNamedArgument = false;
6763   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6764 
6765   // These are valid if SecondArgIsLastNamedArgument is false after the next
6766   // block.
6767   QualType Type;
6768   SourceLocation ParamLoc;
6769   bool IsCRegister = false;
6770 
6771   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6772     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6773       SecondArgIsLastNamedArgument = PV == LastParam;
6774 
6775       Type = PV->getType();
6776       ParamLoc = PV->getLocation();
6777       IsCRegister =
6778           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6779     }
6780   }
6781 
6782   if (!SecondArgIsLastNamedArgument)
6783     Diag(TheCall->getArg(1)->getBeginLoc(),
6784          diag::warn_second_arg_of_va_start_not_last_named_param);
6785   else if (IsCRegister || Type->isReferenceType() ||
6786            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6787              // Promotable integers are UB, but enumerations need a bit of
6788              // extra checking to see what their promotable type actually is.
6789              if (!Type->isPromotableIntegerType())
6790                return false;
6791              if (!Type->isEnumeralType())
6792                return true;
6793              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6794              return !(ED &&
6795                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6796            }()) {
6797     unsigned Reason = 0;
6798     if (Type->isReferenceType())  Reason = 1;
6799     else if (IsCRegister)         Reason = 2;
6800     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6801     Diag(ParamLoc, diag::note_parameter_type) << Type;
6802   }
6803 
6804   TheCall->setType(Context.VoidTy);
6805   return false;
6806 }
6807 
6808 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6809   auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6810     const LangOptions &LO = getLangOpts();
6811 
6812     if (LO.CPlusPlus)
6813       return Arg->getType()
6814                  .getCanonicalType()
6815                  .getTypePtr()
6816                  ->getPointeeType()
6817                  .withoutLocalFastQualifiers() == Context.CharTy;
6818 
6819     // In C, allow aliasing through `char *`, this is required for AArch64 at
6820     // least.
6821     return true;
6822   };
6823 
6824   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6825   //                 const char *named_addr);
6826 
6827   Expr *Func = Call->getCallee();
6828 
6829   if (Call->getNumArgs() < 3)
6830     return Diag(Call->getEndLoc(),
6831                 diag::err_typecheck_call_too_few_args_at_least)
6832            << 0 /*function call*/ << 3 << Call->getNumArgs();
6833 
6834   // Type-check the first argument normally.
6835   if (checkBuiltinArgument(*this, Call, 0))
6836     return true;
6837 
6838   // Check that the current function is variadic.
6839   if (checkVAStartIsInVariadicFunction(*this, Func))
6840     return true;
6841 
6842   // __va_start on Windows does not validate the parameter qualifiers
6843 
6844   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6845   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6846 
6847   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6848   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6849 
6850   const QualType &ConstCharPtrTy =
6851       Context.getPointerType(Context.CharTy.withConst());
6852   if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6853     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6854         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6855         << 0                                      /* qualifier difference */
6856         << 3                                      /* parameter mismatch */
6857         << 2 << Arg1->getType() << ConstCharPtrTy;
6858 
6859   const QualType SizeTy = Context.getSizeType();
6860   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6861     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6862         << Arg2->getType() << SizeTy << 1 /* different class */
6863         << 0                              /* qualifier difference */
6864         << 3                              /* parameter mismatch */
6865         << 3 << Arg2->getType() << SizeTy;
6866 
6867   return false;
6868 }
6869 
6870 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6871 /// friends.  This is declared to take (...), so we have to check everything.
6872 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6873   if (checkArgCount(*this, TheCall, 2))
6874     return true;
6875 
6876   ExprResult OrigArg0 = TheCall->getArg(0);
6877   ExprResult OrigArg1 = TheCall->getArg(1);
6878 
6879   // Do standard promotions between the two arguments, returning their common
6880   // type.
6881   QualType Res = UsualArithmeticConversions(
6882       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6883   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6884     return true;
6885 
6886   // Make sure any conversions are pushed back into the call; this is
6887   // type safe since unordered compare builtins are declared as "_Bool
6888   // foo(...)".
6889   TheCall->setArg(0, OrigArg0.get());
6890   TheCall->setArg(1, OrigArg1.get());
6891 
6892   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6893     return false;
6894 
6895   // If the common type isn't a real floating type, then the arguments were
6896   // invalid for this operation.
6897   if (Res.isNull() || !Res->isRealFloatingType())
6898     return Diag(OrigArg0.get()->getBeginLoc(),
6899                 diag::err_typecheck_call_invalid_ordered_compare)
6900            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6901            << SourceRange(OrigArg0.get()->getBeginLoc(),
6902                           OrigArg1.get()->getEndLoc());
6903 
6904   return false;
6905 }
6906 
6907 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6908 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6909 /// to check everything. We expect the last argument to be a floating point
6910 /// value.
6911 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6912   if (checkArgCount(*this, TheCall, NumArgs))
6913     return true;
6914 
6915   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6916   // on all preceding parameters just being int.  Try all of those.
6917   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6918     Expr *Arg = TheCall->getArg(i);
6919 
6920     if (Arg->isTypeDependent())
6921       return false;
6922 
6923     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6924 
6925     if (Res.isInvalid())
6926       return true;
6927     TheCall->setArg(i, Res.get());
6928   }
6929 
6930   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6931 
6932   if (OrigArg->isTypeDependent())
6933     return false;
6934 
6935   // Usual Unary Conversions will convert half to float, which we want for
6936   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6937   // type how it is, but do normal L->Rvalue conversions.
6938   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6939     OrigArg = UsualUnaryConversions(OrigArg).get();
6940   else
6941     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6942   TheCall->setArg(NumArgs - 1, OrigArg);
6943 
6944   // This operation requires a non-_Complex floating-point number.
6945   if (!OrigArg->getType()->isRealFloatingType())
6946     return Diag(OrigArg->getBeginLoc(),
6947                 diag::err_typecheck_call_invalid_unary_fp)
6948            << OrigArg->getType() << OrigArg->getSourceRange();
6949 
6950   return false;
6951 }
6952 
6953 /// Perform semantic analysis for a call to __builtin_complex.
6954 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6955   if (checkArgCount(*this, TheCall, 2))
6956     return true;
6957 
6958   bool Dependent = false;
6959   for (unsigned I = 0; I != 2; ++I) {
6960     Expr *Arg = TheCall->getArg(I);
6961     QualType T = Arg->getType();
6962     if (T->isDependentType()) {
6963       Dependent = true;
6964       continue;
6965     }
6966 
6967     // Despite supporting _Complex int, GCC requires a real floating point type
6968     // for the operands of __builtin_complex.
6969     if (!T->isRealFloatingType()) {
6970       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6971              << Arg->getType() << Arg->getSourceRange();
6972     }
6973 
6974     ExprResult Converted = DefaultLvalueConversion(Arg);
6975     if (Converted.isInvalid())
6976       return true;
6977     TheCall->setArg(I, Converted.get());
6978   }
6979 
6980   if (Dependent) {
6981     TheCall->setType(Context.DependentTy);
6982     return false;
6983   }
6984 
6985   Expr *Real = TheCall->getArg(0);
6986   Expr *Imag = TheCall->getArg(1);
6987   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6988     return Diag(Real->getBeginLoc(),
6989                 diag::err_typecheck_call_different_arg_types)
6990            << Real->getType() << Imag->getType()
6991            << Real->getSourceRange() << Imag->getSourceRange();
6992   }
6993 
6994   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6995   // don't allow this builtin to form those types either.
6996   // FIXME: Should we allow these types?
6997   if (Real->getType()->isFloat16Type())
6998     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6999            << "_Float16";
7000   if (Real->getType()->isHalfType())
7001     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
7002            << "half";
7003 
7004   TheCall->setType(Context.getComplexType(Real->getType()));
7005   return false;
7006 }
7007 
7008 // Customized Sema Checking for VSX builtins that have the following signature:
7009 // vector [...] builtinName(vector [...], vector [...], const int);
7010 // Which takes the same type of vectors (any legal vector type) for the first
7011 // two arguments and takes compile time constant for the third argument.
7012 // Example builtins are :
7013 // vector double vec_xxpermdi(vector double, vector double, int);
7014 // vector short vec_xxsldwi(vector short, vector short, int);
7015 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
7016   unsigned ExpectedNumArgs = 3;
7017   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
7018     return true;
7019 
7020   // Check the third argument is a compile time constant
7021   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
7022     return Diag(TheCall->getBeginLoc(),
7023                 diag::err_vsx_builtin_nonconstant_argument)
7024            << 3 /* argument index */ << TheCall->getDirectCallee()
7025            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
7026                           TheCall->getArg(2)->getEndLoc());
7027 
7028   QualType Arg1Ty = TheCall->getArg(0)->getType();
7029   QualType Arg2Ty = TheCall->getArg(1)->getType();
7030 
7031   // Check the type of argument 1 and argument 2 are vectors.
7032   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
7033   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
7034       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
7035     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
7036            << TheCall->getDirectCallee()
7037            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7038                           TheCall->getArg(1)->getEndLoc());
7039   }
7040 
7041   // Check the first two arguments are the same type.
7042   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
7043     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
7044            << TheCall->getDirectCallee()
7045            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7046                           TheCall->getArg(1)->getEndLoc());
7047   }
7048 
7049   // When default clang type checking is turned off and the customized type
7050   // checking is used, the returning type of the function must be explicitly
7051   // set. Otherwise it is _Bool by default.
7052   TheCall->setType(Arg1Ty);
7053 
7054   return false;
7055 }
7056 
7057 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
7058 // This is declared to take (...), so we have to check everything.
7059 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
7060   if (TheCall->getNumArgs() < 2)
7061     return ExprError(Diag(TheCall->getEndLoc(),
7062                           diag::err_typecheck_call_too_few_args_at_least)
7063                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
7064                      << TheCall->getSourceRange());
7065 
7066   // Determine which of the following types of shufflevector we're checking:
7067   // 1) unary, vector mask: (lhs, mask)
7068   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
7069   QualType resType = TheCall->getArg(0)->getType();
7070   unsigned numElements = 0;
7071 
7072   if (!TheCall->getArg(0)->isTypeDependent() &&
7073       !TheCall->getArg(1)->isTypeDependent()) {
7074     QualType LHSType = TheCall->getArg(0)->getType();
7075     QualType RHSType = TheCall->getArg(1)->getType();
7076 
7077     if (!LHSType->isVectorType() || !RHSType->isVectorType())
7078       return ExprError(
7079           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
7080           << TheCall->getDirectCallee()
7081           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7082                          TheCall->getArg(1)->getEndLoc()));
7083 
7084     numElements = LHSType->castAs<VectorType>()->getNumElements();
7085     unsigned numResElements = TheCall->getNumArgs() - 2;
7086 
7087     // Check to see if we have a call with 2 vector arguments, the unary shuffle
7088     // with mask.  If so, verify that RHS is an integer vector type with the
7089     // same number of elts as lhs.
7090     if (TheCall->getNumArgs() == 2) {
7091       if (!RHSType->hasIntegerRepresentation() ||
7092           RHSType->castAs<VectorType>()->getNumElements() != numElements)
7093         return ExprError(Diag(TheCall->getBeginLoc(),
7094                               diag::err_vec_builtin_incompatible_vector)
7095                          << TheCall->getDirectCallee()
7096                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
7097                                         TheCall->getArg(1)->getEndLoc()));
7098     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
7099       return ExprError(Diag(TheCall->getBeginLoc(),
7100                             diag::err_vec_builtin_incompatible_vector)
7101                        << TheCall->getDirectCallee()
7102                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7103                                       TheCall->getArg(1)->getEndLoc()));
7104     } else if (numElements != numResElements) {
7105       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
7106       resType = Context.getVectorType(eltType, numResElements,
7107                                       VectorType::GenericVector);
7108     }
7109   }
7110 
7111   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
7112     if (TheCall->getArg(i)->isTypeDependent() ||
7113         TheCall->getArg(i)->isValueDependent())
7114       continue;
7115 
7116     Optional<llvm::APSInt> Result;
7117     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
7118       return ExprError(Diag(TheCall->getBeginLoc(),
7119                             diag::err_shufflevector_nonconstant_argument)
7120                        << TheCall->getArg(i)->getSourceRange());
7121 
7122     // Allow -1 which will be translated to undef in the IR.
7123     if (Result->isSigned() && Result->isAllOnes())
7124       continue;
7125 
7126     if (Result->getActiveBits() > 64 ||
7127         Result->getZExtValue() >= numElements * 2)
7128       return ExprError(Diag(TheCall->getBeginLoc(),
7129                             diag::err_shufflevector_argument_too_large)
7130                        << TheCall->getArg(i)->getSourceRange());
7131   }
7132 
7133   SmallVector<Expr*, 32> exprs;
7134 
7135   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
7136     exprs.push_back(TheCall->getArg(i));
7137     TheCall->setArg(i, nullptr);
7138   }
7139 
7140   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
7141                                          TheCall->getCallee()->getBeginLoc(),
7142                                          TheCall->getRParenLoc());
7143 }
7144 
7145 /// SemaConvertVectorExpr - Handle __builtin_convertvector
7146 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
7147                                        SourceLocation BuiltinLoc,
7148                                        SourceLocation RParenLoc) {
7149   ExprValueKind VK = VK_PRValue;
7150   ExprObjectKind OK = OK_Ordinary;
7151   QualType DstTy = TInfo->getType();
7152   QualType SrcTy = E->getType();
7153 
7154   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
7155     return ExprError(Diag(BuiltinLoc,
7156                           diag::err_convertvector_non_vector)
7157                      << E->getSourceRange());
7158   if (!DstTy->isVectorType() && !DstTy->isDependentType())
7159     return ExprError(Diag(BuiltinLoc,
7160                           diag::err_convertvector_non_vector_type));
7161 
7162   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
7163     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
7164     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
7165     if (SrcElts != DstElts)
7166       return ExprError(Diag(BuiltinLoc,
7167                             diag::err_convertvector_incompatible_vector)
7168                        << E->getSourceRange());
7169   }
7170 
7171   return new (Context)
7172       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
7173 }
7174 
7175 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
7176 // This is declared to take (const void*, ...) and can take two
7177 // optional constant int args.
7178 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
7179   unsigned NumArgs = TheCall->getNumArgs();
7180 
7181   if (NumArgs > 3)
7182     return Diag(TheCall->getEndLoc(),
7183                 diag::err_typecheck_call_too_many_args_at_most)
7184            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7185 
7186   // Argument 0 is checked for us and the remaining arguments must be
7187   // constant integers.
7188   for (unsigned i = 1; i != NumArgs; ++i)
7189     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
7190       return true;
7191 
7192   return false;
7193 }
7194 
7195 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
7196 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
7197   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
7198     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
7199            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7200   if (checkArgCount(*this, TheCall, 1))
7201     return true;
7202   Expr *Arg = TheCall->getArg(0);
7203   if (Arg->isInstantiationDependent())
7204     return false;
7205 
7206   QualType ArgTy = Arg->getType();
7207   if (!ArgTy->hasFloatingRepresentation())
7208     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
7209            << ArgTy;
7210   if (Arg->isLValue()) {
7211     ExprResult FirstArg = DefaultLvalueConversion(Arg);
7212     TheCall->setArg(0, FirstArg.get());
7213   }
7214   TheCall->setType(TheCall->getArg(0)->getType());
7215   return false;
7216 }
7217 
7218 /// SemaBuiltinAssume - Handle __assume (MS Extension).
7219 // __assume does not evaluate its arguments, and should warn if its argument
7220 // has side effects.
7221 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
7222   Expr *Arg = TheCall->getArg(0);
7223   if (Arg->isInstantiationDependent()) return false;
7224 
7225   if (Arg->HasSideEffects(Context))
7226     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
7227         << Arg->getSourceRange()
7228         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
7229 
7230   return false;
7231 }
7232 
7233 /// Handle __builtin_alloca_with_align. This is declared
7234 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
7235 /// than 8.
7236 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
7237   // The alignment must be a constant integer.
7238   Expr *Arg = TheCall->getArg(1);
7239 
7240   // We can't check the value of a dependent argument.
7241   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7242     if (const auto *UE =
7243             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
7244       if (UE->getKind() == UETT_AlignOf ||
7245           UE->getKind() == UETT_PreferredAlignOf)
7246         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
7247             << Arg->getSourceRange();
7248 
7249     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
7250 
7251     if (!Result.isPowerOf2())
7252       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7253              << Arg->getSourceRange();
7254 
7255     if (Result < Context.getCharWidth())
7256       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
7257              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
7258 
7259     if (Result > std::numeric_limits<int32_t>::max())
7260       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
7261              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
7262   }
7263 
7264   return false;
7265 }
7266 
7267 /// Handle __builtin_assume_aligned. This is declared
7268 /// as (const void*, size_t, ...) and can take one optional constant int arg.
7269 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
7270   unsigned NumArgs = TheCall->getNumArgs();
7271 
7272   if (NumArgs > 3)
7273     return Diag(TheCall->getEndLoc(),
7274                 diag::err_typecheck_call_too_many_args_at_most)
7275            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7276 
7277   // The alignment must be a constant integer.
7278   Expr *Arg = TheCall->getArg(1);
7279 
7280   // We can't check the value of a dependent argument.
7281   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7282     llvm::APSInt Result;
7283     if (SemaBuiltinConstantArg(TheCall, 1, Result))
7284       return true;
7285 
7286     if (!Result.isPowerOf2())
7287       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7288              << Arg->getSourceRange();
7289 
7290     if (Result > Sema::MaximumAlignment)
7291       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
7292           << Arg->getSourceRange() << Sema::MaximumAlignment;
7293   }
7294 
7295   if (NumArgs > 2) {
7296     ExprResult Arg(TheCall->getArg(2));
7297     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
7298       Context.getSizeType(), false);
7299     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7300     if (Arg.isInvalid()) return true;
7301     TheCall->setArg(2, Arg.get());
7302   }
7303 
7304   return false;
7305 }
7306 
7307 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
7308   unsigned BuiltinID =
7309       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
7310   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
7311 
7312   unsigned NumArgs = TheCall->getNumArgs();
7313   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
7314   if (NumArgs < NumRequiredArgs) {
7315     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
7316            << 0 /* function call */ << NumRequiredArgs << NumArgs
7317            << TheCall->getSourceRange();
7318   }
7319   if (NumArgs >= NumRequiredArgs + 0x100) {
7320     return Diag(TheCall->getEndLoc(),
7321                 diag::err_typecheck_call_too_many_args_at_most)
7322            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
7323            << TheCall->getSourceRange();
7324   }
7325   unsigned i = 0;
7326 
7327   // For formatting call, check buffer arg.
7328   if (!IsSizeCall) {
7329     ExprResult Arg(TheCall->getArg(i));
7330     InitializedEntity Entity = InitializedEntity::InitializeParameter(
7331         Context, Context.VoidPtrTy, false);
7332     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7333     if (Arg.isInvalid())
7334       return true;
7335     TheCall->setArg(i, Arg.get());
7336     i++;
7337   }
7338 
7339   // Check string literal arg.
7340   unsigned FormatIdx = i;
7341   {
7342     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
7343     if (Arg.isInvalid())
7344       return true;
7345     TheCall->setArg(i, Arg.get());
7346     i++;
7347   }
7348 
7349   // Make sure variadic args are scalar.
7350   unsigned FirstDataArg = i;
7351   while (i < NumArgs) {
7352     ExprResult Arg = DefaultVariadicArgumentPromotion(
7353         TheCall->getArg(i), VariadicFunction, nullptr);
7354     if (Arg.isInvalid())
7355       return true;
7356     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
7357     if (ArgSize.getQuantity() >= 0x100) {
7358       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
7359              << i << (int)ArgSize.getQuantity() << 0xff
7360              << TheCall->getSourceRange();
7361     }
7362     TheCall->setArg(i, Arg.get());
7363     i++;
7364   }
7365 
7366   // Check formatting specifiers. NOTE: We're only doing this for the non-size
7367   // call to avoid duplicate diagnostics.
7368   if (!IsSizeCall) {
7369     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
7370     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
7371     bool Success = CheckFormatArguments(
7372         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
7373         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
7374         CheckedVarArgs);
7375     if (!Success)
7376       return true;
7377   }
7378 
7379   if (IsSizeCall) {
7380     TheCall->setType(Context.getSizeType());
7381   } else {
7382     TheCall->setType(Context.VoidPtrTy);
7383   }
7384   return false;
7385 }
7386 
7387 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
7388 /// TheCall is a constant expression.
7389 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7390                                   llvm::APSInt &Result) {
7391   Expr *Arg = TheCall->getArg(ArgNum);
7392   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
7393   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
7394 
7395   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
7396 
7397   Optional<llvm::APSInt> R;
7398   if (!(R = Arg->getIntegerConstantExpr(Context)))
7399     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
7400            << FDecl->getDeclName() << Arg->getSourceRange();
7401   Result = *R;
7402   return false;
7403 }
7404 
7405 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
7406 /// TheCall is a constant expression in the range [Low, High].
7407 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
7408                                        int Low, int High, bool RangeIsError) {
7409   if (isConstantEvaluated())
7410     return false;
7411   llvm::APSInt Result;
7412 
7413   // We can't check the value of a dependent argument.
7414   Expr *Arg = TheCall->getArg(ArgNum);
7415   if (Arg->isTypeDependent() || Arg->isValueDependent())
7416     return false;
7417 
7418   // Check constant-ness first.
7419   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7420     return true;
7421 
7422   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7423     if (RangeIsError)
7424       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
7425              << toString(Result, 10) << Low << High << Arg->getSourceRange();
7426     else
7427       // Defer the warning until we know if the code will be emitted so that
7428       // dead code can ignore this.
7429       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
7430                           PDiag(diag::warn_argument_invalid_range)
7431                               << toString(Result, 10) << Low << High
7432                               << Arg->getSourceRange());
7433   }
7434 
7435   return false;
7436 }
7437 
7438 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
7439 /// TheCall is a constant expression is a multiple of Num..
7440 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
7441                                           unsigned Num) {
7442   llvm::APSInt Result;
7443 
7444   // We can't check the value of a dependent argument.
7445   Expr *Arg = TheCall->getArg(ArgNum);
7446   if (Arg->isTypeDependent() || Arg->isValueDependent())
7447     return false;
7448 
7449   // Check constant-ness first.
7450   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7451     return true;
7452 
7453   if (Result.getSExtValue() % Num != 0)
7454     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7455            << Num << Arg->getSourceRange();
7456 
7457   return false;
7458 }
7459 
7460 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7461 /// constant expression representing a power of 2.
7462 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7463   llvm::APSInt Result;
7464 
7465   // We can't check the value of a dependent argument.
7466   Expr *Arg = TheCall->getArg(ArgNum);
7467   if (Arg->isTypeDependent() || Arg->isValueDependent())
7468     return false;
7469 
7470   // Check constant-ness first.
7471   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7472     return true;
7473 
7474   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7475   // and only if x is a power of 2.
7476   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7477     return false;
7478 
7479   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7480          << Arg->getSourceRange();
7481 }
7482 
7483 static bool IsShiftedByte(llvm::APSInt Value) {
7484   if (Value.isNegative())
7485     return false;
7486 
7487   // Check if it's a shifted byte, by shifting it down
7488   while (true) {
7489     // If the value fits in the bottom byte, the check passes.
7490     if (Value < 0x100)
7491       return true;
7492 
7493     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7494     // fails.
7495     if ((Value & 0xFF) != 0)
7496       return false;
7497 
7498     // If the bottom 8 bits are all 0, but something above that is nonzero,
7499     // then shifting the value right by 8 bits won't affect whether it's a
7500     // shifted byte or not. So do that, and go round again.
7501     Value >>= 8;
7502   }
7503 }
7504 
7505 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7506 /// a constant expression representing an arbitrary byte value shifted left by
7507 /// a multiple of 8 bits.
7508 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7509                                              unsigned ArgBits) {
7510   llvm::APSInt Result;
7511 
7512   // We can't check the value of a dependent argument.
7513   Expr *Arg = TheCall->getArg(ArgNum);
7514   if (Arg->isTypeDependent() || Arg->isValueDependent())
7515     return false;
7516 
7517   // Check constant-ness first.
7518   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7519     return true;
7520 
7521   // Truncate to the given size.
7522   Result = Result.getLoBits(ArgBits);
7523   Result.setIsUnsigned(true);
7524 
7525   if (IsShiftedByte(Result))
7526     return false;
7527 
7528   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7529          << Arg->getSourceRange();
7530 }
7531 
7532 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7533 /// TheCall is a constant expression representing either a shifted byte value,
7534 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7535 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7536 /// Arm MVE intrinsics.
7537 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7538                                                    int ArgNum,
7539                                                    unsigned ArgBits) {
7540   llvm::APSInt Result;
7541 
7542   // We can't check the value of a dependent argument.
7543   Expr *Arg = TheCall->getArg(ArgNum);
7544   if (Arg->isTypeDependent() || Arg->isValueDependent())
7545     return false;
7546 
7547   // Check constant-ness first.
7548   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7549     return true;
7550 
7551   // Truncate to the given size.
7552   Result = Result.getLoBits(ArgBits);
7553   Result.setIsUnsigned(true);
7554 
7555   // Check to see if it's in either of the required forms.
7556   if (IsShiftedByte(Result) ||
7557       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7558     return false;
7559 
7560   return Diag(TheCall->getBeginLoc(),
7561               diag::err_argument_not_shifted_byte_or_xxff)
7562          << Arg->getSourceRange();
7563 }
7564 
7565 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7566 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7567   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7568     if (checkArgCount(*this, TheCall, 2))
7569       return true;
7570     Expr *Arg0 = TheCall->getArg(0);
7571     Expr *Arg1 = TheCall->getArg(1);
7572 
7573     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7574     if (FirstArg.isInvalid())
7575       return true;
7576     QualType FirstArgType = FirstArg.get()->getType();
7577     if (!FirstArgType->isAnyPointerType())
7578       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7579                << "first" << FirstArgType << Arg0->getSourceRange();
7580     TheCall->setArg(0, FirstArg.get());
7581 
7582     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7583     if (SecArg.isInvalid())
7584       return true;
7585     QualType SecArgType = SecArg.get()->getType();
7586     if (!SecArgType->isIntegerType())
7587       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7588                << "second" << SecArgType << Arg1->getSourceRange();
7589 
7590     // Derive the return type from the pointer argument.
7591     TheCall->setType(FirstArgType);
7592     return false;
7593   }
7594 
7595   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7596     if (checkArgCount(*this, TheCall, 2))
7597       return true;
7598 
7599     Expr *Arg0 = TheCall->getArg(0);
7600     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7601     if (FirstArg.isInvalid())
7602       return true;
7603     QualType FirstArgType = FirstArg.get()->getType();
7604     if (!FirstArgType->isAnyPointerType())
7605       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7606                << "first" << FirstArgType << Arg0->getSourceRange();
7607     TheCall->setArg(0, FirstArg.get());
7608 
7609     // Derive the return type from the pointer argument.
7610     TheCall->setType(FirstArgType);
7611 
7612     // Second arg must be an constant in range [0,15]
7613     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7614   }
7615 
7616   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7617     if (checkArgCount(*this, TheCall, 2))
7618       return true;
7619     Expr *Arg0 = TheCall->getArg(0);
7620     Expr *Arg1 = TheCall->getArg(1);
7621 
7622     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7623     if (FirstArg.isInvalid())
7624       return true;
7625     QualType FirstArgType = FirstArg.get()->getType();
7626     if (!FirstArgType->isAnyPointerType())
7627       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7628                << "first" << FirstArgType << Arg0->getSourceRange();
7629 
7630     QualType SecArgType = Arg1->getType();
7631     if (!SecArgType->isIntegerType())
7632       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7633                << "second" << SecArgType << Arg1->getSourceRange();
7634     TheCall->setType(Context.IntTy);
7635     return false;
7636   }
7637 
7638   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7639       BuiltinID == AArch64::BI__builtin_arm_stg) {
7640     if (checkArgCount(*this, TheCall, 1))
7641       return true;
7642     Expr *Arg0 = TheCall->getArg(0);
7643     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7644     if (FirstArg.isInvalid())
7645       return true;
7646 
7647     QualType FirstArgType = FirstArg.get()->getType();
7648     if (!FirstArgType->isAnyPointerType())
7649       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7650                << "first" << FirstArgType << Arg0->getSourceRange();
7651     TheCall->setArg(0, FirstArg.get());
7652 
7653     // Derive the return type from the pointer argument.
7654     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7655       TheCall->setType(FirstArgType);
7656     return false;
7657   }
7658 
7659   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7660     Expr *ArgA = TheCall->getArg(0);
7661     Expr *ArgB = TheCall->getArg(1);
7662 
7663     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7664     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7665 
7666     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7667       return true;
7668 
7669     QualType ArgTypeA = ArgExprA.get()->getType();
7670     QualType ArgTypeB = ArgExprB.get()->getType();
7671 
7672     auto isNull = [&] (Expr *E) -> bool {
7673       return E->isNullPointerConstant(
7674                         Context, Expr::NPC_ValueDependentIsNotNull); };
7675 
7676     // argument should be either a pointer or null
7677     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7678       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7679         << "first" << ArgTypeA << ArgA->getSourceRange();
7680 
7681     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7682       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7683         << "second" << ArgTypeB << ArgB->getSourceRange();
7684 
7685     // Ensure Pointee types are compatible
7686     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7687         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7688       QualType pointeeA = ArgTypeA->getPointeeType();
7689       QualType pointeeB = ArgTypeB->getPointeeType();
7690       if (!Context.typesAreCompatible(
7691              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7692              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7693         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7694           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7695           << ArgB->getSourceRange();
7696       }
7697     }
7698 
7699     // at least one argument should be pointer type
7700     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7701       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7702         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7703 
7704     if (isNull(ArgA)) // adopt type of the other pointer
7705       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7706 
7707     if (isNull(ArgB))
7708       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7709 
7710     TheCall->setArg(0, ArgExprA.get());
7711     TheCall->setArg(1, ArgExprB.get());
7712     TheCall->setType(Context.LongLongTy);
7713     return false;
7714   }
7715   assert(false && "Unhandled ARM MTE intrinsic");
7716   return true;
7717 }
7718 
7719 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7720 /// TheCall is an ARM/AArch64 special register string literal.
7721 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7722                                     int ArgNum, unsigned ExpectedFieldNum,
7723                                     bool AllowName) {
7724   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7725                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7726                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7727                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7728                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7729                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7730   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7731                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7732                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7733                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7734                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7735                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7736   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7737 
7738   // We can't check the value of a dependent argument.
7739   Expr *Arg = TheCall->getArg(ArgNum);
7740   if (Arg->isTypeDependent() || Arg->isValueDependent())
7741     return false;
7742 
7743   // Check if the argument is a string literal.
7744   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7745     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7746            << Arg->getSourceRange();
7747 
7748   // Check the type of special register given.
7749   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7750   SmallVector<StringRef, 6> Fields;
7751   Reg.split(Fields, ":");
7752 
7753   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7754     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7755            << Arg->getSourceRange();
7756 
7757   // If the string is the name of a register then we cannot check that it is
7758   // valid here but if the string is of one the forms described in ACLE then we
7759   // can check that the supplied fields are integers and within the valid
7760   // ranges.
7761   if (Fields.size() > 1) {
7762     bool FiveFields = Fields.size() == 5;
7763 
7764     bool ValidString = true;
7765     if (IsARMBuiltin) {
7766       ValidString &= Fields[0].startswith_insensitive("cp") ||
7767                      Fields[0].startswith_insensitive("p");
7768       if (ValidString)
7769         Fields[0] = Fields[0].drop_front(
7770             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7771 
7772       ValidString &= Fields[2].startswith_insensitive("c");
7773       if (ValidString)
7774         Fields[2] = Fields[2].drop_front(1);
7775 
7776       if (FiveFields) {
7777         ValidString &= Fields[3].startswith_insensitive("c");
7778         if (ValidString)
7779           Fields[3] = Fields[3].drop_front(1);
7780       }
7781     }
7782 
7783     SmallVector<int, 5> Ranges;
7784     if (FiveFields)
7785       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7786     else
7787       Ranges.append({15, 7, 15});
7788 
7789     for (unsigned i=0; i<Fields.size(); ++i) {
7790       int IntField;
7791       ValidString &= !Fields[i].getAsInteger(10, IntField);
7792       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7793     }
7794 
7795     if (!ValidString)
7796       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7797              << Arg->getSourceRange();
7798   } else if (IsAArch64Builtin && Fields.size() == 1) {
7799     // If the register name is one of those that appear in the condition below
7800     // and the special register builtin being used is one of the write builtins,
7801     // then we require that the argument provided for writing to the register
7802     // is an integer constant expression. This is because it will be lowered to
7803     // an MSR (immediate) instruction, so we need to know the immediate at
7804     // compile time.
7805     if (TheCall->getNumArgs() != 2)
7806       return false;
7807 
7808     std::string RegLower = Reg.lower();
7809     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7810         RegLower != "pan" && RegLower != "uao")
7811       return false;
7812 
7813     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7814   }
7815 
7816   return false;
7817 }
7818 
7819 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7820 /// Emit an error and return true on failure; return false on success.
7821 /// TypeStr is a string containing the type descriptor of the value returned by
7822 /// the builtin and the descriptors of the expected type of the arguments.
7823 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
7824                                  const char *TypeStr) {
7825 
7826   assert((TypeStr[0] != '\0') &&
7827          "Invalid types in PPC MMA builtin declaration");
7828 
7829   switch (BuiltinID) {
7830   default:
7831     // This function is called in CheckPPCBuiltinFunctionCall where the
7832     // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here
7833     // we are isolating the pair vector memop builtins that can be used with mma
7834     // off so the default case is every builtin that requires mma and paired
7835     // vector memops.
7836     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7837                          diag::err_ppc_builtin_only_on_arch, "10") ||
7838         SemaFeatureCheck(*this, TheCall, "mma",
7839                          diag::err_ppc_builtin_only_on_arch, "10"))
7840       return true;
7841     break;
7842   case PPC::BI__builtin_vsx_lxvp:
7843   case PPC::BI__builtin_vsx_stxvp:
7844   case PPC::BI__builtin_vsx_assemble_pair:
7845   case PPC::BI__builtin_vsx_disassemble_pair:
7846     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7847                          diag::err_ppc_builtin_only_on_arch, "10"))
7848       return true;
7849     break;
7850   }
7851 
7852   unsigned Mask = 0;
7853   unsigned ArgNum = 0;
7854 
7855   // The first type in TypeStr is the type of the value returned by the
7856   // builtin. So we first read that type and change the type of TheCall.
7857   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7858   TheCall->setType(type);
7859 
7860   while (*TypeStr != '\0') {
7861     Mask = 0;
7862     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7863     if (ArgNum >= TheCall->getNumArgs()) {
7864       ArgNum++;
7865       break;
7866     }
7867 
7868     Expr *Arg = TheCall->getArg(ArgNum);
7869     QualType PassedType = Arg->getType();
7870     QualType StrippedRVType = PassedType.getCanonicalType();
7871 
7872     // Strip Restrict/Volatile qualifiers.
7873     if (StrippedRVType.isRestrictQualified() ||
7874         StrippedRVType.isVolatileQualified())
7875       StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
7876 
7877     // The only case where the argument type and expected type are allowed to
7878     // mismatch is if the argument type is a non-void pointer (or array) and
7879     // expected type is a void pointer.
7880     if (StrippedRVType != ExpectedType)
7881       if (!(ExpectedType->isVoidPointerType() &&
7882             (StrippedRVType->isPointerType() || StrippedRVType->isArrayType())))
7883         return Diag(Arg->getBeginLoc(),
7884                     diag::err_typecheck_convert_incompatible)
7885                << PassedType << ExpectedType << 1 << 0 << 0;
7886 
7887     // If the value of the Mask is not 0, we have a constraint in the size of
7888     // the integer argument so here we ensure the argument is a constant that
7889     // is in the valid range.
7890     if (Mask != 0 &&
7891         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7892       return true;
7893 
7894     ArgNum++;
7895   }
7896 
7897   // In case we exited early from the previous loop, there are other types to
7898   // read from TypeStr. So we need to read them all to ensure we have the right
7899   // number of arguments in TheCall and if it is not the case, to display a
7900   // better error message.
7901   while (*TypeStr != '\0') {
7902     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7903     ArgNum++;
7904   }
7905   if (checkArgCount(*this, TheCall, ArgNum))
7906     return true;
7907 
7908   return false;
7909 }
7910 
7911 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7912 /// This checks that the target supports __builtin_longjmp and
7913 /// that val is a constant 1.
7914 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7915   if (!Context.getTargetInfo().hasSjLjLowering())
7916     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7917            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7918 
7919   Expr *Arg = TheCall->getArg(1);
7920   llvm::APSInt Result;
7921 
7922   // TODO: This is less than ideal. Overload this to take a value.
7923   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7924     return true;
7925 
7926   if (Result != 1)
7927     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7928            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7929 
7930   return false;
7931 }
7932 
7933 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7934 /// This checks that the target supports __builtin_setjmp.
7935 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7936   if (!Context.getTargetInfo().hasSjLjLowering())
7937     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7938            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7939   return false;
7940 }
7941 
7942 namespace {
7943 
7944 class UncoveredArgHandler {
7945   enum { Unknown = -1, AllCovered = -2 };
7946 
7947   signed FirstUncoveredArg = Unknown;
7948   SmallVector<const Expr *, 4> DiagnosticExprs;
7949 
7950 public:
7951   UncoveredArgHandler() = default;
7952 
7953   bool hasUncoveredArg() const {
7954     return (FirstUncoveredArg >= 0);
7955   }
7956 
7957   unsigned getUncoveredArg() const {
7958     assert(hasUncoveredArg() && "no uncovered argument");
7959     return FirstUncoveredArg;
7960   }
7961 
7962   void setAllCovered() {
7963     // A string has been found with all arguments covered, so clear out
7964     // the diagnostics.
7965     DiagnosticExprs.clear();
7966     FirstUncoveredArg = AllCovered;
7967   }
7968 
7969   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7970     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7971 
7972     // Don't update if a previous string covers all arguments.
7973     if (FirstUncoveredArg == AllCovered)
7974       return;
7975 
7976     // UncoveredArgHandler tracks the highest uncovered argument index
7977     // and with it all the strings that match this index.
7978     if (NewFirstUncoveredArg == FirstUncoveredArg)
7979       DiagnosticExprs.push_back(StrExpr);
7980     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7981       DiagnosticExprs.clear();
7982       DiagnosticExprs.push_back(StrExpr);
7983       FirstUncoveredArg = NewFirstUncoveredArg;
7984     }
7985   }
7986 
7987   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7988 };
7989 
7990 enum StringLiteralCheckType {
7991   SLCT_NotALiteral,
7992   SLCT_UncheckedLiteral,
7993   SLCT_CheckedLiteral
7994 };
7995 
7996 } // namespace
7997 
7998 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7999                                      BinaryOperatorKind BinOpKind,
8000                                      bool AddendIsRight) {
8001   unsigned BitWidth = Offset.getBitWidth();
8002   unsigned AddendBitWidth = Addend.getBitWidth();
8003   // There might be negative interim results.
8004   if (Addend.isUnsigned()) {
8005     Addend = Addend.zext(++AddendBitWidth);
8006     Addend.setIsSigned(true);
8007   }
8008   // Adjust the bit width of the APSInts.
8009   if (AddendBitWidth > BitWidth) {
8010     Offset = Offset.sext(AddendBitWidth);
8011     BitWidth = AddendBitWidth;
8012   } else if (BitWidth > AddendBitWidth) {
8013     Addend = Addend.sext(BitWidth);
8014   }
8015 
8016   bool Ov = false;
8017   llvm::APSInt ResOffset = Offset;
8018   if (BinOpKind == BO_Add)
8019     ResOffset = Offset.sadd_ov(Addend, Ov);
8020   else {
8021     assert(AddendIsRight && BinOpKind == BO_Sub &&
8022            "operator must be add or sub with addend on the right");
8023     ResOffset = Offset.ssub_ov(Addend, Ov);
8024   }
8025 
8026   // We add an offset to a pointer here so we should support an offset as big as
8027   // possible.
8028   if (Ov) {
8029     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
8030            "index (intermediate) result too big");
8031     Offset = Offset.sext(2 * BitWidth);
8032     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
8033     return;
8034   }
8035 
8036   Offset = ResOffset;
8037 }
8038 
8039 namespace {
8040 
8041 // This is a wrapper class around StringLiteral to support offsetted string
8042 // literals as format strings. It takes the offset into account when returning
8043 // the string and its length or the source locations to display notes correctly.
8044 class FormatStringLiteral {
8045   const StringLiteral *FExpr;
8046   int64_t Offset;
8047 
8048  public:
8049   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
8050       : FExpr(fexpr), Offset(Offset) {}
8051 
8052   StringRef getString() const {
8053     return FExpr->getString().drop_front(Offset);
8054   }
8055 
8056   unsigned getByteLength() const {
8057     return FExpr->getByteLength() - getCharByteWidth() * Offset;
8058   }
8059 
8060   unsigned getLength() const { return FExpr->getLength() - Offset; }
8061   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
8062 
8063   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
8064 
8065   QualType getType() const { return FExpr->getType(); }
8066 
8067   bool isAscii() const { return FExpr->isAscii(); }
8068   bool isWide() const { return FExpr->isWide(); }
8069   bool isUTF8() const { return FExpr->isUTF8(); }
8070   bool isUTF16() const { return FExpr->isUTF16(); }
8071   bool isUTF32() const { return FExpr->isUTF32(); }
8072   bool isPascal() const { return FExpr->isPascal(); }
8073 
8074   SourceLocation getLocationOfByte(
8075       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
8076       const TargetInfo &Target, unsigned *StartToken = nullptr,
8077       unsigned *StartTokenByteOffset = nullptr) const {
8078     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
8079                                     StartToken, StartTokenByteOffset);
8080   }
8081 
8082   SourceLocation getBeginLoc() const LLVM_READONLY {
8083     return FExpr->getBeginLoc().getLocWithOffset(Offset);
8084   }
8085 
8086   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
8087 };
8088 
8089 }  // namespace
8090 
8091 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8092                               const Expr *OrigFormatExpr,
8093                               ArrayRef<const Expr *> Args,
8094                               bool HasVAListArg, unsigned format_idx,
8095                               unsigned firstDataArg,
8096                               Sema::FormatStringType Type,
8097                               bool inFunctionCall,
8098                               Sema::VariadicCallType CallType,
8099                               llvm::SmallBitVector &CheckedVarArgs,
8100                               UncoveredArgHandler &UncoveredArg,
8101                               bool IgnoreStringsWithoutSpecifiers);
8102 
8103 // Determine if an expression is a string literal or constant string.
8104 // If this function returns false on the arguments to a function expecting a
8105 // format string, we will usually need to emit a warning.
8106 // True string literals are then checked by CheckFormatString.
8107 static StringLiteralCheckType
8108 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
8109                       bool HasVAListArg, unsigned format_idx,
8110                       unsigned firstDataArg, Sema::FormatStringType Type,
8111                       Sema::VariadicCallType CallType, bool InFunctionCall,
8112                       llvm::SmallBitVector &CheckedVarArgs,
8113                       UncoveredArgHandler &UncoveredArg,
8114                       llvm::APSInt Offset,
8115                       bool IgnoreStringsWithoutSpecifiers = false) {
8116   if (S.isConstantEvaluated())
8117     return SLCT_NotALiteral;
8118  tryAgain:
8119   assert(Offset.isSigned() && "invalid offset");
8120 
8121   if (E->isTypeDependent() || E->isValueDependent())
8122     return SLCT_NotALiteral;
8123 
8124   E = E->IgnoreParenCasts();
8125 
8126   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
8127     // Technically -Wformat-nonliteral does not warn about this case.
8128     // The behavior of printf and friends in this case is implementation
8129     // dependent.  Ideally if the format string cannot be null then
8130     // it should have a 'nonnull' attribute in the function prototype.
8131     return SLCT_UncheckedLiteral;
8132 
8133   switch (E->getStmtClass()) {
8134   case Stmt::BinaryConditionalOperatorClass:
8135   case Stmt::ConditionalOperatorClass: {
8136     // The expression is a literal if both sub-expressions were, and it was
8137     // completely checked only if both sub-expressions were checked.
8138     const AbstractConditionalOperator *C =
8139         cast<AbstractConditionalOperator>(E);
8140 
8141     // Determine whether it is necessary to check both sub-expressions, for
8142     // example, because the condition expression is a constant that can be
8143     // evaluated at compile time.
8144     bool CheckLeft = true, CheckRight = true;
8145 
8146     bool Cond;
8147     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
8148                                                  S.isConstantEvaluated())) {
8149       if (Cond)
8150         CheckRight = false;
8151       else
8152         CheckLeft = false;
8153     }
8154 
8155     // We need to maintain the offsets for the right and the left hand side
8156     // separately to check if every possible indexed expression is a valid
8157     // string literal. They might have different offsets for different string
8158     // literals in the end.
8159     StringLiteralCheckType Left;
8160     if (!CheckLeft)
8161       Left = SLCT_UncheckedLiteral;
8162     else {
8163       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
8164                                    HasVAListArg, format_idx, firstDataArg,
8165                                    Type, CallType, InFunctionCall,
8166                                    CheckedVarArgs, UncoveredArg, Offset,
8167                                    IgnoreStringsWithoutSpecifiers);
8168       if (Left == SLCT_NotALiteral || !CheckRight) {
8169         return Left;
8170       }
8171     }
8172 
8173     StringLiteralCheckType Right = checkFormatStringExpr(
8174         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
8175         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8176         IgnoreStringsWithoutSpecifiers);
8177 
8178     return (CheckLeft && Left < Right) ? Left : Right;
8179   }
8180 
8181   case Stmt::ImplicitCastExprClass:
8182     E = cast<ImplicitCastExpr>(E)->getSubExpr();
8183     goto tryAgain;
8184 
8185   case Stmt::OpaqueValueExprClass:
8186     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
8187       E = src;
8188       goto tryAgain;
8189     }
8190     return SLCT_NotALiteral;
8191 
8192   case Stmt::PredefinedExprClass:
8193     // While __func__, etc., are technically not string literals, they
8194     // cannot contain format specifiers and thus are not a security
8195     // liability.
8196     return SLCT_UncheckedLiteral;
8197 
8198   case Stmt::DeclRefExprClass: {
8199     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8200 
8201     // As an exception, do not flag errors for variables binding to
8202     // const string literals.
8203     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
8204       bool isConstant = false;
8205       QualType T = DR->getType();
8206 
8207       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
8208         isConstant = AT->getElementType().isConstant(S.Context);
8209       } else if (const PointerType *PT = T->getAs<PointerType>()) {
8210         isConstant = T.isConstant(S.Context) &&
8211                      PT->getPointeeType().isConstant(S.Context);
8212       } else if (T->isObjCObjectPointerType()) {
8213         // In ObjC, there is usually no "const ObjectPointer" type,
8214         // so don't check if the pointee type is constant.
8215         isConstant = T.isConstant(S.Context);
8216       }
8217 
8218       if (isConstant) {
8219         if (const Expr *Init = VD->getAnyInitializer()) {
8220           // Look through initializers like const char c[] = { "foo" }
8221           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
8222             if (InitList->isStringLiteralInit())
8223               Init = InitList->getInit(0)->IgnoreParenImpCasts();
8224           }
8225           return checkFormatStringExpr(S, Init, Args,
8226                                        HasVAListArg, format_idx,
8227                                        firstDataArg, Type, CallType,
8228                                        /*InFunctionCall*/ false, CheckedVarArgs,
8229                                        UncoveredArg, Offset);
8230         }
8231       }
8232 
8233       // For vprintf* functions (i.e., HasVAListArg==true), we add a
8234       // special check to see if the format string is a function parameter
8235       // of the function calling the printf function.  If the function
8236       // has an attribute indicating it is a printf-like function, then we
8237       // should suppress warnings concerning non-literals being used in a call
8238       // to a vprintf function.  For example:
8239       //
8240       // void
8241       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
8242       //      va_list ap;
8243       //      va_start(ap, fmt);
8244       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
8245       //      ...
8246       // }
8247       if (HasVAListArg) {
8248         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
8249           if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) {
8250             int PVIndex = PV->getFunctionScopeIndex() + 1;
8251             for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
8252               // adjust for implicit parameter
8253               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
8254                 if (MD->isInstance())
8255                   ++PVIndex;
8256               // We also check if the formats are compatible.
8257               // We can't pass a 'scanf' string to a 'printf' function.
8258               if (PVIndex == PVFormat->getFormatIdx() &&
8259                   Type == S.GetFormatStringType(PVFormat))
8260                 return SLCT_UncheckedLiteral;
8261             }
8262           }
8263         }
8264       }
8265     }
8266 
8267     return SLCT_NotALiteral;
8268   }
8269 
8270   case Stmt::CallExprClass:
8271   case Stmt::CXXMemberCallExprClass: {
8272     const CallExpr *CE = cast<CallExpr>(E);
8273     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
8274       bool IsFirst = true;
8275       StringLiteralCheckType CommonResult;
8276       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
8277         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
8278         StringLiteralCheckType Result = checkFormatStringExpr(
8279             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8280             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8281             IgnoreStringsWithoutSpecifiers);
8282         if (IsFirst) {
8283           CommonResult = Result;
8284           IsFirst = false;
8285         }
8286       }
8287       if (!IsFirst)
8288         return CommonResult;
8289 
8290       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
8291         unsigned BuiltinID = FD->getBuiltinID();
8292         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
8293             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
8294           const Expr *Arg = CE->getArg(0);
8295           return checkFormatStringExpr(S, Arg, Args,
8296                                        HasVAListArg, format_idx,
8297                                        firstDataArg, Type, CallType,
8298                                        InFunctionCall, CheckedVarArgs,
8299                                        UncoveredArg, Offset,
8300                                        IgnoreStringsWithoutSpecifiers);
8301         }
8302       }
8303     }
8304 
8305     return SLCT_NotALiteral;
8306   }
8307   case Stmt::ObjCMessageExprClass: {
8308     const auto *ME = cast<ObjCMessageExpr>(E);
8309     if (const auto *MD = ME->getMethodDecl()) {
8310       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
8311         // As a special case heuristic, if we're using the method -[NSBundle
8312         // localizedStringForKey:value:table:], ignore any key strings that lack
8313         // format specifiers. The idea is that if the key doesn't have any
8314         // format specifiers then its probably just a key to map to the
8315         // localized strings. If it does have format specifiers though, then its
8316         // likely that the text of the key is the format string in the
8317         // programmer's language, and should be checked.
8318         const ObjCInterfaceDecl *IFace;
8319         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
8320             IFace->getIdentifier()->isStr("NSBundle") &&
8321             MD->getSelector().isKeywordSelector(
8322                 {"localizedStringForKey", "value", "table"})) {
8323           IgnoreStringsWithoutSpecifiers = true;
8324         }
8325 
8326         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
8327         return checkFormatStringExpr(
8328             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8329             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8330             IgnoreStringsWithoutSpecifiers);
8331       }
8332     }
8333 
8334     return SLCT_NotALiteral;
8335   }
8336   case Stmt::ObjCStringLiteralClass:
8337   case Stmt::StringLiteralClass: {
8338     const StringLiteral *StrE = nullptr;
8339 
8340     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
8341       StrE = ObjCFExpr->getString();
8342     else
8343       StrE = cast<StringLiteral>(E);
8344 
8345     if (StrE) {
8346       if (Offset.isNegative() || Offset > StrE->getLength()) {
8347         // TODO: It would be better to have an explicit warning for out of
8348         // bounds literals.
8349         return SLCT_NotALiteral;
8350       }
8351       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
8352       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
8353                         firstDataArg, Type, InFunctionCall, CallType,
8354                         CheckedVarArgs, UncoveredArg,
8355                         IgnoreStringsWithoutSpecifiers);
8356       return SLCT_CheckedLiteral;
8357     }
8358 
8359     return SLCT_NotALiteral;
8360   }
8361   case Stmt::BinaryOperatorClass: {
8362     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
8363 
8364     // A string literal + an int offset is still a string literal.
8365     if (BinOp->isAdditiveOp()) {
8366       Expr::EvalResult LResult, RResult;
8367 
8368       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
8369           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8370       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
8371           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8372 
8373       if (LIsInt != RIsInt) {
8374         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
8375 
8376         if (LIsInt) {
8377           if (BinOpKind == BO_Add) {
8378             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
8379             E = BinOp->getRHS();
8380             goto tryAgain;
8381           }
8382         } else {
8383           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
8384           E = BinOp->getLHS();
8385           goto tryAgain;
8386         }
8387       }
8388     }
8389 
8390     return SLCT_NotALiteral;
8391   }
8392   case Stmt::UnaryOperatorClass: {
8393     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
8394     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
8395     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
8396       Expr::EvalResult IndexResult;
8397       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
8398                                        Expr::SE_NoSideEffects,
8399                                        S.isConstantEvaluated())) {
8400         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
8401                    /*RHS is int*/ true);
8402         E = ASE->getBase();
8403         goto tryAgain;
8404       }
8405     }
8406 
8407     return SLCT_NotALiteral;
8408   }
8409 
8410   default:
8411     return SLCT_NotALiteral;
8412   }
8413 }
8414 
8415 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
8416   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
8417       .Case("scanf", FST_Scanf)
8418       .Cases("printf", "printf0", FST_Printf)
8419       .Cases("NSString", "CFString", FST_NSString)
8420       .Case("strftime", FST_Strftime)
8421       .Case("strfmon", FST_Strfmon)
8422       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
8423       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
8424       .Case("os_trace", FST_OSLog)
8425       .Case("os_log", FST_OSLog)
8426       .Default(FST_Unknown);
8427 }
8428 
8429 /// CheckFormatArguments - Check calls to printf and scanf (and similar
8430 /// functions) for correct use of format strings.
8431 /// Returns true if a format string has been fully checked.
8432 bool Sema::CheckFormatArguments(const FormatAttr *Format,
8433                                 ArrayRef<const Expr *> Args,
8434                                 bool IsCXXMember,
8435                                 VariadicCallType CallType,
8436                                 SourceLocation Loc, SourceRange Range,
8437                                 llvm::SmallBitVector &CheckedVarArgs) {
8438   FormatStringInfo FSI;
8439   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
8440     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
8441                                 FSI.FirstDataArg, GetFormatStringType(Format),
8442                                 CallType, Loc, Range, CheckedVarArgs);
8443   return false;
8444 }
8445 
8446 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8447                                 bool HasVAListArg, unsigned format_idx,
8448                                 unsigned firstDataArg, FormatStringType Type,
8449                                 VariadicCallType CallType,
8450                                 SourceLocation Loc, SourceRange Range,
8451                                 llvm::SmallBitVector &CheckedVarArgs) {
8452   // CHECK: printf/scanf-like function is called with no format string.
8453   if (format_idx >= Args.size()) {
8454     Diag(Loc, diag::warn_missing_format_string) << Range;
8455     return false;
8456   }
8457 
8458   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8459 
8460   // CHECK: format string is not a string literal.
8461   //
8462   // Dynamically generated format strings are difficult to
8463   // automatically vet at compile time.  Requiring that format strings
8464   // are string literals: (1) permits the checking of format strings by
8465   // the compiler and thereby (2) can practically remove the source of
8466   // many format string exploits.
8467 
8468   // Format string can be either ObjC string (e.g. @"%d") or
8469   // C string (e.g. "%d")
8470   // ObjC string uses the same format specifiers as C string, so we can use
8471   // the same format string checking logic for both ObjC and C strings.
8472   UncoveredArgHandler UncoveredArg;
8473   StringLiteralCheckType CT =
8474       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8475                             format_idx, firstDataArg, Type, CallType,
8476                             /*IsFunctionCall*/ true, CheckedVarArgs,
8477                             UncoveredArg,
8478                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8479 
8480   // Generate a diagnostic where an uncovered argument is detected.
8481   if (UncoveredArg.hasUncoveredArg()) {
8482     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8483     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8484     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8485   }
8486 
8487   if (CT != SLCT_NotALiteral)
8488     // Literal format string found, check done!
8489     return CT == SLCT_CheckedLiteral;
8490 
8491   // Strftime is particular as it always uses a single 'time' argument,
8492   // so it is safe to pass a non-literal string.
8493   if (Type == FST_Strftime)
8494     return false;
8495 
8496   // Do not emit diag when the string param is a macro expansion and the
8497   // format is either NSString or CFString. This is a hack to prevent
8498   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8499   // which are usually used in place of NS and CF string literals.
8500   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8501   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8502     return false;
8503 
8504   // If there are no arguments specified, warn with -Wformat-security, otherwise
8505   // warn only with -Wformat-nonliteral.
8506   if (Args.size() == firstDataArg) {
8507     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8508       << OrigFormatExpr->getSourceRange();
8509     switch (Type) {
8510     default:
8511       break;
8512     case FST_Kprintf:
8513     case FST_FreeBSDKPrintf:
8514     case FST_Printf:
8515       Diag(FormatLoc, diag::note_format_security_fixit)
8516         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8517       break;
8518     case FST_NSString:
8519       Diag(FormatLoc, diag::note_format_security_fixit)
8520         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8521       break;
8522     }
8523   } else {
8524     Diag(FormatLoc, diag::warn_format_nonliteral)
8525       << OrigFormatExpr->getSourceRange();
8526   }
8527   return false;
8528 }
8529 
8530 namespace {
8531 
8532 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8533 protected:
8534   Sema &S;
8535   const FormatStringLiteral *FExpr;
8536   const Expr *OrigFormatExpr;
8537   const Sema::FormatStringType FSType;
8538   const unsigned FirstDataArg;
8539   const unsigned NumDataArgs;
8540   const char *Beg; // Start of format string.
8541   const bool HasVAListArg;
8542   ArrayRef<const Expr *> Args;
8543   unsigned FormatIdx;
8544   llvm::SmallBitVector CoveredArgs;
8545   bool usesPositionalArgs = false;
8546   bool atFirstArg = true;
8547   bool inFunctionCall;
8548   Sema::VariadicCallType CallType;
8549   llvm::SmallBitVector &CheckedVarArgs;
8550   UncoveredArgHandler &UncoveredArg;
8551 
8552 public:
8553   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8554                      const Expr *origFormatExpr,
8555                      const Sema::FormatStringType type, unsigned firstDataArg,
8556                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8557                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8558                      bool inFunctionCall, Sema::VariadicCallType callType,
8559                      llvm::SmallBitVector &CheckedVarArgs,
8560                      UncoveredArgHandler &UncoveredArg)
8561       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8562         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8563         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8564         inFunctionCall(inFunctionCall), CallType(callType),
8565         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8566     CoveredArgs.resize(numDataArgs);
8567     CoveredArgs.reset();
8568   }
8569 
8570   void DoneProcessing();
8571 
8572   void HandleIncompleteSpecifier(const char *startSpecifier,
8573                                  unsigned specifierLen) override;
8574 
8575   void HandleInvalidLengthModifier(
8576                            const analyze_format_string::FormatSpecifier &FS,
8577                            const analyze_format_string::ConversionSpecifier &CS,
8578                            const char *startSpecifier, unsigned specifierLen,
8579                            unsigned DiagID);
8580 
8581   void HandleNonStandardLengthModifier(
8582                     const analyze_format_string::FormatSpecifier &FS,
8583                     const char *startSpecifier, unsigned specifierLen);
8584 
8585   void HandleNonStandardConversionSpecifier(
8586                     const analyze_format_string::ConversionSpecifier &CS,
8587                     const char *startSpecifier, unsigned specifierLen);
8588 
8589   void HandlePosition(const char *startPos, unsigned posLen) override;
8590 
8591   void HandleInvalidPosition(const char *startSpecifier,
8592                              unsigned specifierLen,
8593                              analyze_format_string::PositionContext p) override;
8594 
8595   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8596 
8597   void HandleNullChar(const char *nullCharacter) override;
8598 
8599   template <typename Range>
8600   static void
8601   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8602                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8603                        bool IsStringLocation, Range StringRange,
8604                        ArrayRef<FixItHint> Fixit = None);
8605 
8606 protected:
8607   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8608                                         const char *startSpec,
8609                                         unsigned specifierLen,
8610                                         const char *csStart, unsigned csLen);
8611 
8612   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8613                                          const char *startSpec,
8614                                          unsigned specifierLen);
8615 
8616   SourceRange getFormatStringRange();
8617   CharSourceRange getSpecifierRange(const char *startSpecifier,
8618                                     unsigned specifierLen);
8619   SourceLocation getLocationOfByte(const char *x);
8620 
8621   const Expr *getDataArg(unsigned i) const;
8622 
8623   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8624                     const analyze_format_string::ConversionSpecifier &CS,
8625                     const char *startSpecifier, unsigned specifierLen,
8626                     unsigned argIndex);
8627 
8628   template <typename Range>
8629   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8630                             bool IsStringLocation, Range StringRange,
8631                             ArrayRef<FixItHint> Fixit = None);
8632 };
8633 
8634 } // namespace
8635 
8636 SourceRange CheckFormatHandler::getFormatStringRange() {
8637   return OrigFormatExpr->getSourceRange();
8638 }
8639 
8640 CharSourceRange CheckFormatHandler::
8641 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8642   SourceLocation Start = getLocationOfByte(startSpecifier);
8643   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8644 
8645   // Advance the end SourceLocation by one due to half-open ranges.
8646   End = End.getLocWithOffset(1);
8647 
8648   return CharSourceRange::getCharRange(Start, End);
8649 }
8650 
8651 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8652   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8653                                   S.getLangOpts(), S.Context.getTargetInfo());
8654 }
8655 
8656 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8657                                                    unsigned specifierLen){
8658   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8659                        getLocationOfByte(startSpecifier),
8660                        /*IsStringLocation*/true,
8661                        getSpecifierRange(startSpecifier, specifierLen));
8662 }
8663 
8664 void CheckFormatHandler::HandleInvalidLengthModifier(
8665     const analyze_format_string::FormatSpecifier &FS,
8666     const analyze_format_string::ConversionSpecifier &CS,
8667     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8668   using namespace analyze_format_string;
8669 
8670   const LengthModifier &LM = FS.getLengthModifier();
8671   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8672 
8673   // See if we know how to fix this length modifier.
8674   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8675   if (FixedLM) {
8676     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8677                          getLocationOfByte(LM.getStart()),
8678                          /*IsStringLocation*/true,
8679                          getSpecifierRange(startSpecifier, specifierLen));
8680 
8681     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8682       << FixedLM->toString()
8683       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8684 
8685   } else {
8686     FixItHint Hint;
8687     if (DiagID == diag::warn_format_nonsensical_length)
8688       Hint = FixItHint::CreateRemoval(LMRange);
8689 
8690     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8691                          getLocationOfByte(LM.getStart()),
8692                          /*IsStringLocation*/true,
8693                          getSpecifierRange(startSpecifier, specifierLen),
8694                          Hint);
8695   }
8696 }
8697 
8698 void CheckFormatHandler::HandleNonStandardLengthModifier(
8699     const analyze_format_string::FormatSpecifier &FS,
8700     const char *startSpecifier, unsigned specifierLen) {
8701   using namespace analyze_format_string;
8702 
8703   const LengthModifier &LM = FS.getLengthModifier();
8704   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8705 
8706   // See if we know how to fix this length modifier.
8707   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8708   if (FixedLM) {
8709     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8710                            << LM.toString() << 0,
8711                          getLocationOfByte(LM.getStart()),
8712                          /*IsStringLocation*/true,
8713                          getSpecifierRange(startSpecifier, specifierLen));
8714 
8715     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8716       << FixedLM->toString()
8717       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8718 
8719   } else {
8720     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8721                            << LM.toString() << 0,
8722                          getLocationOfByte(LM.getStart()),
8723                          /*IsStringLocation*/true,
8724                          getSpecifierRange(startSpecifier, specifierLen));
8725   }
8726 }
8727 
8728 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8729     const analyze_format_string::ConversionSpecifier &CS,
8730     const char *startSpecifier, unsigned specifierLen) {
8731   using namespace analyze_format_string;
8732 
8733   // See if we know how to fix this conversion specifier.
8734   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8735   if (FixedCS) {
8736     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8737                           << CS.toString() << /*conversion specifier*/1,
8738                          getLocationOfByte(CS.getStart()),
8739                          /*IsStringLocation*/true,
8740                          getSpecifierRange(startSpecifier, specifierLen));
8741 
8742     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8743     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8744       << FixedCS->toString()
8745       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8746   } else {
8747     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8748                           << CS.toString() << /*conversion specifier*/1,
8749                          getLocationOfByte(CS.getStart()),
8750                          /*IsStringLocation*/true,
8751                          getSpecifierRange(startSpecifier, specifierLen));
8752   }
8753 }
8754 
8755 void CheckFormatHandler::HandlePosition(const char *startPos,
8756                                         unsigned posLen) {
8757   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8758                                getLocationOfByte(startPos),
8759                                /*IsStringLocation*/true,
8760                                getSpecifierRange(startPos, posLen));
8761 }
8762 
8763 void
8764 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8765                                      analyze_format_string::PositionContext p) {
8766   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8767                          << (unsigned) p,
8768                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8769                        getSpecifierRange(startPos, posLen));
8770 }
8771 
8772 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8773                                             unsigned posLen) {
8774   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8775                                getLocationOfByte(startPos),
8776                                /*IsStringLocation*/true,
8777                                getSpecifierRange(startPos, posLen));
8778 }
8779 
8780 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8781   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8782     // The presence of a null character is likely an error.
8783     EmitFormatDiagnostic(
8784       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8785       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8786       getFormatStringRange());
8787   }
8788 }
8789 
8790 // Note that this may return NULL if there was an error parsing or building
8791 // one of the argument expressions.
8792 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8793   return Args[FirstDataArg + i];
8794 }
8795 
8796 void CheckFormatHandler::DoneProcessing() {
8797   // Does the number of data arguments exceed the number of
8798   // format conversions in the format string?
8799   if (!HasVAListArg) {
8800       // Find any arguments that weren't covered.
8801     CoveredArgs.flip();
8802     signed notCoveredArg = CoveredArgs.find_first();
8803     if (notCoveredArg >= 0) {
8804       assert((unsigned)notCoveredArg < NumDataArgs);
8805       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8806     } else {
8807       UncoveredArg.setAllCovered();
8808     }
8809   }
8810 }
8811 
8812 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8813                                    const Expr *ArgExpr) {
8814   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8815          "Invalid state");
8816 
8817   if (!ArgExpr)
8818     return;
8819 
8820   SourceLocation Loc = ArgExpr->getBeginLoc();
8821 
8822   if (S.getSourceManager().isInSystemMacro(Loc))
8823     return;
8824 
8825   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8826   for (auto E : DiagnosticExprs)
8827     PDiag << E->getSourceRange();
8828 
8829   CheckFormatHandler::EmitFormatDiagnostic(
8830                                   S, IsFunctionCall, DiagnosticExprs[0],
8831                                   PDiag, Loc, /*IsStringLocation*/false,
8832                                   DiagnosticExprs[0]->getSourceRange());
8833 }
8834 
8835 bool
8836 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8837                                                      SourceLocation Loc,
8838                                                      const char *startSpec,
8839                                                      unsigned specifierLen,
8840                                                      const char *csStart,
8841                                                      unsigned csLen) {
8842   bool keepGoing = true;
8843   if (argIndex < NumDataArgs) {
8844     // Consider the argument coverered, even though the specifier doesn't
8845     // make sense.
8846     CoveredArgs.set(argIndex);
8847   }
8848   else {
8849     // If argIndex exceeds the number of data arguments we
8850     // don't issue a warning because that is just a cascade of warnings (and
8851     // they may have intended '%%' anyway). We don't want to continue processing
8852     // the format string after this point, however, as we will like just get
8853     // gibberish when trying to match arguments.
8854     keepGoing = false;
8855   }
8856 
8857   StringRef Specifier(csStart, csLen);
8858 
8859   // If the specifier in non-printable, it could be the first byte of a UTF-8
8860   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8861   // hex value.
8862   std::string CodePointStr;
8863   if (!llvm::sys::locale::isPrint(*csStart)) {
8864     llvm::UTF32 CodePoint;
8865     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8866     const llvm::UTF8 *E =
8867         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8868     llvm::ConversionResult Result =
8869         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8870 
8871     if (Result != llvm::conversionOK) {
8872       unsigned char FirstChar = *csStart;
8873       CodePoint = (llvm::UTF32)FirstChar;
8874     }
8875 
8876     llvm::raw_string_ostream OS(CodePointStr);
8877     if (CodePoint < 256)
8878       OS << "\\x" << llvm::format("%02x", CodePoint);
8879     else if (CodePoint <= 0xFFFF)
8880       OS << "\\u" << llvm::format("%04x", CodePoint);
8881     else
8882       OS << "\\U" << llvm::format("%08x", CodePoint);
8883     OS.flush();
8884     Specifier = CodePointStr;
8885   }
8886 
8887   EmitFormatDiagnostic(
8888       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8889       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8890 
8891   return keepGoing;
8892 }
8893 
8894 void
8895 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8896                                                       const char *startSpec,
8897                                                       unsigned specifierLen) {
8898   EmitFormatDiagnostic(
8899     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8900     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8901 }
8902 
8903 bool
8904 CheckFormatHandler::CheckNumArgs(
8905   const analyze_format_string::FormatSpecifier &FS,
8906   const analyze_format_string::ConversionSpecifier &CS,
8907   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8908 
8909   if (argIndex >= NumDataArgs) {
8910     PartialDiagnostic PDiag = FS.usesPositionalArg()
8911       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8912            << (argIndex+1) << NumDataArgs)
8913       : S.PDiag(diag::warn_printf_insufficient_data_args);
8914     EmitFormatDiagnostic(
8915       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8916       getSpecifierRange(startSpecifier, specifierLen));
8917 
8918     // Since more arguments than conversion tokens are given, by extension
8919     // all arguments are covered, so mark this as so.
8920     UncoveredArg.setAllCovered();
8921     return false;
8922   }
8923   return true;
8924 }
8925 
8926 template<typename Range>
8927 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8928                                               SourceLocation Loc,
8929                                               bool IsStringLocation,
8930                                               Range StringRange,
8931                                               ArrayRef<FixItHint> FixIt) {
8932   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8933                        Loc, IsStringLocation, StringRange, FixIt);
8934 }
8935 
8936 /// If the format string is not within the function call, emit a note
8937 /// so that the function call and string are in diagnostic messages.
8938 ///
8939 /// \param InFunctionCall if true, the format string is within the function
8940 /// call and only one diagnostic message will be produced.  Otherwise, an
8941 /// extra note will be emitted pointing to location of the format string.
8942 ///
8943 /// \param ArgumentExpr the expression that is passed as the format string
8944 /// argument in the function call.  Used for getting locations when two
8945 /// diagnostics are emitted.
8946 ///
8947 /// \param PDiag the callee should already have provided any strings for the
8948 /// diagnostic message.  This function only adds locations and fixits
8949 /// to diagnostics.
8950 ///
8951 /// \param Loc primary location for diagnostic.  If two diagnostics are
8952 /// required, one will be at Loc and a new SourceLocation will be created for
8953 /// the other one.
8954 ///
8955 /// \param IsStringLocation if true, Loc points to the format string should be
8956 /// used for the note.  Otherwise, Loc points to the argument list and will
8957 /// be used with PDiag.
8958 ///
8959 /// \param StringRange some or all of the string to highlight.  This is
8960 /// templated so it can accept either a CharSourceRange or a SourceRange.
8961 ///
8962 /// \param FixIt optional fix it hint for the format string.
8963 template <typename Range>
8964 void CheckFormatHandler::EmitFormatDiagnostic(
8965     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8966     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8967     Range StringRange, ArrayRef<FixItHint> FixIt) {
8968   if (InFunctionCall) {
8969     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8970     D << StringRange;
8971     D << FixIt;
8972   } else {
8973     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8974       << ArgumentExpr->getSourceRange();
8975 
8976     const Sema::SemaDiagnosticBuilder &Note =
8977       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8978              diag::note_format_string_defined);
8979 
8980     Note << StringRange;
8981     Note << FixIt;
8982   }
8983 }
8984 
8985 //===--- CHECK: Printf format string checking ------------------------------===//
8986 
8987 namespace {
8988 
8989 class CheckPrintfHandler : public CheckFormatHandler {
8990 public:
8991   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8992                      const Expr *origFormatExpr,
8993                      const Sema::FormatStringType type, unsigned firstDataArg,
8994                      unsigned numDataArgs, bool isObjC, const char *beg,
8995                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8996                      unsigned formatIdx, bool inFunctionCall,
8997                      Sema::VariadicCallType CallType,
8998                      llvm::SmallBitVector &CheckedVarArgs,
8999                      UncoveredArgHandler &UncoveredArg)
9000       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9001                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9002                            inFunctionCall, CallType, CheckedVarArgs,
9003                            UncoveredArg) {}
9004 
9005   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
9006 
9007   /// Returns true if '%@' specifiers are allowed in the format string.
9008   bool allowsObjCArg() const {
9009     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
9010            FSType == Sema::FST_OSTrace;
9011   }
9012 
9013   bool HandleInvalidPrintfConversionSpecifier(
9014                                       const analyze_printf::PrintfSpecifier &FS,
9015                                       const char *startSpecifier,
9016                                       unsigned specifierLen) override;
9017 
9018   void handleInvalidMaskType(StringRef MaskType) override;
9019 
9020   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
9021                              const char *startSpecifier, unsigned specifierLen,
9022                              const TargetInfo &Target) override;
9023   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9024                        const char *StartSpecifier,
9025                        unsigned SpecifierLen,
9026                        const Expr *E);
9027 
9028   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
9029                     const char *startSpecifier, unsigned specifierLen);
9030   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
9031                            const analyze_printf::OptionalAmount &Amt,
9032                            unsigned type,
9033                            const char *startSpecifier, unsigned specifierLen);
9034   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
9035                   const analyze_printf::OptionalFlag &flag,
9036                   const char *startSpecifier, unsigned specifierLen);
9037   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
9038                          const analyze_printf::OptionalFlag &ignoredFlag,
9039                          const analyze_printf::OptionalFlag &flag,
9040                          const char *startSpecifier, unsigned specifierLen);
9041   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
9042                            const Expr *E);
9043 
9044   void HandleEmptyObjCModifierFlag(const char *startFlag,
9045                                    unsigned flagLen) override;
9046 
9047   void HandleInvalidObjCModifierFlag(const char *startFlag,
9048                                             unsigned flagLen) override;
9049 
9050   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
9051                                            const char *flagsEnd,
9052                                            const char *conversionPosition)
9053                                              override;
9054 };
9055 
9056 } // namespace
9057 
9058 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
9059                                       const analyze_printf::PrintfSpecifier &FS,
9060                                       const char *startSpecifier,
9061                                       unsigned specifierLen) {
9062   const analyze_printf::PrintfConversionSpecifier &CS =
9063     FS.getConversionSpecifier();
9064 
9065   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9066                                           getLocationOfByte(CS.getStart()),
9067                                           startSpecifier, specifierLen,
9068                                           CS.getStart(), CS.getLength());
9069 }
9070 
9071 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
9072   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
9073 }
9074 
9075 bool CheckPrintfHandler::HandleAmount(
9076                                const analyze_format_string::OptionalAmount &Amt,
9077                                unsigned k, const char *startSpecifier,
9078                                unsigned specifierLen) {
9079   if (Amt.hasDataArgument()) {
9080     if (!HasVAListArg) {
9081       unsigned argIndex = Amt.getArgIndex();
9082       if (argIndex >= NumDataArgs) {
9083         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
9084                                << k,
9085                              getLocationOfByte(Amt.getStart()),
9086                              /*IsStringLocation*/true,
9087                              getSpecifierRange(startSpecifier, specifierLen));
9088         // Don't do any more checking.  We will just emit
9089         // spurious errors.
9090         return false;
9091       }
9092 
9093       // Type check the data argument.  It should be an 'int'.
9094       // Although not in conformance with C99, we also allow the argument to be
9095       // an 'unsigned int' as that is a reasonably safe case.  GCC also
9096       // doesn't emit a warning for that case.
9097       CoveredArgs.set(argIndex);
9098       const Expr *Arg = getDataArg(argIndex);
9099       if (!Arg)
9100         return false;
9101 
9102       QualType T = Arg->getType();
9103 
9104       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
9105       assert(AT.isValid());
9106 
9107       if (!AT.matchesType(S.Context, T)) {
9108         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
9109                                << k << AT.getRepresentativeTypeName(S.Context)
9110                                << T << Arg->getSourceRange(),
9111                              getLocationOfByte(Amt.getStart()),
9112                              /*IsStringLocation*/true,
9113                              getSpecifierRange(startSpecifier, specifierLen));
9114         // Don't do any more checking.  We will just emit
9115         // spurious errors.
9116         return false;
9117       }
9118     }
9119   }
9120   return true;
9121 }
9122 
9123 void CheckPrintfHandler::HandleInvalidAmount(
9124                                       const analyze_printf::PrintfSpecifier &FS,
9125                                       const analyze_printf::OptionalAmount &Amt,
9126                                       unsigned type,
9127                                       const char *startSpecifier,
9128                                       unsigned specifierLen) {
9129   const analyze_printf::PrintfConversionSpecifier &CS =
9130     FS.getConversionSpecifier();
9131 
9132   FixItHint fixit =
9133     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
9134       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
9135                                  Amt.getConstantLength()))
9136       : FixItHint();
9137 
9138   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
9139                          << type << CS.toString(),
9140                        getLocationOfByte(Amt.getStart()),
9141                        /*IsStringLocation*/true,
9142                        getSpecifierRange(startSpecifier, specifierLen),
9143                        fixit);
9144 }
9145 
9146 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
9147                                     const analyze_printf::OptionalFlag &flag,
9148                                     const char *startSpecifier,
9149                                     unsigned specifierLen) {
9150   // Warn about pointless flag with a fixit removal.
9151   const analyze_printf::PrintfConversionSpecifier &CS =
9152     FS.getConversionSpecifier();
9153   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
9154                          << flag.toString() << CS.toString(),
9155                        getLocationOfByte(flag.getPosition()),
9156                        /*IsStringLocation*/true,
9157                        getSpecifierRange(startSpecifier, specifierLen),
9158                        FixItHint::CreateRemoval(
9159                          getSpecifierRange(flag.getPosition(), 1)));
9160 }
9161 
9162 void CheckPrintfHandler::HandleIgnoredFlag(
9163                                 const analyze_printf::PrintfSpecifier &FS,
9164                                 const analyze_printf::OptionalFlag &ignoredFlag,
9165                                 const analyze_printf::OptionalFlag &flag,
9166                                 const char *startSpecifier,
9167                                 unsigned specifierLen) {
9168   // Warn about ignored flag with a fixit removal.
9169   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
9170                          << ignoredFlag.toString() << flag.toString(),
9171                        getLocationOfByte(ignoredFlag.getPosition()),
9172                        /*IsStringLocation*/true,
9173                        getSpecifierRange(startSpecifier, specifierLen),
9174                        FixItHint::CreateRemoval(
9175                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
9176 }
9177 
9178 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
9179                                                      unsigned flagLen) {
9180   // Warn about an empty flag.
9181   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
9182                        getLocationOfByte(startFlag),
9183                        /*IsStringLocation*/true,
9184                        getSpecifierRange(startFlag, flagLen));
9185 }
9186 
9187 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
9188                                                        unsigned flagLen) {
9189   // Warn about an invalid flag.
9190   auto Range = getSpecifierRange(startFlag, flagLen);
9191   StringRef flag(startFlag, flagLen);
9192   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
9193                       getLocationOfByte(startFlag),
9194                       /*IsStringLocation*/true,
9195                       Range, FixItHint::CreateRemoval(Range));
9196 }
9197 
9198 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
9199     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
9200     // Warn about using '[...]' without a '@' conversion.
9201     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
9202     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
9203     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
9204                          getLocationOfByte(conversionPosition),
9205                          /*IsStringLocation*/true,
9206                          Range, FixItHint::CreateRemoval(Range));
9207 }
9208 
9209 // Determines if the specified is a C++ class or struct containing
9210 // a member with the specified name and kind (e.g. a CXXMethodDecl named
9211 // "c_str()").
9212 template<typename MemberKind>
9213 static llvm::SmallPtrSet<MemberKind*, 1>
9214 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9215   const RecordType *RT = Ty->getAs<RecordType>();
9216   llvm::SmallPtrSet<MemberKind*, 1> Results;
9217 
9218   if (!RT)
9219     return Results;
9220   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
9221   if (!RD || !RD->getDefinition())
9222     return Results;
9223 
9224   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9225                  Sema::LookupMemberName);
9226   R.suppressDiagnostics();
9227 
9228   // We just need to include all members of the right kind turned up by the
9229   // filter, at this point.
9230   if (S.LookupQualifiedName(R, RT->getDecl()))
9231     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9232       NamedDecl *decl = (*I)->getUnderlyingDecl();
9233       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9234         Results.insert(FK);
9235     }
9236   return Results;
9237 }
9238 
9239 /// Check if we could call '.c_str()' on an object.
9240 ///
9241 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9242 /// allow the call, or if it would be ambiguous).
9243 bool Sema::hasCStrMethod(const Expr *E) {
9244   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9245 
9246   MethodSet Results =
9247       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
9248   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9249        MI != ME; ++MI)
9250     if ((*MI)->getMinRequiredArguments() == 0)
9251       return true;
9252   return false;
9253 }
9254 
9255 // Check if a (w)string was passed when a (w)char* was needed, and offer a
9256 // better diagnostic if so. AT is assumed to be valid.
9257 // Returns true when a c_str() conversion method is found.
9258 bool CheckPrintfHandler::checkForCStrMembers(
9259     const analyze_printf::ArgType &AT, const Expr *E) {
9260   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9261 
9262   MethodSet Results =
9263       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
9264 
9265   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9266        MI != ME; ++MI) {
9267     const CXXMethodDecl *Method = *MI;
9268     if (Method->getMinRequiredArguments() == 0 &&
9269         AT.matchesType(S.Context, Method->getReturnType())) {
9270       // FIXME: Suggest parens if the expression needs them.
9271       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
9272       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
9273           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
9274       return true;
9275     }
9276   }
9277 
9278   return false;
9279 }
9280 
9281 bool CheckPrintfHandler::HandlePrintfSpecifier(
9282     const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9283     unsigned specifierLen, const TargetInfo &Target) {
9284   using namespace analyze_format_string;
9285   using namespace analyze_printf;
9286 
9287   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9288 
9289   if (FS.consumesDataArgument()) {
9290     if (atFirstArg) {
9291         atFirstArg = false;
9292         usesPositionalArgs = FS.usesPositionalArg();
9293     }
9294     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9295       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9296                                         startSpecifier, specifierLen);
9297       return false;
9298     }
9299   }
9300 
9301   // First check if the field width, precision, and conversion specifier
9302   // have matching data arguments.
9303   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
9304                     startSpecifier, specifierLen)) {
9305     return false;
9306   }
9307 
9308   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
9309                     startSpecifier, specifierLen)) {
9310     return false;
9311   }
9312 
9313   if (!CS.consumesDataArgument()) {
9314     // FIXME: Technically specifying a precision or field width here
9315     // makes no sense.  Worth issuing a warning at some point.
9316     return true;
9317   }
9318 
9319   // Consume the argument.
9320   unsigned argIndex = FS.getArgIndex();
9321   if (argIndex < NumDataArgs) {
9322     // The check to see if the argIndex is valid will come later.
9323     // We set the bit here because we may exit early from this
9324     // function if we encounter some other error.
9325     CoveredArgs.set(argIndex);
9326   }
9327 
9328   // FreeBSD kernel extensions.
9329   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9330       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9331     // We need at least two arguments.
9332     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9333       return false;
9334 
9335     // Claim the second argument.
9336     CoveredArgs.set(argIndex + 1);
9337 
9338     // Type check the first argument (int for %b, pointer for %D)
9339     const Expr *Ex = getDataArg(argIndex);
9340     const analyze_printf::ArgType &AT =
9341       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
9342         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
9343     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9344       EmitFormatDiagnostic(
9345           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9346               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9347               << false << Ex->getSourceRange(),
9348           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9349           getSpecifierRange(startSpecifier, specifierLen));
9350 
9351     // Type check the second argument (char * for both %b and %D)
9352     Ex = getDataArg(argIndex + 1);
9353     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
9354     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9355       EmitFormatDiagnostic(
9356           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9357               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9358               << false << Ex->getSourceRange(),
9359           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9360           getSpecifierRange(startSpecifier, specifierLen));
9361 
9362      return true;
9363   }
9364 
9365   // Check for using an Objective-C specific conversion specifier
9366   // in a non-ObjC literal.
9367   if (!allowsObjCArg() && CS.isObjCArg()) {
9368     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9369                                                   specifierLen);
9370   }
9371 
9372   // %P can only be used with os_log.
9373   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
9374     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9375                                                   specifierLen);
9376   }
9377 
9378   // %n is not allowed with os_log.
9379   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
9380     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9381                          getLocationOfByte(CS.getStart()),
9382                          /*IsStringLocation*/ false,
9383                          getSpecifierRange(startSpecifier, specifierLen));
9384 
9385     return true;
9386   }
9387 
9388   // Only scalars are allowed for os_trace.
9389   if (FSType == Sema::FST_OSTrace &&
9390       (CS.getKind() == ConversionSpecifier::PArg ||
9391        CS.getKind() == ConversionSpecifier::sArg ||
9392        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9393     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9394                                                   specifierLen);
9395   }
9396 
9397   // Check for use of public/private annotation outside of os_log().
9398   if (FSType != Sema::FST_OSLog) {
9399     if (FS.isPublic().isSet()) {
9400       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9401                                << "public",
9402                            getLocationOfByte(FS.isPublic().getPosition()),
9403                            /*IsStringLocation*/ false,
9404                            getSpecifierRange(startSpecifier, specifierLen));
9405     }
9406     if (FS.isPrivate().isSet()) {
9407       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9408                                << "private",
9409                            getLocationOfByte(FS.isPrivate().getPosition()),
9410                            /*IsStringLocation*/ false,
9411                            getSpecifierRange(startSpecifier, specifierLen));
9412     }
9413   }
9414 
9415   const llvm::Triple &Triple = Target.getTriple();
9416   if (CS.getKind() == ConversionSpecifier::nArg &&
9417       (Triple.isAndroid() || Triple.isOSFuchsia())) {
9418     EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
9419                          getLocationOfByte(CS.getStart()),
9420                          /*IsStringLocation*/ false,
9421                          getSpecifierRange(startSpecifier, specifierLen));
9422   }
9423 
9424   // Check for invalid use of field width
9425   if (!FS.hasValidFieldWidth()) {
9426     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9427         startSpecifier, specifierLen);
9428   }
9429 
9430   // Check for invalid use of precision
9431   if (!FS.hasValidPrecision()) {
9432     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9433         startSpecifier, specifierLen);
9434   }
9435 
9436   // Precision is mandatory for %P specifier.
9437   if (CS.getKind() == ConversionSpecifier::PArg &&
9438       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9439     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9440                          getLocationOfByte(startSpecifier),
9441                          /*IsStringLocation*/ false,
9442                          getSpecifierRange(startSpecifier, specifierLen));
9443   }
9444 
9445   // Check each flag does not conflict with any other component.
9446   if (!FS.hasValidThousandsGroupingPrefix())
9447     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9448   if (!FS.hasValidLeadingZeros())
9449     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9450   if (!FS.hasValidPlusPrefix())
9451     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9452   if (!FS.hasValidSpacePrefix())
9453     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9454   if (!FS.hasValidAlternativeForm())
9455     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9456   if (!FS.hasValidLeftJustified())
9457     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9458 
9459   // Check that flags are not ignored by another flag
9460   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9461     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9462         startSpecifier, specifierLen);
9463   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9464     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9465             startSpecifier, specifierLen);
9466 
9467   // Check the length modifier is valid with the given conversion specifier.
9468   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9469                                  S.getLangOpts()))
9470     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9471                                 diag::warn_format_nonsensical_length);
9472   else if (!FS.hasStandardLengthModifier())
9473     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9474   else if (!FS.hasStandardLengthConversionCombination())
9475     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9476                                 diag::warn_format_non_standard_conversion_spec);
9477 
9478   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9479     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9480 
9481   // The remaining checks depend on the data arguments.
9482   if (HasVAListArg)
9483     return true;
9484 
9485   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9486     return false;
9487 
9488   const Expr *Arg = getDataArg(argIndex);
9489   if (!Arg)
9490     return true;
9491 
9492   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9493 }
9494 
9495 static bool requiresParensToAddCast(const Expr *E) {
9496   // FIXME: We should have a general way to reason about operator
9497   // precedence and whether parens are actually needed here.
9498   // Take care of a few common cases where they aren't.
9499   const Expr *Inside = E->IgnoreImpCasts();
9500   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9501     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9502 
9503   switch (Inside->getStmtClass()) {
9504   case Stmt::ArraySubscriptExprClass:
9505   case Stmt::CallExprClass:
9506   case Stmt::CharacterLiteralClass:
9507   case Stmt::CXXBoolLiteralExprClass:
9508   case Stmt::DeclRefExprClass:
9509   case Stmt::FloatingLiteralClass:
9510   case Stmt::IntegerLiteralClass:
9511   case Stmt::MemberExprClass:
9512   case Stmt::ObjCArrayLiteralClass:
9513   case Stmt::ObjCBoolLiteralExprClass:
9514   case Stmt::ObjCBoxedExprClass:
9515   case Stmt::ObjCDictionaryLiteralClass:
9516   case Stmt::ObjCEncodeExprClass:
9517   case Stmt::ObjCIvarRefExprClass:
9518   case Stmt::ObjCMessageExprClass:
9519   case Stmt::ObjCPropertyRefExprClass:
9520   case Stmt::ObjCStringLiteralClass:
9521   case Stmt::ObjCSubscriptRefExprClass:
9522   case Stmt::ParenExprClass:
9523   case Stmt::StringLiteralClass:
9524   case Stmt::UnaryOperatorClass:
9525     return false;
9526   default:
9527     return true;
9528   }
9529 }
9530 
9531 static std::pair<QualType, StringRef>
9532 shouldNotPrintDirectly(const ASTContext &Context,
9533                        QualType IntendedTy,
9534                        const Expr *E) {
9535   // Use a 'while' to peel off layers of typedefs.
9536   QualType TyTy = IntendedTy;
9537   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9538     StringRef Name = UserTy->getDecl()->getName();
9539     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9540       .Case("CFIndex", Context.getNSIntegerType())
9541       .Case("NSInteger", Context.getNSIntegerType())
9542       .Case("NSUInteger", Context.getNSUIntegerType())
9543       .Case("SInt32", Context.IntTy)
9544       .Case("UInt32", Context.UnsignedIntTy)
9545       .Default(QualType());
9546 
9547     if (!CastTy.isNull())
9548       return std::make_pair(CastTy, Name);
9549 
9550     TyTy = UserTy->desugar();
9551   }
9552 
9553   // Strip parens if necessary.
9554   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9555     return shouldNotPrintDirectly(Context,
9556                                   PE->getSubExpr()->getType(),
9557                                   PE->getSubExpr());
9558 
9559   // If this is a conditional expression, then its result type is constructed
9560   // via usual arithmetic conversions and thus there might be no necessary
9561   // typedef sugar there.  Recurse to operands to check for NSInteger &
9562   // Co. usage condition.
9563   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9564     QualType TrueTy, FalseTy;
9565     StringRef TrueName, FalseName;
9566 
9567     std::tie(TrueTy, TrueName) =
9568       shouldNotPrintDirectly(Context,
9569                              CO->getTrueExpr()->getType(),
9570                              CO->getTrueExpr());
9571     std::tie(FalseTy, FalseName) =
9572       shouldNotPrintDirectly(Context,
9573                              CO->getFalseExpr()->getType(),
9574                              CO->getFalseExpr());
9575 
9576     if (TrueTy == FalseTy)
9577       return std::make_pair(TrueTy, TrueName);
9578     else if (TrueTy.isNull())
9579       return std::make_pair(FalseTy, FalseName);
9580     else if (FalseTy.isNull())
9581       return std::make_pair(TrueTy, TrueName);
9582   }
9583 
9584   return std::make_pair(QualType(), StringRef());
9585 }
9586 
9587 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9588 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9589 /// type do not count.
9590 static bool
9591 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9592   QualType From = ICE->getSubExpr()->getType();
9593   QualType To = ICE->getType();
9594   // It's an integer promotion if the destination type is the promoted
9595   // source type.
9596   if (ICE->getCastKind() == CK_IntegralCast &&
9597       From->isPromotableIntegerType() &&
9598       S.Context.getPromotedIntegerType(From) == To)
9599     return true;
9600   // Look through vector types, since we do default argument promotion for
9601   // those in OpenCL.
9602   if (const auto *VecTy = From->getAs<ExtVectorType>())
9603     From = VecTy->getElementType();
9604   if (const auto *VecTy = To->getAs<ExtVectorType>())
9605     To = VecTy->getElementType();
9606   // It's a floating promotion if the source type is a lower rank.
9607   return ICE->getCastKind() == CK_FloatingCast &&
9608          S.Context.getFloatingTypeOrder(From, To) < 0;
9609 }
9610 
9611 bool
9612 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9613                                     const char *StartSpecifier,
9614                                     unsigned SpecifierLen,
9615                                     const Expr *E) {
9616   using namespace analyze_format_string;
9617   using namespace analyze_printf;
9618 
9619   // Now type check the data expression that matches the
9620   // format specifier.
9621   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9622   if (!AT.isValid())
9623     return true;
9624 
9625   QualType ExprTy = E->getType();
9626   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9627     ExprTy = TET->getUnderlyingExpr()->getType();
9628   }
9629 
9630   // Diagnose attempts to print a boolean value as a character. Unlike other
9631   // -Wformat diagnostics, this is fine from a type perspective, but it still
9632   // doesn't make sense.
9633   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9634       E->isKnownToHaveBooleanValue()) {
9635     const CharSourceRange &CSR =
9636         getSpecifierRange(StartSpecifier, SpecifierLen);
9637     SmallString<4> FSString;
9638     llvm::raw_svector_ostream os(FSString);
9639     FS.toString(os);
9640     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9641                              << FSString,
9642                          E->getExprLoc(), false, CSR);
9643     return true;
9644   }
9645 
9646   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9647   if (Match == analyze_printf::ArgType::Match)
9648     return true;
9649 
9650   // Look through argument promotions for our error message's reported type.
9651   // This includes the integral and floating promotions, but excludes array
9652   // and function pointer decay (seeing that an argument intended to be a
9653   // string has type 'char [6]' is probably more confusing than 'char *') and
9654   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9655   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9656     if (isArithmeticArgumentPromotion(S, ICE)) {
9657       E = ICE->getSubExpr();
9658       ExprTy = E->getType();
9659 
9660       // Check if we didn't match because of an implicit cast from a 'char'
9661       // or 'short' to an 'int'.  This is done because printf is a varargs
9662       // function.
9663       if (ICE->getType() == S.Context.IntTy ||
9664           ICE->getType() == S.Context.UnsignedIntTy) {
9665         // All further checking is done on the subexpression
9666         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9667             AT.matchesType(S.Context, ExprTy);
9668         if (ImplicitMatch == analyze_printf::ArgType::Match)
9669           return true;
9670         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9671             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9672           Match = ImplicitMatch;
9673       }
9674     }
9675   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9676     // Special case for 'a', which has type 'int' in C.
9677     // Note, however, that we do /not/ want to treat multibyte constants like
9678     // 'MooV' as characters! This form is deprecated but still exists. In
9679     // addition, don't treat expressions as of type 'char' if one byte length
9680     // modifier is provided.
9681     if (ExprTy == S.Context.IntTy &&
9682         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9683       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9684         ExprTy = S.Context.CharTy;
9685   }
9686 
9687   // Look through enums to their underlying type.
9688   bool IsEnum = false;
9689   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9690     ExprTy = EnumTy->getDecl()->getIntegerType();
9691     IsEnum = true;
9692   }
9693 
9694   // %C in an Objective-C context prints a unichar, not a wchar_t.
9695   // If the argument is an integer of some kind, believe the %C and suggest
9696   // a cast instead of changing the conversion specifier.
9697   QualType IntendedTy = ExprTy;
9698   if (isObjCContext() &&
9699       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9700     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9701         !ExprTy->isCharType()) {
9702       // 'unichar' is defined as a typedef of unsigned short, but we should
9703       // prefer using the typedef if it is visible.
9704       IntendedTy = S.Context.UnsignedShortTy;
9705 
9706       // While we are here, check if the value is an IntegerLiteral that happens
9707       // to be within the valid range.
9708       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9709         const llvm::APInt &V = IL->getValue();
9710         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9711           return true;
9712       }
9713 
9714       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9715                           Sema::LookupOrdinaryName);
9716       if (S.LookupName(Result, S.getCurScope())) {
9717         NamedDecl *ND = Result.getFoundDecl();
9718         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9719           if (TD->getUnderlyingType() == IntendedTy)
9720             IntendedTy = S.Context.getTypedefType(TD);
9721       }
9722     }
9723   }
9724 
9725   // Special-case some of Darwin's platform-independence types by suggesting
9726   // casts to primitive types that are known to be large enough.
9727   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9728   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9729     QualType CastTy;
9730     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9731     if (!CastTy.isNull()) {
9732       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9733       // (long in ASTContext). Only complain to pedants.
9734       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9735           (AT.isSizeT() || AT.isPtrdiffT()) &&
9736           AT.matchesType(S.Context, CastTy))
9737         Match = ArgType::NoMatchPedantic;
9738       IntendedTy = CastTy;
9739       ShouldNotPrintDirectly = true;
9740     }
9741   }
9742 
9743   // We may be able to offer a FixItHint if it is a supported type.
9744   PrintfSpecifier fixedFS = FS;
9745   bool Success =
9746       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9747 
9748   if (Success) {
9749     // Get the fix string from the fixed format specifier
9750     SmallString<16> buf;
9751     llvm::raw_svector_ostream os(buf);
9752     fixedFS.toString(os);
9753 
9754     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9755 
9756     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9757       unsigned Diag;
9758       switch (Match) {
9759       case ArgType::Match: llvm_unreachable("expected non-matching");
9760       case ArgType::NoMatchPedantic:
9761         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9762         break;
9763       case ArgType::NoMatchTypeConfusion:
9764         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9765         break;
9766       case ArgType::NoMatch:
9767         Diag = diag::warn_format_conversion_argument_type_mismatch;
9768         break;
9769       }
9770 
9771       // In this case, the specifier is wrong and should be changed to match
9772       // the argument.
9773       EmitFormatDiagnostic(S.PDiag(Diag)
9774                                << AT.getRepresentativeTypeName(S.Context)
9775                                << IntendedTy << IsEnum << E->getSourceRange(),
9776                            E->getBeginLoc(),
9777                            /*IsStringLocation*/ false, SpecRange,
9778                            FixItHint::CreateReplacement(SpecRange, os.str()));
9779     } else {
9780       // The canonical type for formatting this value is different from the
9781       // actual type of the expression. (This occurs, for example, with Darwin's
9782       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9783       // should be printed as 'long' for 64-bit compatibility.)
9784       // Rather than emitting a normal format/argument mismatch, we want to
9785       // add a cast to the recommended type (and correct the format string
9786       // if necessary).
9787       SmallString<16> CastBuf;
9788       llvm::raw_svector_ostream CastFix(CastBuf);
9789       CastFix << "(";
9790       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9791       CastFix << ")";
9792 
9793       SmallVector<FixItHint,4> Hints;
9794       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9795         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9796 
9797       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9798         // If there's already a cast present, just replace it.
9799         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9800         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9801 
9802       } else if (!requiresParensToAddCast(E)) {
9803         // If the expression has high enough precedence,
9804         // just write the C-style cast.
9805         Hints.push_back(
9806             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9807       } else {
9808         // Otherwise, add parens around the expression as well as the cast.
9809         CastFix << "(";
9810         Hints.push_back(
9811             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9812 
9813         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9814         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9815       }
9816 
9817       if (ShouldNotPrintDirectly) {
9818         // The expression has a type that should not be printed directly.
9819         // We extract the name from the typedef because we don't want to show
9820         // the underlying type in the diagnostic.
9821         StringRef Name;
9822         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9823           Name = TypedefTy->getDecl()->getName();
9824         else
9825           Name = CastTyName;
9826         unsigned Diag = Match == ArgType::NoMatchPedantic
9827                             ? diag::warn_format_argument_needs_cast_pedantic
9828                             : diag::warn_format_argument_needs_cast;
9829         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9830                                            << E->getSourceRange(),
9831                              E->getBeginLoc(), /*IsStringLocation=*/false,
9832                              SpecRange, Hints);
9833       } else {
9834         // In this case, the expression could be printed using a different
9835         // specifier, but we've decided that the specifier is probably correct
9836         // and we should cast instead. Just use the normal warning message.
9837         EmitFormatDiagnostic(
9838             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9839                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9840                 << E->getSourceRange(),
9841             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9842       }
9843     }
9844   } else {
9845     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9846                                                    SpecifierLen);
9847     // Since the warning for passing non-POD types to variadic functions
9848     // was deferred until now, we emit a warning for non-POD
9849     // arguments here.
9850     switch (S.isValidVarArgType(ExprTy)) {
9851     case Sema::VAK_Valid:
9852     case Sema::VAK_ValidInCXX11: {
9853       unsigned Diag;
9854       switch (Match) {
9855       case ArgType::Match: llvm_unreachable("expected non-matching");
9856       case ArgType::NoMatchPedantic:
9857         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9858         break;
9859       case ArgType::NoMatchTypeConfusion:
9860         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9861         break;
9862       case ArgType::NoMatch:
9863         Diag = diag::warn_format_conversion_argument_type_mismatch;
9864         break;
9865       }
9866 
9867       EmitFormatDiagnostic(
9868           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9869                         << IsEnum << CSR << E->getSourceRange(),
9870           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9871       break;
9872     }
9873     case Sema::VAK_Undefined:
9874     case Sema::VAK_MSVCUndefined:
9875       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9876                                << S.getLangOpts().CPlusPlus11 << ExprTy
9877                                << CallType
9878                                << AT.getRepresentativeTypeName(S.Context) << CSR
9879                                << E->getSourceRange(),
9880                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9881       checkForCStrMembers(AT, E);
9882       break;
9883 
9884     case Sema::VAK_Invalid:
9885       if (ExprTy->isObjCObjectType())
9886         EmitFormatDiagnostic(
9887             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9888                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9889                 << AT.getRepresentativeTypeName(S.Context) << CSR
9890                 << E->getSourceRange(),
9891             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9892       else
9893         // FIXME: If this is an initializer list, suggest removing the braces
9894         // or inserting a cast to the target type.
9895         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9896             << isa<InitListExpr>(E) << ExprTy << CallType
9897             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9898       break;
9899     }
9900 
9901     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9902            "format string specifier index out of range");
9903     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9904   }
9905 
9906   return true;
9907 }
9908 
9909 //===--- CHECK: Scanf format string checking ------------------------------===//
9910 
9911 namespace {
9912 
9913 class CheckScanfHandler : public CheckFormatHandler {
9914 public:
9915   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9916                     const Expr *origFormatExpr, Sema::FormatStringType type,
9917                     unsigned firstDataArg, unsigned numDataArgs,
9918                     const char *beg, bool hasVAListArg,
9919                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9920                     bool inFunctionCall, Sema::VariadicCallType CallType,
9921                     llvm::SmallBitVector &CheckedVarArgs,
9922                     UncoveredArgHandler &UncoveredArg)
9923       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9924                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9925                            inFunctionCall, CallType, CheckedVarArgs,
9926                            UncoveredArg) {}
9927 
9928   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9929                             const char *startSpecifier,
9930                             unsigned specifierLen) override;
9931 
9932   bool HandleInvalidScanfConversionSpecifier(
9933           const analyze_scanf::ScanfSpecifier &FS,
9934           const char *startSpecifier,
9935           unsigned specifierLen) override;
9936 
9937   void HandleIncompleteScanList(const char *start, const char *end) override;
9938 };
9939 
9940 } // namespace
9941 
9942 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9943                                                  const char *end) {
9944   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9945                        getLocationOfByte(end), /*IsStringLocation*/true,
9946                        getSpecifierRange(start, end - start));
9947 }
9948 
9949 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9950                                         const analyze_scanf::ScanfSpecifier &FS,
9951                                         const char *startSpecifier,
9952                                         unsigned specifierLen) {
9953   const analyze_scanf::ScanfConversionSpecifier &CS =
9954     FS.getConversionSpecifier();
9955 
9956   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9957                                           getLocationOfByte(CS.getStart()),
9958                                           startSpecifier, specifierLen,
9959                                           CS.getStart(), CS.getLength());
9960 }
9961 
9962 bool CheckScanfHandler::HandleScanfSpecifier(
9963                                        const analyze_scanf::ScanfSpecifier &FS,
9964                                        const char *startSpecifier,
9965                                        unsigned specifierLen) {
9966   using namespace analyze_scanf;
9967   using namespace analyze_format_string;
9968 
9969   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9970 
9971   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9972   // be used to decide if we are using positional arguments consistently.
9973   if (FS.consumesDataArgument()) {
9974     if (atFirstArg) {
9975       atFirstArg = false;
9976       usesPositionalArgs = FS.usesPositionalArg();
9977     }
9978     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9979       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9980                                         startSpecifier, specifierLen);
9981       return false;
9982     }
9983   }
9984 
9985   // Check if the field with is non-zero.
9986   const OptionalAmount &Amt = FS.getFieldWidth();
9987   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9988     if (Amt.getConstantAmount() == 0) {
9989       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9990                                                    Amt.getConstantLength());
9991       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9992                            getLocationOfByte(Amt.getStart()),
9993                            /*IsStringLocation*/true, R,
9994                            FixItHint::CreateRemoval(R));
9995     }
9996   }
9997 
9998   if (!FS.consumesDataArgument()) {
9999     // FIXME: Technically specifying a precision or field width here
10000     // makes no sense.  Worth issuing a warning at some point.
10001     return true;
10002   }
10003 
10004   // Consume the argument.
10005   unsigned argIndex = FS.getArgIndex();
10006   if (argIndex < NumDataArgs) {
10007       // The check to see if the argIndex is valid will come later.
10008       // We set the bit here because we may exit early from this
10009       // function if we encounter some other error.
10010     CoveredArgs.set(argIndex);
10011   }
10012 
10013   // Check the length modifier is valid with the given conversion specifier.
10014   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
10015                                  S.getLangOpts()))
10016     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10017                                 diag::warn_format_nonsensical_length);
10018   else if (!FS.hasStandardLengthModifier())
10019     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
10020   else if (!FS.hasStandardLengthConversionCombination())
10021     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10022                                 diag::warn_format_non_standard_conversion_spec);
10023 
10024   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
10025     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
10026 
10027   // The remaining checks depend on the data arguments.
10028   if (HasVAListArg)
10029     return true;
10030 
10031   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
10032     return false;
10033 
10034   // Check that the argument type matches the format specifier.
10035   const Expr *Ex = getDataArg(argIndex);
10036   if (!Ex)
10037     return true;
10038 
10039   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
10040 
10041   if (!AT.isValid()) {
10042     return true;
10043   }
10044 
10045   analyze_format_string::ArgType::MatchKind Match =
10046       AT.matchesType(S.Context, Ex->getType());
10047   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
10048   if (Match == analyze_format_string::ArgType::Match)
10049     return true;
10050 
10051   ScanfSpecifier fixedFS = FS;
10052   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
10053                                  S.getLangOpts(), S.Context);
10054 
10055   unsigned Diag =
10056       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
10057                : diag::warn_format_conversion_argument_type_mismatch;
10058 
10059   if (Success) {
10060     // Get the fix string from the fixed format specifier.
10061     SmallString<128> buf;
10062     llvm::raw_svector_ostream os(buf);
10063     fixedFS.toString(os);
10064 
10065     EmitFormatDiagnostic(
10066         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
10067                       << Ex->getType() << false << Ex->getSourceRange(),
10068         Ex->getBeginLoc(),
10069         /*IsStringLocation*/ false,
10070         getSpecifierRange(startSpecifier, specifierLen),
10071         FixItHint::CreateReplacement(
10072             getSpecifierRange(startSpecifier, specifierLen), os.str()));
10073   } else {
10074     EmitFormatDiagnostic(S.PDiag(Diag)
10075                              << AT.getRepresentativeTypeName(S.Context)
10076                              << Ex->getType() << false << Ex->getSourceRange(),
10077                          Ex->getBeginLoc(),
10078                          /*IsStringLocation*/ false,
10079                          getSpecifierRange(startSpecifier, specifierLen));
10080   }
10081 
10082   return true;
10083 }
10084 
10085 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
10086                               const Expr *OrigFormatExpr,
10087                               ArrayRef<const Expr *> Args,
10088                               bool HasVAListArg, unsigned format_idx,
10089                               unsigned firstDataArg,
10090                               Sema::FormatStringType Type,
10091                               bool inFunctionCall,
10092                               Sema::VariadicCallType CallType,
10093                               llvm::SmallBitVector &CheckedVarArgs,
10094                               UncoveredArgHandler &UncoveredArg,
10095                               bool IgnoreStringsWithoutSpecifiers) {
10096   // CHECK: is the format string a wide literal?
10097   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
10098     CheckFormatHandler::EmitFormatDiagnostic(
10099         S, inFunctionCall, Args[format_idx],
10100         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
10101         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10102     return;
10103   }
10104 
10105   // Str - The format string.  NOTE: this is NOT null-terminated!
10106   StringRef StrRef = FExpr->getString();
10107   const char *Str = StrRef.data();
10108   // Account for cases where the string literal is truncated in a declaration.
10109   const ConstantArrayType *T =
10110     S.Context.getAsConstantArrayType(FExpr->getType());
10111   assert(T && "String literal not of constant array type!");
10112   size_t TypeSize = T->getSize().getZExtValue();
10113   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10114   const unsigned numDataArgs = Args.size() - firstDataArg;
10115 
10116   if (IgnoreStringsWithoutSpecifiers &&
10117       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
10118           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10119     return;
10120 
10121   // Emit a warning if the string literal is truncated and does not contain an
10122   // embedded null character.
10123   if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
10124     CheckFormatHandler::EmitFormatDiagnostic(
10125         S, inFunctionCall, Args[format_idx],
10126         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
10127         FExpr->getBeginLoc(),
10128         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
10129     return;
10130   }
10131 
10132   // CHECK: empty format string?
10133   if (StrLen == 0 && numDataArgs > 0) {
10134     CheckFormatHandler::EmitFormatDiagnostic(
10135         S, inFunctionCall, Args[format_idx],
10136         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
10137         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10138     return;
10139   }
10140 
10141   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
10142       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
10143       Type == Sema::FST_OSTrace) {
10144     CheckPrintfHandler H(
10145         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
10146         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
10147         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
10148         CheckedVarArgs, UncoveredArg);
10149 
10150     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
10151                                                   S.getLangOpts(),
10152                                                   S.Context.getTargetInfo(),
10153                                             Type == Sema::FST_FreeBSDKPrintf))
10154       H.DoneProcessing();
10155   } else if (Type == Sema::FST_Scanf) {
10156     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10157                         numDataArgs, Str, HasVAListArg, Args, format_idx,
10158                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
10159 
10160     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
10161                                                  S.getLangOpts(),
10162                                                  S.Context.getTargetInfo()))
10163       H.DoneProcessing();
10164   } // TODO: handle other formats
10165 }
10166 
10167 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
10168   // Str - The format string.  NOTE: this is NOT null-terminated!
10169   StringRef StrRef = FExpr->getString();
10170   const char *Str = StrRef.data();
10171   // Account for cases where the string literal is truncated in a declaration.
10172   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
10173   assert(T && "String literal not of constant array type!");
10174   size_t TypeSize = T->getSize().getZExtValue();
10175   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10176   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
10177                                                          getLangOpts(),
10178                                                          Context.getTargetInfo());
10179 }
10180 
10181 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10182 
10183 // Returns the related absolute value function that is larger, of 0 if one
10184 // does not exist.
10185 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10186   switch (AbsFunction) {
10187   default:
10188     return 0;
10189 
10190   case Builtin::BI__builtin_abs:
10191     return Builtin::BI__builtin_labs;
10192   case Builtin::BI__builtin_labs:
10193     return Builtin::BI__builtin_llabs;
10194   case Builtin::BI__builtin_llabs:
10195     return 0;
10196 
10197   case Builtin::BI__builtin_fabsf:
10198     return Builtin::BI__builtin_fabs;
10199   case Builtin::BI__builtin_fabs:
10200     return Builtin::BI__builtin_fabsl;
10201   case Builtin::BI__builtin_fabsl:
10202     return 0;
10203 
10204   case Builtin::BI__builtin_cabsf:
10205     return Builtin::BI__builtin_cabs;
10206   case Builtin::BI__builtin_cabs:
10207     return Builtin::BI__builtin_cabsl;
10208   case Builtin::BI__builtin_cabsl:
10209     return 0;
10210 
10211   case Builtin::BIabs:
10212     return Builtin::BIlabs;
10213   case Builtin::BIlabs:
10214     return Builtin::BIllabs;
10215   case Builtin::BIllabs:
10216     return 0;
10217 
10218   case Builtin::BIfabsf:
10219     return Builtin::BIfabs;
10220   case Builtin::BIfabs:
10221     return Builtin::BIfabsl;
10222   case Builtin::BIfabsl:
10223     return 0;
10224 
10225   case Builtin::BIcabsf:
10226    return Builtin::BIcabs;
10227   case Builtin::BIcabs:
10228     return Builtin::BIcabsl;
10229   case Builtin::BIcabsl:
10230     return 0;
10231   }
10232 }
10233 
10234 // Returns the argument type of the absolute value function.
10235 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
10236                                              unsigned AbsType) {
10237   if (AbsType == 0)
10238     return QualType();
10239 
10240   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
10241   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10242   if (Error != ASTContext::GE_None)
10243     return QualType();
10244 
10245   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
10246   if (!FT)
10247     return QualType();
10248 
10249   if (FT->getNumParams() != 1)
10250     return QualType();
10251 
10252   return FT->getParamType(0);
10253 }
10254 
10255 // Returns the best absolute value function, or zero, based on type and
10256 // current absolute value function.
10257 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10258                                    unsigned AbsFunctionKind) {
10259   unsigned BestKind = 0;
10260   uint64_t ArgSize = Context.getTypeSize(ArgType);
10261   for (unsigned Kind = AbsFunctionKind; Kind != 0;
10262        Kind = getLargerAbsoluteValueFunction(Kind)) {
10263     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10264     if (Context.getTypeSize(ParamType) >= ArgSize) {
10265       if (BestKind == 0)
10266         BestKind = Kind;
10267       else if (Context.hasSameType(ParamType, ArgType)) {
10268         BestKind = Kind;
10269         break;
10270       }
10271     }
10272   }
10273   return BestKind;
10274 }
10275 
10276 enum AbsoluteValueKind {
10277   AVK_Integer,
10278   AVK_Floating,
10279   AVK_Complex
10280 };
10281 
10282 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
10283   if (T->isIntegralOrEnumerationType())
10284     return AVK_Integer;
10285   if (T->isRealFloatingType())
10286     return AVK_Floating;
10287   if (T->isAnyComplexType())
10288     return AVK_Complex;
10289 
10290   llvm_unreachable("Type not integer, floating, or complex");
10291 }
10292 
10293 // Changes the absolute value function to a different type.  Preserves whether
10294 // the function is a builtin.
10295 static unsigned changeAbsFunction(unsigned AbsKind,
10296                                   AbsoluteValueKind ValueKind) {
10297   switch (ValueKind) {
10298   case AVK_Integer:
10299     switch (AbsKind) {
10300     default:
10301       return 0;
10302     case Builtin::BI__builtin_fabsf:
10303     case Builtin::BI__builtin_fabs:
10304     case Builtin::BI__builtin_fabsl:
10305     case Builtin::BI__builtin_cabsf:
10306     case Builtin::BI__builtin_cabs:
10307     case Builtin::BI__builtin_cabsl:
10308       return Builtin::BI__builtin_abs;
10309     case Builtin::BIfabsf:
10310     case Builtin::BIfabs:
10311     case Builtin::BIfabsl:
10312     case Builtin::BIcabsf:
10313     case Builtin::BIcabs:
10314     case Builtin::BIcabsl:
10315       return Builtin::BIabs;
10316     }
10317   case AVK_Floating:
10318     switch (AbsKind) {
10319     default:
10320       return 0;
10321     case Builtin::BI__builtin_abs:
10322     case Builtin::BI__builtin_labs:
10323     case Builtin::BI__builtin_llabs:
10324     case Builtin::BI__builtin_cabsf:
10325     case Builtin::BI__builtin_cabs:
10326     case Builtin::BI__builtin_cabsl:
10327       return Builtin::BI__builtin_fabsf;
10328     case Builtin::BIabs:
10329     case Builtin::BIlabs:
10330     case Builtin::BIllabs:
10331     case Builtin::BIcabsf:
10332     case Builtin::BIcabs:
10333     case Builtin::BIcabsl:
10334       return Builtin::BIfabsf;
10335     }
10336   case AVK_Complex:
10337     switch (AbsKind) {
10338     default:
10339       return 0;
10340     case Builtin::BI__builtin_abs:
10341     case Builtin::BI__builtin_labs:
10342     case Builtin::BI__builtin_llabs:
10343     case Builtin::BI__builtin_fabsf:
10344     case Builtin::BI__builtin_fabs:
10345     case Builtin::BI__builtin_fabsl:
10346       return Builtin::BI__builtin_cabsf;
10347     case Builtin::BIabs:
10348     case Builtin::BIlabs:
10349     case Builtin::BIllabs:
10350     case Builtin::BIfabsf:
10351     case Builtin::BIfabs:
10352     case Builtin::BIfabsl:
10353       return Builtin::BIcabsf;
10354     }
10355   }
10356   llvm_unreachable("Unable to convert function");
10357 }
10358 
10359 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10360   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10361   if (!FnInfo)
10362     return 0;
10363 
10364   switch (FDecl->getBuiltinID()) {
10365   default:
10366     return 0;
10367   case Builtin::BI__builtin_abs:
10368   case Builtin::BI__builtin_fabs:
10369   case Builtin::BI__builtin_fabsf:
10370   case Builtin::BI__builtin_fabsl:
10371   case Builtin::BI__builtin_labs:
10372   case Builtin::BI__builtin_llabs:
10373   case Builtin::BI__builtin_cabs:
10374   case Builtin::BI__builtin_cabsf:
10375   case Builtin::BI__builtin_cabsl:
10376   case Builtin::BIabs:
10377   case Builtin::BIlabs:
10378   case Builtin::BIllabs:
10379   case Builtin::BIfabs:
10380   case Builtin::BIfabsf:
10381   case Builtin::BIfabsl:
10382   case Builtin::BIcabs:
10383   case Builtin::BIcabsf:
10384   case Builtin::BIcabsl:
10385     return FDecl->getBuiltinID();
10386   }
10387   llvm_unreachable("Unknown Builtin type");
10388 }
10389 
10390 // If the replacement is valid, emit a note with replacement function.
10391 // Additionally, suggest including the proper header if not already included.
10392 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10393                             unsigned AbsKind, QualType ArgType) {
10394   bool EmitHeaderHint = true;
10395   const char *HeaderName = nullptr;
10396   const char *FunctionName = nullptr;
10397   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10398     FunctionName = "std::abs";
10399     if (ArgType->isIntegralOrEnumerationType()) {
10400       HeaderName = "cstdlib";
10401     } else if (ArgType->isRealFloatingType()) {
10402       HeaderName = "cmath";
10403     } else {
10404       llvm_unreachable("Invalid Type");
10405     }
10406 
10407     // Lookup all std::abs
10408     if (NamespaceDecl *Std = S.getStdNamespace()) {
10409       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10410       R.suppressDiagnostics();
10411       S.LookupQualifiedName(R, Std);
10412 
10413       for (const auto *I : R) {
10414         const FunctionDecl *FDecl = nullptr;
10415         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10416           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10417         } else {
10418           FDecl = dyn_cast<FunctionDecl>(I);
10419         }
10420         if (!FDecl)
10421           continue;
10422 
10423         // Found std::abs(), check that they are the right ones.
10424         if (FDecl->getNumParams() != 1)
10425           continue;
10426 
10427         // Check that the parameter type can handle the argument.
10428         QualType ParamType = FDecl->getParamDecl(0)->getType();
10429         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10430             S.Context.getTypeSize(ArgType) <=
10431                 S.Context.getTypeSize(ParamType)) {
10432           // Found a function, don't need the header hint.
10433           EmitHeaderHint = false;
10434           break;
10435         }
10436       }
10437     }
10438   } else {
10439     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10440     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10441 
10442     if (HeaderName) {
10443       DeclarationName DN(&S.Context.Idents.get(FunctionName));
10444       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10445       R.suppressDiagnostics();
10446       S.LookupName(R, S.getCurScope());
10447 
10448       if (R.isSingleResult()) {
10449         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10450         if (FD && FD->getBuiltinID() == AbsKind) {
10451           EmitHeaderHint = false;
10452         } else {
10453           return;
10454         }
10455       } else if (!R.empty()) {
10456         return;
10457       }
10458     }
10459   }
10460 
10461   S.Diag(Loc, diag::note_replace_abs_function)
10462       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10463 
10464   if (!HeaderName)
10465     return;
10466 
10467   if (!EmitHeaderHint)
10468     return;
10469 
10470   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10471                                                     << FunctionName;
10472 }
10473 
10474 template <std::size_t StrLen>
10475 static bool IsStdFunction(const FunctionDecl *FDecl,
10476                           const char (&Str)[StrLen]) {
10477   if (!FDecl)
10478     return false;
10479   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10480     return false;
10481   if (!FDecl->isInStdNamespace())
10482     return false;
10483 
10484   return true;
10485 }
10486 
10487 // Warn when using the wrong abs() function.
10488 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10489                                       const FunctionDecl *FDecl) {
10490   if (Call->getNumArgs() != 1)
10491     return;
10492 
10493   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10494   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10495   if (AbsKind == 0 && !IsStdAbs)
10496     return;
10497 
10498   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10499   QualType ParamType = Call->getArg(0)->getType();
10500 
10501   // Unsigned types cannot be negative.  Suggest removing the absolute value
10502   // function call.
10503   if (ArgType->isUnsignedIntegerType()) {
10504     const char *FunctionName =
10505         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10506     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10507     Diag(Call->getExprLoc(), diag::note_remove_abs)
10508         << FunctionName
10509         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10510     return;
10511   }
10512 
10513   // Taking the absolute value of a pointer is very suspicious, they probably
10514   // wanted to index into an array, dereference a pointer, call a function, etc.
10515   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10516     unsigned DiagType = 0;
10517     if (ArgType->isFunctionType())
10518       DiagType = 1;
10519     else if (ArgType->isArrayType())
10520       DiagType = 2;
10521 
10522     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10523     return;
10524   }
10525 
10526   // std::abs has overloads which prevent most of the absolute value problems
10527   // from occurring.
10528   if (IsStdAbs)
10529     return;
10530 
10531   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10532   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10533 
10534   // The argument and parameter are the same kind.  Check if they are the right
10535   // size.
10536   if (ArgValueKind == ParamValueKind) {
10537     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10538       return;
10539 
10540     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10541     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10542         << FDecl << ArgType << ParamType;
10543 
10544     if (NewAbsKind == 0)
10545       return;
10546 
10547     emitReplacement(*this, Call->getExprLoc(),
10548                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10549     return;
10550   }
10551 
10552   // ArgValueKind != ParamValueKind
10553   // The wrong type of absolute value function was used.  Attempt to find the
10554   // proper one.
10555   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10556   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10557   if (NewAbsKind == 0)
10558     return;
10559 
10560   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10561       << FDecl << ParamValueKind << ArgValueKind;
10562 
10563   emitReplacement(*this, Call->getExprLoc(),
10564                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10565 }
10566 
10567 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10568 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10569                                 const FunctionDecl *FDecl) {
10570   if (!Call || !FDecl) return;
10571 
10572   // Ignore template specializations and macros.
10573   if (inTemplateInstantiation()) return;
10574   if (Call->getExprLoc().isMacroID()) return;
10575 
10576   // Only care about the one template argument, two function parameter std::max
10577   if (Call->getNumArgs() != 2) return;
10578   if (!IsStdFunction(FDecl, "max")) return;
10579   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10580   if (!ArgList) return;
10581   if (ArgList->size() != 1) return;
10582 
10583   // Check that template type argument is unsigned integer.
10584   const auto& TA = ArgList->get(0);
10585   if (TA.getKind() != TemplateArgument::Type) return;
10586   QualType ArgType = TA.getAsType();
10587   if (!ArgType->isUnsignedIntegerType()) return;
10588 
10589   // See if either argument is a literal zero.
10590   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10591     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10592     if (!MTE) return false;
10593     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10594     if (!Num) return false;
10595     if (Num->getValue() != 0) return false;
10596     return true;
10597   };
10598 
10599   const Expr *FirstArg = Call->getArg(0);
10600   const Expr *SecondArg = Call->getArg(1);
10601   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10602   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10603 
10604   // Only warn when exactly one argument is zero.
10605   if (IsFirstArgZero == IsSecondArgZero) return;
10606 
10607   SourceRange FirstRange = FirstArg->getSourceRange();
10608   SourceRange SecondRange = SecondArg->getSourceRange();
10609 
10610   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10611 
10612   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10613       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10614 
10615   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10616   SourceRange RemovalRange;
10617   if (IsFirstArgZero) {
10618     RemovalRange = SourceRange(FirstRange.getBegin(),
10619                                SecondRange.getBegin().getLocWithOffset(-1));
10620   } else {
10621     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10622                                SecondRange.getEnd());
10623   }
10624 
10625   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10626         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10627         << FixItHint::CreateRemoval(RemovalRange);
10628 }
10629 
10630 //===--- CHECK: Standard memory functions ---------------------------------===//
10631 
10632 /// Takes the expression passed to the size_t parameter of functions
10633 /// such as memcmp, strncat, etc and warns if it's a comparison.
10634 ///
10635 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10636 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10637                                            IdentifierInfo *FnName,
10638                                            SourceLocation FnLoc,
10639                                            SourceLocation RParenLoc) {
10640   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10641   if (!Size)
10642     return false;
10643 
10644   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10645   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10646     return false;
10647 
10648   SourceRange SizeRange = Size->getSourceRange();
10649   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10650       << SizeRange << FnName;
10651   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10652       << FnName
10653       << FixItHint::CreateInsertion(
10654              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10655       << FixItHint::CreateRemoval(RParenLoc);
10656   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10657       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10658       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10659                                     ")");
10660 
10661   return true;
10662 }
10663 
10664 /// Determine whether the given type is or contains a dynamic class type
10665 /// (e.g., whether it has a vtable).
10666 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10667                                                      bool &IsContained) {
10668   // Look through array types while ignoring qualifiers.
10669   const Type *Ty = T->getBaseElementTypeUnsafe();
10670   IsContained = false;
10671 
10672   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10673   RD = RD ? RD->getDefinition() : nullptr;
10674   if (!RD || RD->isInvalidDecl())
10675     return nullptr;
10676 
10677   if (RD->isDynamicClass())
10678     return RD;
10679 
10680   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10681   // It's impossible for a class to transitively contain itself by value, so
10682   // infinite recursion is impossible.
10683   for (auto *FD : RD->fields()) {
10684     bool SubContained;
10685     if (const CXXRecordDecl *ContainedRD =
10686             getContainedDynamicClass(FD->getType(), SubContained)) {
10687       IsContained = true;
10688       return ContainedRD;
10689     }
10690   }
10691 
10692   return nullptr;
10693 }
10694 
10695 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10696   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10697     if (Unary->getKind() == UETT_SizeOf)
10698       return Unary;
10699   return nullptr;
10700 }
10701 
10702 /// If E is a sizeof expression, returns its argument expression,
10703 /// otherwise returns NULL.
10704 static const Expr *getSizeOfExprArg(const Expr *E) {
10705   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10706     if (!SizeOf->isArgumentType())
10707       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10708   return nullptr;
10709 }
10710 
10711 /// If E is a sizeof expression, returns its argument type.
10712 static QualType getSizeOfArgType(const Expr *E) {
10713   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10714     return SizeOf->getTypeOfArgument();
10715   return QualType();
10716 }
10717 
10718 namespace {
10719 
10720 struct SearchNonTrivialToInitializeField
10721     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10722   using Super =
10723       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10724 
10725   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10726 
10727   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10728                      SourceLocation SL) {
10729     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10730       asDerived().visitArray(PDIK, AT, SL);
10731       return;
10732     }
10733 
10734     Super::visitWithKind(PDIK, FT, SL);
10735   }
10736 
10737   void visitARCStrong(QualType FT, SourceLocation SL) {
10738     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10739   }
10740   void visitARCWeak(QualType FT, SourceLocation SL) {
10741     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10742   }
10743   void visitStruct(QualType FT, SourceLocation SL) {
10744     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10745       visit(FD->getType(), FD->getLocation());
10746   }
10747   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10748                   const ArrayType *AT, SourceLocation SL) {
10749     visit(getContext().getBaseElementType(AT), SL);
10750   }
10751   void visitTrivial(QualType FT, SourceLocation SL) {}
10752 
10753   static void diag(QualType RT, const Expr *E, Sema &S) {
10754     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10755   }
10756 
10757   ASTContext &getContext() { return S.getASTContext(); }
10758 
10759   const Expr *E;
10760   Sema &S;
10761 };
10762 
10763 struct SearchNonTrivialToCopyField
10764     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10765   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10766 
10767   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10768 
10769   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10770                      SourceLocation SL) {
10771     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10772       asDerived().visitArray(PCK, AT, SL);
10773       return;
10774     }
10775 
10776     Super::visitWithKind(PCK, FT, SL);
10777   }
10778 
10779   void visitARCStrong(QualType FT, SourceLocation SL) {
10780     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10781   }
10782   void visitARCWeak(QualType FT, SourceLocation SL) {
10783     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10784   }
10785   void visitStruct(QualType FT, SourceLocation SL) {
10786     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10787       visit(FD->getType(), FD->getLocation());
10788   }
10789   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10790                   SourceLocation SL) {
10791     visit(getContext().getBaseElementType(AT), SL);
10792   }
10793   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10794                 SourceLocation SL) {}
10795   void visitTrivial(QualType FT, SourceLocation SL) {}
10796   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10797 
10798   static void diag(QualType RT, const Expr *E, Sema &S) {
10799     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10800   }
10801 
10802   ASTContext &getContext() { return S.getASTContext(); }
10803 
10804   const Expr *E;
10805   Sema &S;
10806 };
10807 
10808 }
10809 
10810 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10811 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10812   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10813 
10814   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10815     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10816       return false;
10817 
10818     return doesExprLikelyComputeSize(BO->getLHS()) ||
10819            doesExprLikelyComputeSize(BO->getRHS());
10820   }
10821 
10822   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10823 }
10824 
10825 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10826 ///
10827 /// \code
10828 ///   #define MACRO 0
10829 ///   foo(MACRO);
10830 ///   foo(0);
10831 /// \endcode
10832 ///
10833 /// This should return true for the first call to foo, but not for the second
10834 /// (regardless of whether foo is a macro or function).
10835 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10836                                         SourceLocation CallLoc,
10837                                         SourceLocation ArgLoc) {
10838   if (!CallLoc.isMacroID())
10839     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10840 
10841   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10842          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10843 }
10844 
10845 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10846 /// last two arguments transposed.
10847 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10848   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10849     return;
10850 
10851   const Expr *SizeArg =
10852     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10853 
10854   auto isLiteralZero = [](const Expr *E) {
10855     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10856   };
10857 
10858   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10859   SourceLocation CallLoc = Call->getRParenLoc();
10860   SourceManager &SM = S.getSourceManager();
10861   if (isLiteralZero(SizeArg) &&
10862       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10863 
10864     SourceLocation DiagLoc = SizeArg->getExprLoc();
10865 
10866     // Some platforms #define bzero to __builtin_memset. See if this is the
10867     // case, and if so, emit a better diagnostic.
10868     if (BId == Builtin::BIbzero ||
10869         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10870                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10871       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10872       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10873     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10874       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10875       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10876     }
10877     return;
10878   }
10879 
10880   // If the second argument to a memset is a sizeof expression and the third
10881   // isn't, this is also likely an error. This should catch
10882   // 'memset(buf, sizeof(buf), 0xff)'.
10883   if (BId == Builtin::BImemset &&
10884       doesExprLikelyComputeSize(Call->getArg(1)) &&
10885       !doesExprLikelyComputeSize(Call->getArg(2))) {
10886     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10887     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10888     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10889     return;
10890   }
10891 }
10892 
10893 /// Check for dangerous or invalid arguments to memset().
10894 ///
10895 /// This issues warnings on known problematic, dangerous or unspecified
10896 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10897 /// function calls.
10898 ///
10899 /// \param Call The call expression to diagnose.
10900 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10901                                    unsigned BId,
10902                                    IdentifierInfo *FnName) {
10903   assert(BId != 0);
10904 
10905   // It is possible to have a non-standard definition of memset.  Validate
10906   // we have enough arguments, and if not, abort further checking.
10907   unsigned ExpectedNumArgs =
10908       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10909   if (Call->getNumArgs() < ExpectedNumArgs)
10910     return;
10911 
10912   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10913                       BId == Builtin::BIstrndup ? 1 : 2);
10914   unsigned LenArg =
10915       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10916   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10917 
10918   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10919                                      Call->getBeginLoc(), Call->getRParenLoc()))
10920     return;
10921 
10922   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10923   CheckMemaccessSize(*this, BId, Call);
10924 
10925   // We have special checking when the length is a sizeof expression.
10926   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10927   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10928   llvm::FoldingSetNodeID SizeOfArgID;
10929 
10930   // Although widely used, 'bzero' is not a standard function. Be more strict
10931   // with the argument types before allowing diagnostics and only allow the
10932   // form bzero(ptr, sizeof(...)).
10933   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10934   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10935     return;
10936 
10937   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10938     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10939     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10940 
10941     QualType DestTy = Dest->getType();
10942     QualType PointeeTy;
10943     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10944       PointeeTy = DestPtrTy->getPointeeType();
10945 
10946       // Never warn about void type pointers. This can be used to suppress
10947       // false positives.
10948       if (PointeeTy->isVoidType())
10949         continue;
10950 
10951       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10952       // actually comparing the expressions for equality. Because computing the
10953       // expression IDs can be expensive, we only do this if the diagnostic is
10954       // enabled.
10955       if (SizeOfArg &&
10956           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10957                            SizeOfArg->getExprLoc())) {
10958         // We only compute IDs for expressions if the warning is enabled, and
10959         // cache the sizeof arg's ID.
10960         if (SizeOfArgID == llvm::FoldingSetNodeID())
10961           SizeOfArg->Profile(SizeOfArgID, Context, true);
10962         llvm::FoldingSetNodeID DestID;
10963         Dest->Profile(DestID, Context, true);
10964         if (DestID == SizeOfArgID) {
10965           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10966           //       over sizeof(src) as well.
10967           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10968           StringRef ReadableName = FnName->getName();
10969 
10970           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10971             if (UnaryOp->getOpcode() == UO_AddrOf)
10972               ActionIdx = 1; // If its an address-of operator, just remove it.
10973           if (!PointeeTy->isIncompleteType() &&
10974               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10975             ActionIdx = 2; // If the pointee's size is sizeof(char),
10976                            // suggest an explicit length.
10977 
10978           // If the function is defined as a builtin macro, do not show macro
10979           // expansion.
10980           SourceLocation SL = SizeOfArg->getExprLoc();
10981           SourceRange DSR = Dest->getSourceRange();
10982           SourceRange SSR = SizeOfArg->getSourceRange();
10983           SourceManager &SM = getSourceManager();
10984 
10985           if (SM.isMacroArgExpansion(SL)) {
10986             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10987             SL = SM.getSpellingLoc(SL);
10988             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10989                              SM.getSpellingLoc(DSR.getEnd()));
10990             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10991                              SM.getSpellingLoc(SSR.getEnd()));
10992           }
10993 
10994           DiagRuntimeBehavior(SL, SizeOfArg,
10995                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10996                                 << ReadableName
10997                                 << PointeeTy
10998                                 << DestTy
10999                                 << DSR
11000                                 << SSR);
11001           DiagRuntimeBehavior(SL, SizeOfArg,
11002                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
11003                                 << ActionIdx
11004                                 << SSR);
11005 
11006           break;
11007         }
11008       }
11009 
11010       // Also check for cases where the sizeof argument is the exact same
11011       // type as the memory argument, and where it points to a user-defined
11012       // record type.
11013       if (SizeOfArgTy != QualType()) {
11014         if (PointeeTy->isRecordType() &&
11015             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
11016           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
11017                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
11018                                 << FnName << SizeOfArgTy << ArgIdx
11019                                 << PointeeTy << Dest->getSourceRange()
11020                                 << LenExpr->getSourceRange());
11021           break;
11022         }
11023       }
11024     } else if (DestTy->isArrayType()) {
11025       PointeeTy = DestTy;
11026     }
11027 
11028     if (PointeeTy == QualType())
11029       continue;
11030 
11031     // Always complain about dynamic classes.
11032     bool IsContained;
11033     if (const CXXRecordDecl *ContainedRD =
11034             getContainedDynamicClass(PointeeTy, IsContained)) {
11035 
11036       unsigned OperationType = 0;
11037       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
11038       // "overwritten" if we're warning about the destination for any call
11039       // but memcmp; otherwise a verb appropriate to the call.
11040       if (ArgIdx != 0 || IsCmp) {
11041         if (BId == Builtin::BImemcpy)
11042           OperationType = 1;
11043         else if(BId == Builtin::BImemmove)
11044           OperationType = 2;
11045         else if (IsCmp)
11046           OperationType = 3;
11047       }
11048 
11049       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11050                           PDiag(diag::warn_dyn_class_memaccess)
11051                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
11052                               << IsContained << ContainedRD << OperationType
11053                               << Call->getCallee()->getSourceRange());
11054     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
11055              BId != Builtin::BImemset)
11056       DiagRuntimeBehavior(
11057         Dest->getExprLoc(), Dest,
11058         PDiag(diag::warn_arc_object_memaccess)
11059           << ArgIdx << FnName << PointeeTy
11060           << Call->getCallee()->getSourceRange());
11061     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
11062       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11063           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
11064         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11065                             PDiag(diag::warn_cstruct_memaccess)
11066                                 << ArgIdx << FnName << PointeeTy << 0);
11067         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
11068       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11069                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
11070         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11071                             PDiag(diag::warn_cstruct_memaccess)
11072                                 << ArgIdx << FnName << PointeeTy << 1);
11073         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
11074       } else {
11075         continue;
11076       }
11077     } else
11078       continue;
11079 
11080     DiagRuntimeBehavior(
11081       Dest->getExprLoc(), Dest,
11082       PDiag(diag::note_bad_memaccess_silence)
11083         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
11084     break;
11085   }
11086 }
11087 
11088 // A little helper routine: ignore addition and subtraction of integer literals.
11089 // This intentionally does not ignore all integer constant expressions because
11090 // we don't want to remove sizeof().
11091 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11092   Ex = Ex->IgnoreParenCasts();
11093 
11094   while (true) {
11095     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
11096     if (!BO || !BO->isAdditiveOp())
11097       break;
11098 
11099     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11100     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11101 
11102     if (isa<IntegerLiteral>(RHS))
11103       Ex = LHS;
11104     else if (isa<IntegerLiteral>(LHS))
11105       Ex = RHS;
11106     else
11107       break;
11108   }
11109 
11110   return Ex;
11111 }
11112 
11113 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
11114                                                       ASTContext &Context) {
11115   // Only handle constant-sized or VLAs, but not flexible members.
11116   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
11117     // Only issue the FIXIT for arrays of size > 1.
11118     if (CAT->getSize().getSExtValue() <= 1)
11119       return false;
11120   } else if (!Ty->isVariableArrayType()) {
11121     return false;
11122   }
11123   return true;
11124 }
11125 
11126 // Warn if the user has made the 'size' argument to strlcpy or strlcat
11127 // be the size of the source, instead of the destination.
11128 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11129                                     IdentifierInfo *FnName) {
11130 
11131   // Don't crash if the user has the wrong number of arguments
11132   unsigned NumArgs = Call->getNumArgs();
11133   if ((NumArgs != 3) && (NumArgs != 4))
11134     return;
11135 
11136   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
11137   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
11138   const Expr *CompareWithSrc = nullptr;
11139 
11140   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
11141                                      Call->getBeginLoc(), Call->getRParenLoc()))
11142     return;
11143 
11144   // Look for 'strlcpy(dst, x, sizeof(x))'
11145   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
11146     CompareWithSrc = Ex;
11147   else {
11148     // Look for 'strlcpy(dst, x, strlen(x))'
11149     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11150       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11151           SizeCall->getNumArgs() == 1)
11152         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
11153     }
11154   }
11155 
11156   if (!CompareWithSrc)
11157     return;
11158 
11159   // Determine if the argument to sizeof/strlen is equal to the source
11160   // argument.  In principle there's all kinds of things you could do
11161   // here, for instance creating an == expression and evaluating it with
11162   // EvaluateAsBooleanCondition, but this uses a more direct technique:
11163   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11164   if (!SrcArgDRE)
11165     return;
11166 
11167   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11168   if (!CompareWithSrcDRE ||
11169       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11170     return;
11171 
11172   const Expr *OriginalSizeArg = Call->getArg(2);
11173   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11174       << OriginalSizeArg->getSourceRange() << FnName;
11175 
11176   // Output a FIXIT hint if the destination is an array (rather than a
11177   // pointer to an array).  This could be enhanced to handle some
11178   // pointers if we know the actual size, like if DstArg is 'array+2'
11179   // we could say 'sizeof(array)-2'.
11180   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
11181   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
11182     return;
11183 
11184   SmallString<128> sizeString;
11185   llvm::raw_svector_ostream OS(sizeString);
11186   OS << "sizeof(";
11187   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11188   OS << ")";
11189 
11190   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
11191       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
11192                                       OS.str());
11193 }
11194 
11195 /// Check if two expressions refer to the same declaration.
11196 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11197   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11198     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11199       return D1->getDecl() == D2->getDecl();
11200   return false;
11201 }
11202 
11203 static const Expr *getStrlenExprArg(const Expr *E) {
11204   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11205     const FunctionDecl *FD = CE->getDirectCallee();
11206     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11207       return nullptr;
11208     return CE->getArg(0)->IgnoreParenCasts();
11209   }
11210   return nullptr;
11211 }
11212 
11213 // Warn on anti-patterns as the 'size' argument to strncat.
11214 // The correct size argument should look like following:
11215 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
11216 void Sema::CheckStrncatArguments(const CallExpr *CE,
11217                                  IdentifierInfo *FnName) {
11218   // Don't crash if the user has the wrong number of arguments.
11219   if (CE->getNumArgs() < 3)
11220     return;
11221   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11222   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11223   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11224 
11225   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11226                                      CE->getRParenLoc()))
11227     return;
11228 
11229   // Identify common expressions, which are wrongly used as the size argument
11230   // to strncat and may lead to buffer overflows.
11231   unsigned PatternType = 0;
11232   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11233     // - sizeof(dst)
11234     if (referToTheSameDecl(SizeOfArg, DstArg))
11235       PatternType = 1;
11236     // - sizeof(src)
11237     else if (referToTheSameDecl(SizeOfArg, SrcArg))
11238       PatternType = 2;
11239   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11240     if (BE->getOpcode() == BO_Sub) {
11241       const Expr *L = BE->getLHS()->IgnoreParenCasts();
11242       const Expr *R = BE->getRHS()->IgnoreParenCasts();
11243       // - sizeof(dst) - strlen(dst)
11244       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11245           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
11246         PatternType = 1;
11247       // - sizeof(src) - (anything)
11248       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11249         PatternType = 2;
11250     }
11251   }
11252 
11253   if (PatternType == 0)
11254     return;
11255 
11256   // Generate the diagnostic.
11257   SourceLocation SL = LenArg->getBeginLoc();
11258   SourceRange SR = LenArg->getSourceRange();
11259   SourceManager &SM = getSourceManager();
11260 
11261   // If the function is defined as a builtin macro, do not show macro expansion.
11262   if (SM.isMacroArgExpansion(SL)) {
11263     SL = SM.getSpellingLoc(SL);
11264     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11265                      SM.getSpellingLoc(SR.getEnd()));
11266   }
11267 
11268   // Check if the destination is an array (rather than a pointer to an array).
11269   QualType DstTy = DstArg->getType();
11270   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11271                                                                     Context);
11272   if (!isKnownSizeArray) {
11273     if (PatternType == 1)
11274       Diag(SL, diag::warn_strncat_wrong_size) << SR;
11275     else
11276       Diag(SL, diag::warn_strncat_src_size) << SR;
11277     return;
11278   }
11279 
11280   if (PatternType == 1)
11281     Diag(SL, diag::warn_strncat_large_size) << SR;
11282   else
11283     Diag(SL, diag::warn_strncat_src_size) << SR;
11284 
11285   SmallString<128> sizeString;
11286   llvm::raw_svector_ostream OS(sizeString);
11287   OS << "sizeof(";
11288   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11289   OS << ") - ";
11290   OS << "strlen(";
11291   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11292   OS << ") - 1";
11293 
11294   Diag(SL, diag::note_strncat_wrong_size)
11295     << FixItHint::CreateReplacement(SR, OS.str());
11296 }
11297 
11298 namespace {
11299 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11300                                 const UnaryOperator *UnaryExpr, const Decl *D) {
11301   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
11302     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11303         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11304     return;
11305   }
11306 }
11307 
11308 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11309                                  const UnaryOperator *UnaryExpr) {
11310   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11311     const Decl *D = Lvalue->getDecl();
11312     if (isa<DeclaratorDecl>(D))
11313       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
11314         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11315   }
11316 
11317   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11318     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11319                                       Lvalue->getMemberDecl());
11320 }
11321 
11322 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11323                             const UnaryOperator *UnaryExpr) {
11324   const auto *Lambda = dyn_cast<LambdaExpr>(
11325       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11326   if (!Lambda)
11327     return;
11328 
11329   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11330       << CalleeName << 2 /*object: lambda expression*/;
11331 }
11332 
11333 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11334                                   const DeclRefExpr *Lvalue) {
11335   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11336   if (Var == nullptr)
11337     return;
11338 
11339   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11340       << CalleeName << 0 /*object: */ << Var;
11341 }
11342 
11343 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11344                             const CastExpr *Cast) {
11345   SmallString<128> SizeString;
11346   llvm::raw_svector_ostream OS(SizeString);
11347 
11348   clang::CastKind Kind = Cast->getCastKind();
11349   if (Kind == clang::CK_BitCast &&
11350       !Cast->getSubExpr()->getType()->isFunctionPointerType())
11351     return;
11352   if (Kind == clang::CK_IntegralToPointer &&
11353       !isa<IntegerLiteral>(
11354           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11355     return;
11356 
11357   switch (Cast->getCastKind()) {
11358   case clang::CK_BitCast:
11359   case clang::CK_IntegralToPointer:
11360   case clang::CK_FunctionToPointerDecay:
11361     OS << '\'';
11362     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11363     OS << '\'';
11364     break;
11365   default:
11366     return;
11367   }
11368 
11369   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11370       << CalleeName << 0 /*object: */ << OS.str();
11371 }
11372 } // namespace
11373 
11374 /// Alerts the user that they are attempting to free a non-malloc'd object.
11375 void Sema::CheckFreeArguments(const CallExpr *E) {
11376   const std::string CalleeName =
11377       cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11378 
11379   { // Prefer something that doesn't involve a cast to make things simpler.
11380     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11381     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11382       switch (UnaryExpr->getOpcode()) {
11383       case UnaryOperator::Opcode::UO_AddrOf:
11384         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11385       case UnaryOperator::Opcode::UO_Plus:
11386         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11387       default:
11388         break;
11389       }
11390 
11391     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11392       if (Lvalue->getType()->isArrayType())
11393         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11394 
11395     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11396       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11397           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11398       return;
11399     }
11400 
11401     if (isa<BlockExpr>(Arg)) {
11402       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11403           << CalleeName << 1 /*object: block*/;
11404       return;
11405     }
11406   }
11407   // Maybe the cast was important, check after the other cases.
11408   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11409     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11410 }
11411 
11412 void
11413 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11414                          SourceLocation ReturnLoc,
11415                          bool isObjCMethod,
11416                          const AttrVec *Attrs,
11417                          const FunctionDecl *FD) {
11418   // Check if the return value is null but should not be.
11419   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11420        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
11421       CheckNonNullExpr(*this, RetValExp))
11422     Diag(ReturnLoc, diag::warn_null_ret)
11423       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11424 
11425   // C++11 [basic.stc.dynamic.allocation]p4:
11426   //   If an allocation function declared with a non-throwing
11427   //   exception-specification fails to allocate storage, it shall return
11428   //   a null pointer. Any other allocation function that fails to allocate
11429   //   storage shall indicate failure only by throwing an exception [...]
11430   if (FD) {
11431     OverloadedOperatorKind Op = FD->getOverloadedOperator();
11432     if (Op == OO_New || Op == OO_Array_New) {
11433       const FunctionProtoType *Proto
11434         = FD->getType()->castAs<FunctionProtoType>();
11435       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11436           CheckNonNullExpr(*this, RetValExp))
11437         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11438           << FD << getLangOpts().CPlusPlus11;
11439     }
11440   }
11441 
11442   // PPC MMA non-pointer types are not allowed as return type. Checking the type
11443   // here prevent the user from using a PPC MMA type as trailing return type.
11444   if (Context.getTargetInfo().getTriple().isPPC64())
11445     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11446 }
11447 
11448 /// Check for comparisons of floating-point values using == and !=. Issue a
11449 /// warning if the comparison is not likely to do what the programmer intended.
11450 void Sema::CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS,
11451                                 BinaryOperatorKind Opcode) {
11452   // Match and capture subexpressions such as "(float) X == 0.1".
11453   FloatingLiteral *FPLiteral;
11454   CastExpr *FPCast;
11455   auto getCastAndLiteral = [&FPLiteral, &FPCast](Expr *L, Expr *R) {
11456     FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
11457     FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
11458     return FPLiteral && FPCast;
11459   };
11460 
11461   if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11462     auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11463     auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11464     if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11465         TargetTy->isFloatingPoint()) {
11466       bool Lossy;
11467       llvm::APFloat TargetC = FPLiteral->getValue();
11468       TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
11469                       llvm::APFloat::rmNearestTiesToEven, &Lossy);
11470       if (Lossy) {
11471         // If the literal cannot be represented in the source type, then a
11472         // check for == is always false and check for != is always true.
11473         Diag(Loc, diag::warn_float_compare_literal)
11474             << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11475             << LHS->getSourceRange() << RHS->getSourceRange();
11476         return;
11477       }
11478     }
11479   }
11480 
11481   // Match a more general floating-point equality comparison (-Wfloat-equal).
11482   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
11483   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
11484 
11485   // Special case: check for x == x (which is OK).
11486   // Do not emit warnings for such cases.
11487   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11488     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11489       if (DRL->getDecl() == DRR->getDecl())
11490         return;
11491 
11492   // Special case: check for comparisons against literals that can be exactly
11493   //  represented by APFloat.  In such cases, do not emit a warning.  This
11494   //  is a heuristic: often comparison against such literals are used to
11495   //  detect if a value in a variable has not changed.  This clearly can
11496   //  lead to false negatives.
11497   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11498     if (FLL->isExact())
11499       return;
11500   } else
11501     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11502       if (FLR->isExact())
11503         return;
11504 
11505   // Check for comparisons with builtin types.
11506   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11507     if (CL->getBuiltinCallee())
11508       return;
11509 
11510   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11511     if (CR->getBuiltinCallee())
11512       return;
11513 
11514   // Emit the diagnostic.
11515   Diag(Loc, diag::warn_floatingpoint_eq)
11516     << LHS->getSourceRange() << RHS->getSourceRange();
11517 }
11518 
11519 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11520 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11521 
11522 namespace {
11523 
11524 /// Structure recording the 'active' range of an integer-valued
11525 /// expression.
11526 struct IntRange {
11527   /// The number of bits active in the int. Note that this includes exactly one
11528   /// sign bit if !NonNegative.
11529   unsigned Width;
11530 
11531   /// True if the int is known not to have negative values. If so, all leading
11532   /// bits before Width are known zero, otherwise they are known to be the
11533   /// same as the MSB within Width.
11534   bool NonNegative;
11535 
11536   IntRange(unsigned Width, bool NonNegative)
11537       : Width(Width), NonNegative(NonNegative) {}
11538 
11539   /// Number of bits excluding the sign bit.
11540   unsigned valueBits() const {
11541     return NonNegative ? Width : Width - 1;
11542   }
11543 
11544   /// Returns the range of the bool type.
11545   static IntRange forBoolType() {
11546     return IntRange(1, true);
11547   }
11548 
11549   /// Returns the range of an opaque value of the given integral type.
11550   static IntRange forValueOfType(ASTContext &C, QualType T) {
11551     return forValueOfCanonicalType(C,
11552                           T->getCanonicalTypeInternal().getTypePtr());
11553   }
11554 
11555   /// Returns the range of an opaque value of a canonical integral type.
11556   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11557     assert(T->isCanonicalUnqualified());
11558 
11559     if (const VectorType *VT = dyn_cast<VectorType>(T))
11560       T = VT->getElementType().getTypePtr();
11561     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11562       T = CT->getElementType().getTypePtr();
11563     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11564       T = AT->getValueType().getTypePtr();
11565 
11566     if (!C.getLangOpts().CPlusPlus) {
11567       // For enum types in C code, use the underlying datatype.
11568       if (const EnumType *ET = dyn_cast<EnumType>(T))
11569         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11570     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11571       // For enum types in C++, use the known bit width of the enumerators.
11572       EnumDecl *Enum = ET->getDecl();
11573       // In C++11, enums can have a fixed underlying type. Use this type to
11574       // compute the range.
11575       if (Enum->isFixed()) {
11576         return IntRange(C.getIntWidth(QualType(T, 0)),
11577                         !ET->isSignedIntegerOrEnumerationType());
11578       }
11579 
11580       unsigned NumPositive = Enum->getNumPositiveBits();
11581       unsigned NumNegative = Enum->getNumNegativeBits();
11582 
11583       if (NumNegative == 0)
11584         return IntRange(NumPositive, true/*NonNegative*/);
11585       else
11586         return IntRange(std::max(NumPositive + 1, NumNegative),
11587                         false/*NonNegative*/);
11588     }
11589 
11590     if (const auto *EIT = dyn_cast<BitIntType>(T))
11591       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11592 
11593     const BuiltinType *BT = cast<BuiltinType>(T);
11594     assert(BT->isInteger());
11595 
11596     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11597   }
11598 
11599   /// Returns the "target" range of a canonical integral type, i.e.
11600   /// the range of values expressible in the type.
11601   ///
11602   /// This matches forValueOfCanonicalType except that enums have the
11603   /// full range of their type, not the range of their enumerators.
11604   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11605     assert(T->isCanonicalUnqualified());
11606 
11607     if (const VectorType *VT = dyn_cast<VectorType>(T))
11608       T = VT->getElementType().getTypePtr();
11609     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11610       T = CT->getElementType().getTypePtr();
11611     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11612       T = AT->getValueType().getTypePtr();
11613     if (const EnumType *ET = dyn_cast<EnumType>(T))
11614       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11615 
11616     if (const auto *EIT = dyn_cast<BitIntType>(T))
11617       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11618 
11619     const BuiltinType *BT = cast<BuiltinType>(T);
11620     assert(BT->isInteger());
11621 
11622     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11623   }
11624 
11625   /// Returns the supremum of two ranges: i.e. their conservative merge.
11626   static IntRange join(IntRange L, IntRange R) {
11627     bool Unsigned = L.NonNegative && R.NonNegative;
11628     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11629                     L.NonNegative && R.NonNegative);
11630   }
11631 
11632   /// Return the range of a bitwise-AND of the two ranges.
11633   static IntRange bit_and(IntRange L, IntRange R) {
11634     unsigned Bits = std::max(L.Width, R.Width);
11635     bool NonNegative = false;
11636     if (L.NonNegative) {
11637       Bits = std::min(Bits, L.Width);
11638       NonNegative = true;
11639     }
11640     if (R.NonNegative) {
11641       Bits = std::min(Bits, R.Width);
11642       NonNegative = true;
11643     }
11644     return IntRange(Bits, NonNegative);
11645   }
11646 
11647   /// Return the range of a sum of the two ranges.
11648   static IntRange sum(IntRange L, IntRange R) {
11649     bool Unsigned = L.NonNegative && R.NonNegative;
11650     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11651                     Unsigned);
11652   }
11653 
11654   /// Return the range of a difference of the two ranges.
11655   static IntRange difference(IntRange L, IntRange R) {
11656     // We need a 1-bit-wider range if:
11657     //   1) LHS can be negative: least value can be reduced.
11658     //   2) RHS can be negative: greatest value can be increased.
11659     bool CanWiden = !L.NonNegative || !R.NonNegative;
11660     bool Unsigned = L.NonNegative && R.Width == 0;
11661     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11662                         !Unsigned,
11663                     Unsigned);
11664   }
11665 
11666   /// Return the range of a product of the two ranges.
11667   static IntRange product(IntRange L, IntRange R) {
11668     // If both LHS and RHS can be negative, we can form
11669     //   -2^L * -2^R = 2^(L + R)
11670     // which requires L + R + 1 value bits to represent.
11671     bool CanWiden = !L.NonNegative && !R.NonNegative;
11672     bool Unsigned = L.NonNegative && R.NonNegative;
11673     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11674                     Unsigned);
11675   }
11676 
11677   /// Return the range of a remainder operation between the two ranges.
11678   static IntRange rem(IntRange L, IntRange R) {
11679     // The result of a remainder can't be larger than the result of
11680     // either side. The sign of the result is the sign of the LHS.
11681     bool Unsigned = L.NonNegative;
11682     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11683                     Unsigned);
11684   }
11685 };
11686 
11687 } // namespace
11688 
11689 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11690                               unsigned MaxWidth) {
11691   if (value.isSigned() && value.isNegative())
11692     return IntRange(value.getMinSignedBits(), false);
11693 
11694   if (value.getBitWidth() > MaxWidth)
11695     value = value.trunc(MaxWidth);
11696 
11697   // isNonNegative() just checks the sign bit without considering
11698   // signedness.
11699   return IntRange(value.getActiveBits(), true);
11700 }
11701 
11702 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11703                               unsigned MaxWidth) {
11704   if (result.isInt())
11705     return GetValueRange(C, result.getInt(), MaxWidth);
11706 
11707   if (result.isVector()) {
11708     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11709     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11710       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11711       R = IntRange::join(R, El);
11712     }
11713     return R;
11714   }
11715 
11716   if (result.isComplexInt()) {
11717     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11718     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11719     return IntRange::join(R, I);
11720   }
11721 
11722   // This can happen with lossless casts to intptr_t of "based" lvalues.
11723   // Assume it might use arbitrary bits.
11724   // FIXME: The only reason we need to pass the type in here is to get
11725   // the sign right on this one case.  It would be nice if APValue
11726   // preserved this.
11727   assert(result.isLValue() || result.isAddrLabelDiff());
11728   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11729 }
11730 
11731 static QualType GetExprType(const Expr *E) {
11732   QualType Ty = E->getType();
11733   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11734     Ty = AtomicRHS->getValueType();
11735   return Ty;
11736 }
11737 
11738 /// Pseudo-evaluate the given integer expression, estimating the
11739 /// range of values it might take.
11740 ///
11741 /// \param MaxWidth The width to which the value will be truncated.
11742 /// \param Approximate If \c true, return a likely range for the result: in
11743 ///        particular, assume that arithmetic on narrower types doesn't leave
11744 ///        those types. If \c false, return a range including all possible
11745 ///        result values.
11746 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11747                              bool InConstantContext, bool Approximate) {
11748   E = E->IgnoreParens();
11749 
11750   // Try a full evaluation first.
11751   Expr::EvalResult result;
11752   if (E->EvaluateAsRValue(result, C, InConstantContext))
11753     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11754 
11755   // I think we only want to look through implicit casts here; if the
11756   // user has an explicit widening cast, we should treat the value as
11757   // being of the new, wider type.
11758   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11759     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11760       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11761                           Approximate);
11762 
11763     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11764 
11765     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11766                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11767 
11768     // Assume that non-integer casts can span the full range of the type.
11769     if (!isIntegerCast)
11770       return OutputTypeRange;
11771 
11772     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11773                                      std::min(MaxWidth, OutputTypeRange.Width),
11774                                      InConstantContext, Approximate);
11775 
11776     // Bail out if the subexpr's range is as wide as the cast type.
11777     if (SubRange.Width >= OutputTypeRange.Width)
11778       return OutputTypeRange;
11779 
11780     // Otherwise, we take the smaller width, and we're non-negative if
11781     // either the output type or the subexpr is.
11782     return IntRange(SubRange.Width,
11783                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11784   }
11785 
11786   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11787     // If we can fold the condition, just take that operand.
11788     bool CondResult;
11789     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11790       return GetExprRange(C,
11791                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11792                           MaxWidth, InConstantContext, Approximate);
11793 
11794     // Otherwise, conservatively merge.
11795     // GetExprRange requires an integer expression, but a throw expression
11796     // results in a void type.
11797     Expr *E = CO->getTrueExpr();
11798     IntRange L = E->getType()->isVoidType()
11799                      ? IntRange{0, true}
11800                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11801     E = CO->getFalseExpr();
11802     IntRange R = E->getType()->isVoidType()
11803                      ? IntRange{0, true}
11804                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11805     return IntRange::join(L, R);
11806   }
11807 
11808   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11809     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11810 
11811     switch (BO->getOpcode()) {
11812     case BO_Cmp:
11813       llvm_unreachable("builtin <=> should have class type");
11814 
11815     // Boolean-valued operations are single-bit and positive.
11816     case BO_LAnd:
11817     case BO_LOr:
11818     case BO_LT:
11819     case BO_GT:
11820     case BO_LE:
11821     case BO_GE:
11822     case BO_EQ:
11823     case BO_NE:
11824       return IntRange::forBoolType();
11825 
11826     // The type of the assignments is the type of the LHS, so the RHS
11827     // is not necessarily the same type.
11828     case BO_MulAssign:
11829     case BO_DivAssign:
11830     case BO_RemAssign:
11831     case BO_AddAssign:
11832     case BO_SubAssign:
11833     case BO_XorAssign:
11834     case BO_OrAssign:
11835       // TODO: bitfields?
11836       return IntRange::forValueOfType(C, GetExprType(E));
11837 
11838     // Simple assignments just pass through the RHS, which will have
11839     // been coerced to the LHS type.
11840     case BO_Assign:
11841       // TODO: bitfields?
11842       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11843                           Approximate);
11844 
11845     // Operations with opaque sources are black-listed.
11846     case BO_PtrMemD:
11847     case BO_PtrMemI:
11848       return IntRange::forValueOfType(C, GetExprType(E));
11849 
11850     // Bitwise-and uses the *infinum* of the two source ranges.
11851     case BO_And:
11852     case BO_AndAssign:
11853       Combine = IntRange::bit_and;
11854       break;
11855 
11856     // Left shift gets black-listed based on a judgement call.
11857     case BO_Shl:
11858       // ...except that we want to treat '1 << (blah)' as logically
11859       // positive.  It's an important idiom.
11860       if (IntegerLiteral *I
11861             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11862         if (I->getValue() == 1) {
11863           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11864           return IntRange(R.Width, /*NonNegative*/ true);
11865         }
11866       }
11867       LLVM_FALLTHROUGH;
11868 
11869     case BO_ShlAssign:
11870       return IntRange::forValueOfType(C, GetExprType(E));
11871 
11872     // Right shift by a constant can narrow its left argument.
11873     case BO_Shr:
11874     case BO_ShrAssign: {
11875       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11876                                 Approximate);
11877 
11878       // If the shift amount is a positive constant, drop the width by
11879       // that much.
11880       if (Optional<llvm::APSInt> shift =
11881               BO->getRHS()->getIntegerConstantExpr(C)) {
11882         if (shift->isNonNegative()) {
11883           unsigned zext = shift->getZExtValue();
11884           if (zext >= L.Width)
11885             L.Width = (L.NonNegative ? 0 : 1);
11886           else
11887             L.Width -= zext;
11888         }
11889       }
11890 
11891       return L;
11892     }
11893 
11894     // Comma acts as its right operand.
11895     case BO_Comma:
11896       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11897                           Approximate);
11898 
11899     case BO_Add:
11900       if (!Approximate)
11901         Combine = IntRange::sum;
11902       break;
11903 
11904     case BO_Sub:
11905       if (BO->getLHS()->getType()->isPointerType())
11906         return IntRange::forValueOfType(C, GetExprType(E));
11907       if (!Approximate)
11908         Combine = IntRange::difference;
11909       break;
11910 
11911     case BO_Mul:
11912       if (!Approximate)
11913         Combine = IntRange::product;
11914       break;
11915 
11916     // The width of a division result is mostly determined by the size
11917     // of the LHS.
11918     case BO_Div: {
11919       // Don't 'pre-truncate' the operands.
11920       unsigned opWidth = C.getIntWidth(GetExprType(E));
11921       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11922                                 Approximate);
11923 
11924       // If the divisor is constant, use that.
11925       if (Optional<llvm::APSInt> divisor =
11926               BO->getRHS()->getIntegerConstantExpr(C)) {
11927         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11928         if (log2 >= L.Width)
11929           L.Width = (L.NonNegative ? 0 : 1);
11930         else
11931           L.Width = std::min(L.Width - log2, MaxWidth);
11932         return L;
11933       }
11934 
11935       // Otherwise, just use the LHS's width.
11936       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11937       // could be -1.
11938       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11939                                 Approximate);
11940       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11941     }
11942 
11943     case BO_Rem:
11944       Combine = IntRange::rem;
11945       break;
11946 
11947     // The default behavior is okay for these.
11948     case BO_Xor:
11949     case BO_Or:
11950       break;
11951     }
11952 
11953     // Combine the two ranges, but limit the result to the type in which we
11954     // performed the computation.
11955     QualType T = GetExprType(E);
11956     unsigned opWidth = C.getIntWidth(T);
11957     IntRange L =
11958         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11959     IntRange R =
11960         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11961     IntRange C = Combine(L, R);
11962     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11963     C.Width = std::min(C.Width, MaxWidth);
11964     return C;
11965   }
11966 
11967   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11968     switch (UO->getOpcode()) {
11969     // Boolean-valued operations are white-listed.
11970     case UO_LNot:
11971       return IntRange::forBoolType();
11972 
11973     // Operations with opaque sources are black-listed.
11974     case UO_Deref:
11975     case UO_AddrOf: // should be impossible
11976       return IntRange::forValueOfType(C, GetExprType(E));
11977 
11978     default:
11979       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11980                           Approximate);
11981     }
11982   }
11983 
11984   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11985     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11986                         Approximate);
11987 
11988   if (const auto *BitField = E->getSourceBitField())
11989     return IntRange(BitField->getBitWidthValue(C),
11990                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11991 
11992   return IntRange::forValueOfType(C, GetExprType(E));
11993 }
11994 
11995 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11996                              bool InConstantContext, bool Approximate) {
11997   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11998                       Approximate);
11999 }
12000 
12001 /// Checks whether the given value, which currently has the given
12002 /// source semantics, has the same value when coerced through the
12003 /// target semantics.
12004 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
12005                                  const llvm::fltSemantics &Src,
12006                                  const llvm::fltSemantics &Tgt) {
12007   llvm::APFloat truncated = value;
12008 
12009   bool ignored;
12010   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
12011   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
12012 
12013   return truncated.bitwiseIsEqual(value);
12014 }
12015 
12016 /// Checks whether the given value, which currently has the given
12017 /// source semantics, has the same value when coerced through the
12018 /// target semantics.
12019 ///
12020 /// The value might be a vector of floats (or a complex number).
12021 static bool IsSameFloatAfterCast(const APValue &value,
12022                                  const llvm::fltSemantics &Src,
12023                                  const llvm::fltSemantics &Tgt) {
12024   if (value.isFloat())
12025     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
12026 
12027   if (value.isVector()) {
12028     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
12029       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
12030         return false;
12031     return true;
12032   }
12033 
12034   assert(value.isComplexFloat());
12035   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
12036           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
12037 }
12038 
12039 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
12040                                        bool IsListInit = false);
12041 
12042 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
12043   // Suppress cases where we are comparing against an enum constant.
12044   if (const DeclRefExpr *DR =
12045       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
12046     if (isa<EnumConstantDecl>(DR->getDecl()))
12047       return true;
12048 
12049   // Suppress cases where the value is expanded from a macro, unless that macro
12050   // is how a language represents a boolean literal. This is the case in both C
12051   // and Objective-C.
12052   SourceLocation BeginLoc = E->getBeginLoc();
12053   if (BeginLoc.isMacroID()) {
12054     StringRef MacroName = Lexer::getImmediateMacroName(
12055         BeginLoc, S.getSourceManager(), S.getLangOpts());
12056     return MacroName != "YES" && MacroName != "NO" &&
12057            MacroName != "true" && MacroName != "false";
12058   }
12059 
12060   return false;
12061 }
12062 
12063 static bool isKnownToHaveUnsignedValue(Expr *E) {
12064   return E->getType()->isIntegerType() &&
12065          (!E->getType()->isSignedIntegerType() ||
12066           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
12067 }
12068 
12069 namespace {
12070 /// The promoted range of values of a type. In general this has the
12071 /// following structure:
12072 ///
12073 ///     |-----------| . . . |-----------|
12074 ///     ^           ^       ^           ^
12075 ///    Min       HoleMin  HoleMax      Max
12076 ///
12077 /// ... where there is only a hole if a signed type is promoted to unsigned
12078 /// (in which case Min and Max are the smallest and largest representable
12079 /// values).
12080 struct PromotedRange {
12081   // Min, or HoleMax if there is a hole.
12082   llvm::APSInt PromotedMin;
12083   // Max, or HoleMin if there is a hole.
12084   llvm::APSInt PromotedMax;
12085 
12086   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12087     if (R.Width == 0)
12088       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12089     else if (R.Width >= BitWidth && !Unsigned) {
12090       // Promotion made the type *narrower*. This happens when promoting
12091       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12092       // Treat all values of 'signed int' as being in range for now.
12093       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
12094       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
12095     } else {
12096       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
12097                         .extOrTrunc(BitWidth);
12098       PromotedMin.setIsUnsigned(Unsigned);
12099 
12100       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
12101                         .extOrTrunc(BitWidth);
12102       PromotedMax.setIsUnsigned(Unsigned);
12103     }
12104   }
12105 
12106   // Determine whether this range is contiguous (has no hole).
12107   bool isContiguous() const { return PromotedMin <= PromotedMax; }
12108 
12109   // Where a constant value is within the range.
12110   enum ComparisonResult {
12111     LT = 0x1,
12112     LE = 0x2,
12113     GT = 0x4,
12114     GE = 0x8,
12115     EQ = 0x10,
12116     NE = 0x20,
12117     InRangeFlag = 0x40,
12118 
12119     Less = LE | LT | NE,
12120     Min = LE | InRangeFlag,
12121     InRange = InRangeFlag,
12122     Max = GE | InRangeFlag,
12123     Greater = GE | GT | NE,
12124 
12125     OnlyValue = LE | GE | EQ | InRangeFlag,
12126     InHole = NE
12127   };
12128 
12129   ComparisonResult compare(const llvm::APSInt &Value) const {
12130     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12131            Value.isUnsigned() == PromotedMin.isUnsigned());
12132     if (!isContiguous()) {
12133       assert(Value.isUnsigned() && "discontiguous range for signed compare");
12134       if (Value.isMinValue()) return Min;
12135       if (Value.isMaxValue()) return Max;
12136       if (Value >= PromotedMin) return InRange;
12137       if (Value <= PromotedMax) return InRange;
12138       return InHole;
12139     }
12140 
12141     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
12142     case -1: return Less;
12143     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12144     case 1:
12145       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
12146       case -1: return InRange;
12147       case 0: return Max;
12148       case 1: return Greater;
12149       }
12150     }
12151 
12152     llvm_unreachable("impossible compare result");
12153   }
12154 
12155   static llvm::Optional<StringRef>
12156   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12157     if (Op == BO_Cmp) {
12158       ComparisonResult LTFlag = LT, GTFlag = GT;
12159       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
12160 
12161       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12162       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12163       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12164       return llvm::None;
12165     }
12166 
12167     ComparisonResult TrueFlag, FalseFlag;
12168     if (Op == BO_EQ) {
12169       TrueFlag = EQ;
12170       FalseFlag = NE;
12171     } else if (Op == BO_NE) {
12172       TrueFlag = NE;
12173       FalseFlag = EQ;
12174     } else {
12175       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12176         TrueFlag = LT;
12177         FalseFlag = GE;
12178       } else {
12179         TrueFlag = GT;
12180         FalseFlag = LE;
12181       }
12182       if (Op == BO_GE || Op == BO_LE)
12183         std::swap(TrueFlag, FalseFlag);
12184     }
12185     if (R & TrueFlag)
12186       return StringRef("true");
12187     if (R & FalseFlag)
12188       return StringRef("false");
12189     return llvm::None;
12190   }
12191 };
12192 }
12193 
12194 static bool HasEnumType(Expr *E) {
12195   // Strip off implicit integral promotions.
12196   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12197     if (ICE->getCastKind() != CK_IntegralCast &&
12198         ICE->getCastKind() != CK_NoOp)
12199       break;
12200     E = ICE->getSubExpr();
12201   }
12202 
12203   return E->getType()->isEnumeralType();
12204 }
12205 
12206 static int classifyConstantValue(Expr *Constant) {
12207   // The values of this enumeration are used in the diagnostics
12208   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12209   enum ConstantValueKind {
12210     Miscellaneous = 0,
12211     LiteralTrue,
12212     LiteralFalse
12213   };
12214   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12215     return BL->getValue() ? ConstantValueKind::LiteralTrue
12216                           : ConstantValueKind::LiteralFalse;
12217   return ConstantValueKind::Miscellaneous;
12218 }
12219 
12220 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
12221                                         Expr *Constant, Expr *Other,
12222                                         const llvm::APSInt &Value,
12223                                         bool RhsConstant) {
12224   if (S.inTemplateInstantiation())
12225     return false;
12226 
12227   Expr *OriginalOther = Other;
12228 
12229   Constant = Constant->IgnoreParenImpCasts();
12230   Other = Other->IgnoreParenImpCasts();
12231 
12232   // Suppress warnings on tautological comparisons between values of the same
12233   // enumeration type. There are only two ways we could warn on this:
12234   //  - If the constant is outside the range of representable values of
12235   //    the enumeration. In such a case, we should warn about the cast
12236   //    to enumeration type, not about the comparison.
12237   //  - If the constant is the maximum / minimum in-range value. For an
12238   //    enumeratin type, such comparisons can be meaningful and useful.
12239   if (Constant->getType()->isEnumeralType() &&
12240       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12241     return false;
12242 
12243   IntRange OtherValueRange = GetExprRange(
12244       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
12245 
12246   QualType OtherT = Other->getType();
12247   if (const auto *AT = OtherT->getAs<AtomicType>())
12248     OtherT = AT->getValueType();
12249   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12250 
12251   // Special case for ObjC BOOL on targets where its a typedef for a signed char
12252   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12253   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12254                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
12255                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12256 
12257   // Whether we're treating Other as being a bool because of the form of
12258   // expression despite it having another type (typically 'int' in C).
12259   bool OtherIsBooleanDespiteType =
12260       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12261   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12262     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
12263 
12264   // Check if all values in the range of possible values of this expression
12265   // lead to the same comparison outcome.
12266   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
12267                                         Value.isUnsigned());
12268   auto Cmp = OtherPromotedValueRange.compare(Value);
12269   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12270   if (!Result)
12271     return false;
12272 
12273   // Also consider the range determined by the type alone. This allows us to
12274   // classify the warning under the proper diagnostic group.
12275   bool TautologicalTypeCompare = false;
12276   {
12277     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12278                                          Value.isUnsigned());
12279     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12280     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12281                                                        RhsConstant)) {
12282       TautologicalTypeCompare = true;
12283       Cmp = TypeCmp;
12284       Result = TypeResult;
12285     }
12286   }
12287 
12288   // Don't warn if the non-constant operand actually always evaluates to the
12289   // same value.
12290   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
12291     return false;
12292 
12293   // Suppress the diagnostic for an in-range comparison if the constant comes
12294   // from a macro or enumerator. We don't want to diagnose
12295   //
12296   //   some_long_value <= INT_MAX
12297   //
12298   // when sizeof(int) == sizeof(long).
12299   bool InRange = Cmp & PromotedRange::InRangeFlag;
12300   if (InRange && IsEnumConstOrFromMacro(S, Constant))
12301     return false;
12302 
12303   // A comparison of an unsigned bit-field against 0 is really a type problem,
12304   // even though at the type level the bit-field might promote to 'signed int'.
12305   if (Other->refersToBitField() && InRange && Value == 0 &&
12306       Other->getType()->isUnsignedIntegerOrEnumerationType())
12307     TautologicalTypeCompare = true;
12308 
12309   // If this is a comparison to an enum constant, include that
12310   // constant in the diagnostic.
12311   const EnumConstantDecl *ED = nullptr;
12312   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
12313     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12314 
12315   // Should be enough for uint128 (39 decimal digits)
12316   SmallString<64> PrettySourceValue;
12317   llvm::raw_svector_ostream OS(PrettySourceValue);
12318   if (ED) {
12319     OS << '\'' << *ED << "' (" << Value << ")";
12320   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12321                Constant->IgnoreParenImpCasts())) {
12322     OS << (BL->getValue() ? "YES" : "NO");
12323   } else {
12324     OS << Value;
12325   }
12326 
12327   if (!TautologicalTypeCompare) {
12328     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12329         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
12330         << E->getOpcodeStr() << OS.str() << *Result
12331         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12332     return true;
12333   }
12334 
12335   if (IsObjCSignedCharBool) {
12336     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12337                           S.PDiag(diag::warn_tautological_compare_objc_bool)
12338                               << OS.str() << *Result);
12339     return true;
12340   }
12341 
12342   // FIXME: We use a somewhat different formatting for the in-range cases and
12343   // cases involving boolean values for historical reasons. We should pick a
12344   // consistent way of presenting these diagnostics.
12345   if (!InRange || Other->isKnownToHaveBooleanValue()) {
12346 
12347     S.DiagRuntimeBehavior(
12348         E->getOperatorLoc(), E,
12349         S.PDiag(!InRange ? diag::warn_out_of_range_compare
12350                          : diag::warn_tautological_bool_compare)
12351             << OS.str() << classifyConstantValue(Constant) << OtherT
12352             << OtherIsBooleanDespiteType << *Result
12353             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12354   } else {
12355     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12356     unsigned Diag =
12357         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12358             ? (HasEnumType(OriginalOther)
12359                    ? diag::warn_unsigned_enum_always_true_comparison
12360                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12361                               : diag::warn_unsigned_always_true_comparison)
12362             : diag::warn_tautological_constant_compare;
12363 
12364     S.Diag(E->getOperatorLoc(), Diag)
12365         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12366         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12367   }
12368 
12369   return true;
12370 }
12371 
12372 /// Analyze the operands of the given comparison.  Implements the
12373 /// fallback case from AnalyzeComparison.
12374 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12375   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12376   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12377 }
12378 
12379 /// Implements -Wsign-compare.
12380 ///
12381 /// \param E the binary operator to check for warnings
12382 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12383   // The type the comparison is being performed in.
12384   QualType T = E->getLHS()->getType();
12385 
12386   // Only analyze comparison operators where both sides have been converted to
12387   // the same type.
12388   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12389     return AnalyzeImpConvsInComparison(S, E);
12390 
12391   // Don't analyze value-dependent comparisons directly.
12392   if (E->isValueDependent())
12393     return AnalyzeImpConvsInComparison(S, E);
12394 
12395   Expr *LHS = E->getLHS();
12396   Expr *RHS = E->getRHS();
12397 
12398   if (T->isIntegralType(S.Context)) {
12399     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
12400     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
12401 
12402     // We don't care about expressions whose result is a constant.
12403     if (RHSValue && LHSValue)
12404       return AnalyzeImpConvsInComparison(S, E);
12405 
12406     // We only care about expressions where just one side is literal
12407     if ((bool)RHSValue ^ (bool)LHSValue) {
12408       // Is the constant on the RHS or LHS?
12409       const bool RhsConstant = (bool)RHSValue;
12410       Expr *Const = RhsConstant ? RHS : LHS;
12411       Expr *Other = RhsConstant ? LHS : RHS;
12412       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12413 
12414       // Check whether an integer constant comparison results in a value
12415       // of 'true' or 'false'.
12416       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12417         return AnalyzeImpConvsInComparison(S, E);
12418     }
12419   }
12420 
12421   if (!T->hasUnsignedIntegerRepresentation()) {
12422     // We don't do anything special if this isn't an unsigned integral
12423     // comparison:  we're only interested in integral comparisons, and
12424     // signed comparisons only happen in cases we don't care to warn about.
12425     return AnalyzeImpConvsInComparison(S, E);
12426   }
12427 
12428   LHS = LHS->IgnoreParenImpCasts();
12429   RHS = RHS->IgnoreParenImpCasts();
12430 
12431   if (!S.getLangOpts().CPlusPlus) {
12432     // Avoid warning about comparison of integers with different signs when
12433     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12434     // the type of `E`.
12435     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12436       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12437     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12438       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12439   }
12440 
12441   // Check to see if one of the (unmodified) operands is of different
12442   // signedness.
12443   Expr *signedOperand, *unsignedOperand;
12444   if (LHS->getType()->hasSignedIntegerRepresentation()) {
12445     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12446            "unsigned comparison between two signed integer expressions?");
12447     signedOperand = LHS;
12448     unsignedOperand = RHS;
12449   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12450     signedOperand = RHS;
12451     unsignedOperand = LHS;
12452   } else {
12453     return AnalyzeImpConvsInComparison(S, E);
12454   }
12455 
12456   // Otherwise, calculate the effective range of the signed operand.
12457   IntRange signedRange = GetExprRange(
12458       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
12459 
12460   // Go ahead and analyze implicit conversions in the operands.  Note
12461   // that we skip the implicit conversions on both sides.
12462   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
12463   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
12464 
12465   // If the signed range is non-negative, -Wsign-compare won't fire.
12466   if (signedRange.NonNegative)
12467     return;
12468 
12469   // For (in)equality comparisons, if the unsigned operand is a
12470   // constant which cannot collide with a overflowed signed operand,
12471   // then reinterpreting the signed operand as unsigned will not
12472   // change the result of the comparison.
12473   if (E->isEqualityOp()) {
12474     unsigned comparisonWidth = S.Context.getIntWidth(T);
12475     IntRange unsignedRange =
12476         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
12477                      /*Approximate*/ true);
12478 
12479     // We should never be unable to prove that the unsigned operand is
12480     // non-negative.
12481     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
12482 
12483     if (unsignedRange.Width < comparisonWidth)
12484       return;
12485   }
12486 
12487   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12488                         S.PDiag(diag::warn_mixed_sign_comparison)
12489                             << LHS->getType() << RHS->getType()
12490                             << LHS->getSourceRange() << RHS->getSourceRange());
12491 }
12492 
12493 /// Analyzes an attempt to assign the given value to a bitfield.
12494 ///
12495 /// Returns true if there was something fishy about the attempt.
12496 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12497                                       SourceLocation InitLoc) {
12498   assert(Bitfield->isBitField());
12499   if (Bitfield->isInvalidDecl())
12500     return false;
12501 
12502   // White-list bool bitfields.
12503   QualType BitfieldType = Bitfield->getType();
12504   if (BitfieldType->isBooleanType())
12505      return false;
12506 
12507   if (BitfieldType->isEnumeralType()) {
12508     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12509     // If the underlying enum type was not explicitly specified as an unsigned
12510     // type and the enum contain only positive values, MSVC++ will cause an
12511     // inconsistency by storing this as a signed type.
12512     if (S.getLangOpts().CPlusPlus11 &&
12513         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12514         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12515         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12516       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12517           << BitfieldEnumDecl;
12518     }
12519   }
12520 
12521   if (Bitfield->getType()->isBooleanType())
12522     return false;
12523 
12524   // Ignore value- or type-dependent expressions.
12525   if (Bitfield->getBitWidth()->isValueDependent() ||
12526       Bitfield->getBitWidth()->isTypeDependent() ||
12527       Init->isValueDependent() ||
12528       Init->isTypeDependent())
12529     return false;
12530 
12531   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12532   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12533 
12534   Expr::EvalResult Result;
12535   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12536                                    Expr::SE_AllowSideEffects)) {
12537     // The RHS is not constant.  If the RHS has an enum type, make sure the
12538     // bitfield is wide enough to hold all the values of the enum without
12539     // truncation.
12540     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12541       EnumDecl *ED = EnumTy->getDecl();
12542       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12543 
12544       // Enum types are implicitly signed on Windows, so check if there are any
12545       // negative enumerators to see if the enum was intended to be signed or
12546       // not.
12547       bool SignedEnum = ED->getNumNegativeBits() > 0;
12548 
12549       // Check for surprising sign changes when assigning enum values to a
12550       // bitfield of different signedness.  If the bitfield is signed and we
12551       // have exactly the right number of bits to store this unsigned enum,
12552       // suggest changing the enum to an unsigned type. This typically happens
12553       // on Windows where unfixed enums always use an underlying type of 'int'.
12554       unsigned DiagID = 0;
12555       if (SignedEnum && !SignedBitfield) {
12556         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12557       } else if (SignedBitfield && !SignedEnum &&
12558                  ED->getNumPositiveBits() == FieldWidth) {
12559         DiagID = diag::warn_signed_bitfield_enum_conversion;
12560       }
12561 
12562       if (DiagID) {
12563         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12564         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12565         SourceRange TypeRange =
12566             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12567         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12568             << SignedEnum << TypeRange;
12569       }
12570 
12571       // Compute the required bitwidth. If the enum has negative values, we need
12572       // one more bit than the normal number of positive bits to represent the
12573       // sign bit.
12574       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12575                                                   ED->getNumNegativeBits())
12576                                        : ED->getNumPositiveBits();
12577 
12578       // Check the bitwidth.
12579       if (BitsNeeded > FieldWidth) {
12580         Expr *WidthExpr = Bitfield->getBitWidth();
12581         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12582             << Bitfield << ED;
12583         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12584             << BitsNeeded << ED << WidthExpr->getSourceRange();
12585       }
12586     }
12587 
12588     return false;
12589   }
12590 
12591   llvm::APSInt Value = Result.Val.getInt();
12592 
12593   unsigned OriginalWidth = Value.getBitWidth();
12594 
12595   if (!Value.isSigned() || Value.isNegative())
12596     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12597       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12598         OriginalWidth = Value.getMinSignedBits();
12599 
12600   if (OriginalWidth <= FieldWidth)
12601     return false;
12602 
12603   // Compute the value which the bitfield will contain.
12604   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12605   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12606 
12607   // Check whether the stored value is equal to the original value.
12608   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12609   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12610     return false;
12611 
12612   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12613   // therefore don't strictly fit into a signed bitfield of width 1.
12614   if (FieldWidth == 1 && Value == 1)
12615     return false;
12616 
12617   std::string PrettyValue = toString(Value, 10);
12618   std::string PrettyTrunc = toString(TruncatedValue, 10);
12619 
12620   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12621     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12622     << Init->getSourceRange();
12623 
12624   return true;
12625 }
12626 
12627 /// Analyze the given simple or compound assignment for warning-worthy
12628 /// operations.
12629 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12630   // Just recurse on the LHS.
12631   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12632 
12633   // We want to recurse on the RHS as normal unless we're assigning to
12634   // a bitfield.
12635   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12636     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12637                                   E->getOperatorLoc())) {
12638       // Recurse, ignoring any implicit conversions on the RHS.
12639       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12640                                         E->getOperatorLoc());
12641     }
12642   }
12643 
12644   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12645 
12646   // Diagnose implicitly sequentially-consistent atomic assignment.
12647   if (E->getLHS()->getType()->isAtomicType())
12648     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12649 }
12650 
12651 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12652 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12653                             SourceLocation CContext, unsigned diag,
12654                             bool pruneControlFlow = false) {
12655   if (pruneControlFlow) {
12656     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12657                           S.PDiag(diag)
12658                               << SourceType << T << E->getSourceRange()
12659                               << SourceRange(CContext));
12660     return;
12661   }
12662   S.Diag(E->getExprLoc(), diag)
12663     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12664 }
12665 
12666 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12667 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12668                             SourceLocation CContext,
12669                             unsigned diag, bool pruneControlFlow = false) {
12670   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12671 }
12672 
12673 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12674   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12675       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12676 }
12677 
12678 static void adornObjCBoolConversionDiagWithTernaryFixit(
12679     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12680   Expr *Ignored = SourceExpr->IgnoreImplicit();
12681   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12682     Ignored = OVE->getSourceExpr();
12683   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12684                      isa<BinaryOperator>(Ignored) ||
12685                      isa<CXXOperatorCallExpr>(Ignored);
12686   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12687   if (NeedsParens)
12688     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12689             << FixItHint::CreateInsertion(EndLoc, ")");
12690   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12691 }
12692 
12693 /// Diagnose an implicit cast from a floating point value to an integer value.
12694 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12695                                     SourceLocation CContext) {
12696   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12697   const bool PruneWarnings = S.inTemplateInstantiation();
12698 
12699   Expr *InnerE = E->IgnoreParenImpCasts();
12700   // We also want to warn on, e.g., "int i = -1.234"
12701   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12702     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12703       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12704 
12705   const bool IsLiteral =
12706       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12707 
12708   llvm::APFloat Value(0.0);
12709   bool IsConstant =
12710     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12711   if (!IsConstant) {
12712     if (isObjCSignedCharBool(S, T)) {
12713       return adornObjCBoolConversionDiagWithTernaryFixit(
12714           S, E,
12715           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12716               << E->getType());
12717     }
12718 
12719     return DiagnoseImpCast(S, E, T, CContext,
12720                            diag::warn_impcast_float_integer, PruneWarnings);
12721   }
12722 
12723   bool isExact = false;
12724 
12725   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12726                             T->hasUnsignedIntegerRepresentation());
12727   llvm::APFloat::opStatus Result = Value.convertToInteger(
12728       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12729 
12730   // FIXME: Force the precision of the source value down so we don't print
12731   // digits which are usually useless (we don't really care here if we
12732   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12733   // would automatically print the shortest representation, but it's a bit
12734   // tricky to implement.
12735   SmallString<16> PrettySourceValue;
12736   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12737   precision = (precision * 59 + 195) / 196;
12738   Value.toString(PrettySourceValue, precision);
12739 
12740   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12741     return adornObjCBoolConversionDiagWithTernaryFixit(
12742         S, E,
12743         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12744             << PrettySourceValue);
12745   }
12746 
12747   if (Result == llvm::APFloat::opOK && isExact) {
12748     if (IsLiteral) return;
12749     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12750                            PruneWarnings);
12751   }
12752 
12753   // Conversion of a floating-point value to a non-bool integer where the
12754   // integral part cannot be represented by the integer type is undefined.
12755   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12756     return DiagnoseImpCast(
12757         S, E, T, CContext,
12758         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12759                   : diag::warn_impcast_float_to_integer_out_of_range,
12760         PruneWarnings);
12761 
12762   unsigned DiagID = 0;
12763   if (IsLiteral) {
12764     // Warn on floating point literal to integer.
12765     DiagID = diag::warn_impcast_literal_float_to_integer;
12766   } else if (IntegerValue == 0) {
12767     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12768       return DiagnoseImpCast(S, E, T, CContext,
12769                              diag::warn_impcast_float_integer, PruneWarnings);
12770     }
12771     // Warn on non-zero to zero conversion.
12772     DiagID = diag::warn_impcast_float_to_integer_zero;
12773   } else {
12774     if (IntegerValue.isUnsigned()) {
12775       if (!IntegerValue.isMaxValue()) {
12776         return DiagnoseImpCast(S, E, T, CContext,
12777                                diag::warn_impcast_float_integer, PruneWarnings);
12778       }
12779     } else {  // IntegerValue.isSigned()
12780       if (!IntegerValue.isMaxSignedValue() &&
12781           !IntegerValue.isMinSignedValue()) {
12782         return DiagnoseImpCast(S, E, T, CContext,
12783                                diag::warn_impcast_float_integer, PruneWarnings);
12784       }
12785     }
12786     // Warn on evaluatable floating point expression to integer conversion.
12787     DiagID = diag::warn_impcast_float_to_integer;
12788   }
12789 
12790   SmallString<16> PrettyTargetValue;
12791   if (IsBool)
12792     PrettyTargetValue = Value.isZero() ? "false" : "true";
12793   else
12794     IntegerValue.toString(PrettyTargetValue);
12795 
12796   if (PruneWarnings) {
12797     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12798                           S.PDiag(DiagID)
12799                               << E->getType() << T.getUnqualifiedType()
12800                               << PrettySourceValue << PrettyTargetValue
12801                               << E->getSourceRange() << SourceRange(CContext));
12802   } else {
12803     S.Diag(E->getExprLoc(), DiagID)
12804         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12805         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12806   }
12807 }
12808 
12809 /// Analyze the given compound assignment for the possible losing of
12810 /// floating-point precision.
12811 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12812   assert(isa<CompoundAssignOperator>(E) &&
12813          "Must be compound assignment operation");
12814   // Recurse on the LHS and RHS in here
12815   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12816   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12817 
12818   if (E->getLHS()->getType()->isAtomicType())
12819     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12820 
12821   // Now check the outermost expression
12822   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12823   const auto *RBT = cast<CompoundAssignOperator>(E)
12824                         ->getComputationResultType()
12825                         ->getAs<BuiltinType>();
12826 
12827   // The below checks assume source is floating point.
12828   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12829 
12830   // If source is floating point but target is an integer.
12831   if (ResultBT->isInteger())
12832     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12833                            E->getExprLoc(), diag::warn_impcast_float_integer);
12834 
12835   if (!ResultBT->isFloatingPoint())
12836     return;
12837 
12838   // If both source and target are floating points, warn about losing precision.
12839   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12840       QualType(ResultBT, 0), QualType(RBT, 0));
12841   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12842     // warn about dropping FP rank.
12843     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12844                     diag::warn_impcast_float_result_precision);
12845 }
12846 
12847 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12848                                       IntRange Range) {
12849   if (!Range.Width) return "0";
12850 
12851   llvm::APSInt ValueInRange = Value;
12852   ValueInRange.setIsSigned(!Range.NonNegative);
12853   ValueInRange = ValueInRange.trunc(Range.Width);
12854   return toString(ValueInRange, 10);
12855 }
12856 
12857 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12858   if (!isa<ImplicitCastExpr>(Ex))
12859     return false;
12860 
12861   Expr *InnerE = Ex->IgnoreParenImpCasts();
12862   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12863   const Type *Source =
12864     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12865   if (Target->isDependentType())
12866     return false;
12867 
12868   const BuiltinType *FloatCandidateBT =
12869     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12870   const Type *BoolCandidateType = ToBool ? Target : Source;
12871 
12872   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12873           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12874 }
12875 
12876 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12877                                              SourceLocation CC) {
12878   unsigned NumArgs = TheCall->getNumArgs();
12879   for (unsigned i = 0; i < NumArgs; ++i) {
12880     Expr *CurrA = TheCall->getArg(i);
12881     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12882       continue;
12883 
12884     bool IsSwapped = ((i > 0) &&
12885         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12886     IsSwapped |= ((i < (NumArgs - 1)) &&
12887         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12888     if (IsSwapped) {
12889       // Warn on this floating-point to bool conversion.
12890       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12891                       CurrA->getType(), CC,
12892                       diag::warn_impcast_floating_point_to_bool);
12893     }
12894   }
12895 }
12896 
12897 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12898                                    SourceLocation CC) {
12899   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12900                         E->getExprLoc()))
12901     return;
12902 
12903   // Don't warn on functions which have return type nullptr_t.
12904   if (isa<CallExpr>(E))
12905     return;
12906 
12907   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12908   const Expr::NullPointerConstantKind NullKind =
12909       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12910   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12911     return;
12912 
12913   // Return if target type is a safe conversion.
12914   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12915       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12916     return;
12917 
12918   SourceLocation Loc = E->getSourceRange().getBegin();
12919 
12920   // Venture through the macro stacks to get to the source of macro arguments.
12921   // The new location is a better location than the complete location that was
12922   // passed in.
12923   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12924   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12925 
12926   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12927   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12928     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12929         Loc, S.SourceMgr, S.getLangOpts());
12930     if (MacroName == "NULL")
12931       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12932   }
12933 
12934   // Only warn if the null and context location are in the same macro expansion.
12935   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12936     return;
12937 
12938   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12939       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12940       << FixItHint::CreateReplacement(Loc,
12941                                       S.getFixItZeroLiteralForType(T, Loc));
12942 }
12943 
12944 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12945                                   ObjCArrayLiteral *ArrayLiteral);
12946 
12947 static void
12948 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12949                            ObjCDictionaryLiteral *DictionaryLiteral);
12950 
12951 /// Check a single element within a collection literal against the
12952 /// target element type.
12953 static void checkObjCCollectionLiteralElement(Sema &S,
12954                                               QualType TargetElementType,
12955                                               Expr *Element,
12956                                               unsigned ElementKind) {
12957   // Skip a bitcast to 'id' or qualified 'id'.
12958   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12959     if (ICE->getCastKind() == CK_BitCast &&
12960         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12961       Element = ICE->getSubExpr();
12962   }
12963 
12964   QualType ElementType = Element->getType();
12965   ExprResult ElementResult(Element);
12966   if (ElementType->getAs<ObjCObjectPointerType>() &&
12967       S.CheckSingleAssignmentConstraints(TargetElementType,
12968                                          ElementResult,
12969                                          false, false)
12970         != Sema::Compatible) {
12971     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12972         << ElementType << ElementKind << TargetElementType
12973         << Element->getSourceRange();
12974   }
12975 
12976   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12977     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12978   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12979     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12980 }
12981 
12982 /// Check an Objective-C array literal being converted to the given
12983 /// target type.
12984 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12985                                   ObjCArrayLiteral *ArrayLiteral) {
12986   if (!S.NSArrayDecl)
12987     return;
12988 
12989   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12990   if (!TargetObjCPtr)
12991     return;
12992 
12993   if (TargetObjCPtr->isUnspecialized() ||
12994       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12995         != S.NSArrayDecl->getCanonicalDecl())
12996     return;
12997 
12998   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12999   if (TypeArgs.size() != 1)
13000     return;
13001 
13002   QualType TargetElementType = TypeArgs[0];
13003   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
13004     checkObjCCollectionLiteralElement(S, TargetElementType,
13005                                       ArrayLiteral->getElement(I),
13006                                       0);
13007   }
13008 }
13009 
13010 /// Check an Objective-C dictionary literal being converted to the given
13011 /// target type.
13012 static void
13013 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
13014                            ObjCDictionaryLiteral *DictionaryLiteral) {
13015   if (!S.NSDictionaryDecl)
13016     return;
13017 
13018   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
13019   if (!TargetObjCPtr)
13020     return;
13021 
13022   if (TargetObjCPtr->isUnspecialized() ||
13023       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
13024         != S.NSDictionaryDecl->getCanonicalDecl())
13025     return;
13026 
13027   auto TypeArgs = TargetObjCPtr->getTypeArgs();
13028   if (TypeArgs.size() != 2)
13029     return;
13030 
13031   QualType TargetKeyType = TypeArgs[0];
13032   QualType TargetObjectType = TypeArgs[1];
13033   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
13034     auto Element = DictionaryLiteral->getKeyValueElement(I);
13035     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
13036     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
13037   }
13038 }
13039 
13040 // Helper function to filter out cases for constant width constant conversion.
13041 // Don't warn on char array initialization or for non-decimal values.
13042 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
13043                                           SourceLocation CC) {
13044   // If initializing from a constant, and the constant starts with '0',
13045   // then it is a binary, octal, or hexadecimal.  Allow these constants
13046   // to fill all the bits, even if there is a sign change.
13047   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
13048     const char FirstLiteralCharacter =
13049         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
13050     if (FirstLiteralCharacter == '0')
13051       return false;
13052   }
13053 
13054   // If the CC location points to a '{', and the type is char, then assume
13055   // assume it is an array initialization.
13056   if (CC.isValid() && T->isCharType()) {
13057     const char FirstContextCharacter =
13058         S.getSourceManager().getCharacterData(CC)[0];
13059     if (FirstContextCharacter == '{')
13060       return false;
13061   }
13062 
13063   return true;
13064 }
13065 
13066 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
13067   const auto *IL = dyn_cast<IntegerLiteral>(E);
13068   if (!IL) {
13069     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
13070       if (UO->getOpcode() == UO_Minus)
13071         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
13072     }
13073   }
13074 
13075   return IL;
13076 }
13077 
13078 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
13079   E = E->IgnoreParenImpCasts();
13080   SourceLocation ExprLoc = E->getExprLoc();
13081 
13082   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
13083     BinaryOperator::Opcode Opc = BO->getOpcode();
13084     Expr::EvalResult Result;
13085     // Do not diagnose unsigned shifts.
13086     if (Opc == BO_Shl) {
13087       const auto *LHS = getIntegerLiteral(BO->getLHS());
13088       const auto *RHS = getIntegerLiteral(BO->getRHS());
13089       if (LHS && LHS->getValue() == 0)
13090         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
13091       else if (!E->isValueDependent() && LHS && RHS &&
13092                RHS->getValue().isNonNegative() &&
13093                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
13094         S.Diag(ExprLoc, diag::warn_left_shift_always)
13095             << (Result.Val.getInt() != 0);
13096       else if (E->getType()->isSignedIntegerType())
13097         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
13098     }
13099   }
13100 
13101   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
13102     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
13103     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
13104     if (!LHS || !RHS)
13105       return;
13106     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13107         (RHS->getValue() == 0 || RHS->getValue() == 1))
13108       // Do not diagnose common idioms.
13109       return;
13110     if (LHS->getValue() != 0 && RHS->getValue() != 0)
13111       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
13112   }
13113 }
13114 
13115 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
13116                                     SourceLocation CC,
13117                                     bool *ICContext = nullptr,
13118                                     bool IsListInit = false) {
13119   if (E->isTypeDependent() || E->isValueDependent()) return;
13120 
13121   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
13122   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
13123   if (Source == Target) return;
13124   if (Target->isDependentType()) return;
13125 
13126   // If the conversion context location is invalid don't complain. We also
13127   // don't want to emit a warning if the issue occurs from the expansion of
13128   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13129   // delay this check as long as possible. Once we detect we are in that
13130   // scenario, we just return.
13131   if (CC.isInvalid())
13132     return;
13133 
13134   if (Source->isAtomicType())
13135     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
13136 
13137   // Diagnose implicit casts to bool.
13138   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
13139     if (isa<StringLiteral>(E))
13140       // Warn on string literal to bool.  Checks for string literals in logical
13141       // and expressions, for instance, assert(0 && "error here"), are
13142       // prevented by a check in AnalyzeImplicitConversions().
13143       return DiagnoseImpCast(S, E, T, CC,
13144                              diag::warn_impcast_string_literal_to_bool);
13145     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
13146         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
13147       // This covers the literal expressions that evaluate to Objective-C
13148       // objects.
13149       return DiagnoseImpCast(S, E, T, CC,
13150                              diag::warn_impcast_objective_c_literal_to_bool);
13151     }
13152     if (Source->isPointerType() || Source->canDecayToPointerType()) {
13153       // Warn on pointer to bool conversion that is always true.
13154       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
13155                                      SourceRange(CC));
13156     }
13157   }
13158 
13159   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13160   // is a typedef for signed char (macOS), then that constant value has to be 1
13161   // or 0.
13162   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
13163     Expr::EvalResult Result;
13164     if (E->EvaluateAsInt(Result, S.getASTContext(),
13165                          Expr::SE_AllowSideEffects)) {
13166       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13167         adornObjCBoolConversionDiagWithTernaryFixit(
13168             S, E,
13169             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13170                 << toString(Result.Val.getInt(), 10));
13171       }
13172       return;
13173     }
13174   }
13175 
13176   // Check implicit casts from Objective-C collection literals to specialized
13177   // collection types, e.g., NSArray<NSString *> *.
13178   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13179     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
13180   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13181     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
13182 
13183   // Strip vector types.
13184   if (isa<VectorType>(Source)) {
13185     if (Target->isVLSTBuiltinType() &&
13186         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
13187                                          QualType(Source, 0)) ||
13188          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
13189                                             QualType(Source, 0))))
13190       return;
13191 
13192     if (!isa<VectorType>(Target)) {
13193       if (S.SourceMgr.isInSystemMacro(CC))
13194         return;
13195       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
13196     }
13197 
13198     // If the vector cast is cast between two vectors of the same size, it is
13199     // a bitcast, not a conversion.
13200     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
13201       return;
13202 
13203     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13204     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13205   }
13206   if (auto VecTy = dyn_cast<VectorType>(Target))
13207     Target = VecTy->getElementType().getTypePtr();
13208 
13209   // Strip complex types.
13210   if (isa<ComplexType>(Source)) {
13211     if (!isa<ComplexType>(Target)) {
13212       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13213         return;
13214 
13215       return DiagnoseImpCast(S, E, T, CC,
13216                              S.getLangOpts().CPlusPlus
13217                                  ? diag::err_impcast_complex_scalar
13218                                  : diag::warn_impcast_complex_scalar);
13219     }
13220 
13221     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13222     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13223   }
13224 
13225   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13226   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13227 
13228   // If the source is floating point...
13229   if (SourceBT && SourceBT->isFloatingPoint()) {
13230     // ...and the target is floating point...
13231     if (TargetBT && TargetBT->isFloatingPoint()) {
13232       // ...then warn if we're dropping FP rank.
13233 
13234       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
13235           QualType(SourceBT, 0), QualType(TargetBT, 0));
13236       if (Order > 0) {
13237         // Don't warn about float constants that are precisely
13238         // representable in the target type.
13239         Expr::EvalResult result;
13240         if (E->EvaluateAsRValue(result, S.Context)) {
13241           // Value might be a float, a float vector, or a float complex.
13242           if (IsSameFloatAfterCast(result.Val,
13243                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13244                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13245             return;
13246         }
13247 
13248         if (S.SourceMgr.isInSystemMacro(CC))
13249           return;
13250 
13251         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
13252       }
13253       // ... or possibly if we're increasing rank, too
13254       else if (Order < 0) {
13255         if (S.SourceMgr.isInSystemMacro(CC))
13256           return;
13257 
13258         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
13259       }
13260       return;
13261     }
13262 
13263     // If the target is integral, always warn.
13264     if (TargetBT && TargetBT->isInteger()) {
13265       if (S.SourceMgr.isInSystemMacro(CC))
13266         return;
13267 
13268       DiagnoseFloatingImpCast(S, E, T, CC);
13269     }
13270 
13271     // Detect the case where a call result is converted from floating-point to
13272     // to bool, and the final argument to the call is converted from bool, to
13273     // discover this typo:
13274     //
13275     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
13276     //
13277     // FIXME: This is an incredibly special case; is there some more general
13278     // way to detect this class of misplaced-parentheses bug?
13279     if (Target->isBooleanType() && isa<CallExpr>(E)) {
13280       // Check last argument of function call to see if it is an
13281       // implicit cast from a type matching the type the result
13282       // is being cast to.
13283       CallExpr *CEx = cast<CallExpr>(E);
13284       if (unsigned NumArgs = CEx->getNumArgs()) {
13285         Expr *LastA = CEx->getArg(NumArgs - 1);
13286         Expr *InnerE = LastA->IgnoreParenImpCasts();
13287         if (isa<ImplicitCastExpr>(LastA) &&
13288             InnerE->getType()->isBooleanType()) {
13289           // Warn on this floating-point to bool conversion
13290           DiagnoseImpCast(S, E, T, CC,
13291                           diag::warn_impcast_floating_point_to_bool);
13292         }
13293       }
13294     }
13295     return;
13296   }
13297 
13298   // Valid casts involving fixed point types should be accounted for here.
13299   if (Source->isFixedPointType()) {
13300     if (Target->isUnsaturatedFixedPointType()) {
13301       Expr::EvalResult Result;
13302       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
13303                                   S.isConstantEvaluated())) {
13304         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13305         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
13306         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
13307         if (Value > MaxVal || Value < MinVal) {
13308           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13309                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13310                                     << Value.toString() << T
13311                                     << E->getSourceRange()
13312                                     << clang::SourceRange(CC));
13313           return;
13314         }
13315       }
13316     } else if (Target->isIntegerType()) {
13317       Expr::EvalResult Result;
13318       if (!S.isConstantEvaluated() &&
13319           E->EvaluateAsFixedPoint(Result, S.Context,
13320                                   Expr::SE_AllowSideEffects)) {
13321         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13322 
13323         bool Overflowed;
13324         llvm::APSInt IntResult = FXResult.convertToInt(
13325             S.Context.getIntWidth(T),
13326             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
13327 
13328         if (Overflowed) {
13329           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13330                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13331                                     << FXResult.toString() << T
13332                                     << E->getSourceRange()
13333                                     << clang::SourceRange(CC));
13334           return;
13335         }
13336       }
13337     }
13338   } else if (Target->isUnsaturatedFixedPointType()) {
13339     if (Source->isIntegerType()) {
13340       Expr::EvalResult Result;
13341       if (!S.isConstantEvaluated() &&
13342           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
13343         llvm::APSInt Value = Result.Val.getInt();
13344 
13345         bool Overflowed;
13346         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13347             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
13348 
13349         if (Overflowed) {
13350           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13351                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13352                                     << toString(Value, /*Radix=*/10) << T
13353                                     << E->getSourceRange()
13354                                     << clang::SourceRange(CC));
13355           return;
13356         }
13357       }
13358     }
13359   }
13360 
13361   // If we are casting an integer type to a floating point type without
13362   // initialization-list syntax, we might lose accuracy if the floating
13363   // point type has a narrower significand than the integer type.
13364   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13365       TargetBT->isFloatingType() && !IsListInit) {
13366     // Determine the number of precision bits in the source integer type.
13367     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
13368                                         /*Approximate*/ true);
13369     unsigned int SourcePrecision = SourceRange.Width;
13370 
13371     // Determine the number of precision bits in the
13372     // target floating point type.
13373     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13374         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13375 
13376     if (SourcePrecision > 0 && TargetPrecision > 0 &&
13377         SourcePrecision > TargetPrecision) {
13378 
13379       if (Optional<llvm::APSInt> SourceInt =
13380               E->getIntegerConstantExpr(S.Context)) {
13381         // If the source integer is a constant, convert it to the target
13382         // floating point type. Issue a warning if the value changes
13383         // during the whole conversion.
13384         llvm::APFloat TargetFloatValue(
13385             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13386         llvm::APFloat::opStatus ConversionStatus =
13387             TargetFloatValue.convertFromAPInt(
13388                 *SourceInt, SourceBT->isSignedInteger(),
13389                 llvm::APFloat::rmNearestTiesToEven);
13390 
13391         if (ConversionStatus != llvm::APFloat::opOK) {
13392           SmallString<32> PrettySourceValue;
13393           SourceInt->toString(PrettySourceValue, 10);
13394           SmallString<32> PrettyTargetValue;
13395           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13396 
13397           S.DiagRuntimeBehavior(
13398               E->getExprLoc(), E,
13399               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
13400                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
13401                   << E->getSourceRange() << clang::SourceRange(CC));
13402         }
13403       } else {
13404         // Otherwise, the implicit conversion may lose precision.
13405         DiagnoseImpCast(S, E, T, CC,
13406                         diag::warn_impcast_integer_float_precision);
13407       }
13408     }
13409   }
13410 
13411   DiagnoseNullConversion(S, E, T, CC);
13412 
13413   S.DiscardMisalignedMemberAddress(Target, E);
13414 
13415   if (Target->isBooleanType())
13416     DiagnoseIntInBoolContext(S, E);
13417 
13418   if (!Source->isIntegerType() || !Target->isIntegerType())
13419     return;
13420 
13421   // TODO: remove this early return once the false positives for constant->bool
13422   // in templates, macros, etc, are reduced or removed.
13423   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13424     return;
13425 
13426   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
13427       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13428     return adornObjCBoolConversionDiagWithTernaryFixit(
13429         S, E,
13430         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13431             << E->getType());
13432   }
13433 
13434   IntRange SourceTypeRange =
13435       IntRange::forTargetOfCanonicalType(S.Context, Source);
13436   IntRange LikelySourceRange =
13437       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
13438   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
13439 
13440   if (LikelySourceRange.Width > TargetRange.Width) {
13441     // If the source is a constant, use a default-on diagnostic.
13442     // TODO: this should happen for bitfield stores, too.
13443     Expr::EvalResult Result;
13444     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
13445                          S.isConstantEvaluated())) {
13446       llvm::APSInt Value(32);
13447       Value = Result.Val.getInt();
13448 
13449       if (S.SourceMgr.isInSystemMacro(CC))
13450         return;
13451 
13452       std::string PrettySourceValue = toString(Value, 10);
13453       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13454 
13455       S.DiagRuntimeBehavior(
13456           E->getExprLoc(), E,
13457           S.PDiag(diag::warn_impcast_integer_precision_constant)
13458               << PrettySourceValue << PrettyTargetValue << E->getType() << T
13459               << E->getSourceRange() << SourceRange(CC));
13460       return;
13461     }
13462 
13463     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13464     if (S.SourceMgr.isInSystemMacro(CC))
13465       return;
13466 
13467     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
13468       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
13469                              /* pruneControlFlow */ true);
13470     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
13471   }
13472 
13473   if (TargetRange.Width > SourceTypeRange.Width) {
13474     if (auto *UO = dyn_cast<UnaryOperator>(E))
13475       if (UO->getOpcode() == UO_Minus)
13476         if (Source->isUnsignedIntegerType()) {
13477           if (Target->isUnsignedIntegerType())
13478             return DiagnoseImpCast(S, E, T, CC,
13479                                    diag::warn_impcast_high_order_zero_bits);
13480           if (Target->isSignedIntegerType())
13481             return DiagnoseImpCast(S, E, T, CC,
13482                                    diag::warn_impcast_nonnegative_result);
13483         }
13484   }
13485 
13486   if (TargetRange.Width == LikelySourceRange.Width &&
13487       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13488       Source->isSignedIntegerType()) {
13489     // Warn when doing a signed to signed conversion, warn if the positive
13490     // source value is exactly the width of the target type, which will
13491     // cause a negative value to be stored.
13492 
13493     Expr::EvalResult Result;
13494     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
13495         !S.SourceMgr.isInSystemMacro(CC)) {
13496       llvm::APSInt Value = Result.Val.getInt();
13497       if (isSameWidthConstantConversion(S, E, T, CC)) {
13498         std::string PrettySourceValue = toString(Value, 10);
13499         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13500 
13501         S.DiagRuntimeBehavior(
13502             E->getExprLoc(), E,
13503             S.PDiag(diag::warn_impcast_integer_precision_constant)
13504                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13505                 << E->getSourceRange() << SourceRange(CC));
13506         return;
13507       }
13508     }
13509 
13510     // Fall through for non-constants to give a sign conversion warning.
13511   }
13512 
13513   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13514       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13515        LikelySourceRange.Width == TargetRange.Width)) {
13516     if (S.SourceMgr.isInSystemMacro(CC))
13517       return;
13518 
13519     unsigned DiagID = diag::warn_impcast_integer_sign;
13520 
13521     // Traditionally, gcc has warned about this under -Wsign-compare.
13522     // We also want to warn about it in -Wconversion.
13523     // So if -Wconversion is off, use a completely identical diagnostic
13524     // in the sign-compare group.
13525     // The conditional-checking code will
13526     if (ICContext) {
13527       DiagID = diag::warn_impcast_integer_sign_conditional;
13528       *ICContext = true;
13529     }
13530 
13531     return DiagnoseImpCast(S, E, T, CC, DiagID);
13532   }
13533 
13534   // Diagnose conversions between different enumeration types.
13535   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13536   // type, to give us better diagnostics.
13537   QualType SourceType = E->getType();
13538   if (!S.getLangOpts().CPlusPlus) {
13539     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13540       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13541         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13542         SourceType = S.Context.getTypeDeclType(Enum);
13543         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13544       }
13545   }
13546 
13547   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13548     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13549       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13550           TargetEnum->getDecl()->hasNameForLinkage() &&
13551           SourceEnum != TargetEnum) {
13552         if (S.SourceMgr.isInSystemMacro(CC))
13553           return;
13554 
13555         return DiagnoseImpCast(S, E, SourceType, T, CC,
13556                                diag::warn_impcast_different_enum_types);
13557       }
13558 }
13559 
13560 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13561                                      SourceLocation CC, QualType T);
13562 
13563 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13564                                     SourceLocation CC, bool &ICContext) {
13565   E = E->IgnoreParenImpCasts();
13566 
13567   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13568     return CheckConditionalOperator(S, CO, CC, T);
13569 
13570   AnalyzeImplicitConversions(S, E, CC);
13571   if (E->getType() != T)
13572     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13573 }
13574 
13575 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13576                                      SourceLocation CC, QualType T) {
13577   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13578 
13579   Expr *TrueExpr = E->getTrueExpr();
13580   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13581     TrueExpr = BCO->getCommon();
13582 
13583   bool Suspicious = false;
13584   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13585   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13586 
13587   if (T->isBooleanType())
13588     DiagnoseIntInBoolContext(S, E);
13589 
13590   // If -Wconversion would have warned about either of the candidates
13591   // for a signedness conversion to the context type...
13592   if (!Suspicious) return;
13593 
13594   // ...but it's currently ignored...
13595   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13596     return;
13597 
13598   // ...then check whether it would have warned about either of the
13599   // candidates for a signedness conversion to the condition type.
13600   if (E->getType() == T) return;
13601 
13602   Suspicious = false;
13603   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13604                           E->getType(), CC, &Suspicious);
13605   if (!Suspicious)
13606     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13607                             E->getType(), CC, &Suspicious);
13608 }
13609 
13610 /// Check conversion of given expression to boolean.
13611 /// Input argument E is a logical expression.
13612 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13613   if (S.getLangOpts().Bool)
13614     return;
13615   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13616     return;
13617   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13618 }
13619 
13620 namespace {
13621 struct AnalyzeImplicitConversionsWorkItem {
13622   Expr *E;
13623   SourceLocation CC;
13624   bool IsListInit;
13625 };
13626 }
13627 
13628 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13629 /// that should be visited are added to WorkList.
13630 static void AnalyzeImplicitConversions(
13631     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13632     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13633   Expr *OrigE = Item.E;
13634   SourceLocation CC = Item.CC;
13635 
13636   QualType T = OrigE->getType();
13637   Expr *E = OrigE->IgnoreParenImpCasts();
13638 
13639   // Propagate whether we are in a C++ list initialization expression.
13640   // If so, we do not issue warnings for implicit int-float conversion
13641   // precision loss, because C++11 narrowing already handles it.
13642   bool IsListInit = Item.IsListInit ||
13643                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13644 
13645   if (E->isTypeDependent() || E->isValueDependent())
13646     return;
13647 
13648   Expr *SourceExpr = E;
13649   // Examine, but don't traverse into the source expression of an
13650   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13651   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13652   // evaluate it in the context of checking the specific conversion to T though.
13653   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13654     if (auto *Src = OVE->getSourceExpr())
13655       SourceExpr = Src;
13656 
13657   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13658     if (UO->getOpcode() == UO_Not &&
13659         UO->getSubExpr()->isKnownToHaveBooleanValue())
13660       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13661           << OrigE->getSourceRange() << T->isBooleanType()
13662           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13663 
13664   if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
13665     if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13666         BO->getLHS()->isKnownToHaveBooleanValue() &&
13667         BO->getRHS()->isKnownToHaveBooleanValue() &&
13668         BO->getLHS()->HasSideEffects(S.Context) &&
13669         BO->getRHS()->HasSideEffects(S.Context)) {
13670       S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13671           << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange()
13672           << FixItHint::CreateReplacement(
13673                  BO->getOperatorLoc(),
13674                  (BO->getOpcode() == BO_And ? "&&" : "||"));
13675       S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13676     }
13677 
13678   // For conditional operators, we analyze the arguments as if they
13679   // were being fed directly into the output.
13680   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13681     CheckConditionalOperator(S, CO, CC, T);
13682     return;
13683   }
13684 
13685   // Check implicit argument conversions for function calls.
13686   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13687     CheckImplicitArgumentConversions(S, Call, CC);
13688 
13689   // Go ahead and check any implicit conversions we might have skipped.
13690   // The non-canonical typecheck is just an optimization;
13691   // CheckImplicitConversion will filter out dead implicit conversions.
13692   if (SourceExpr->getType() != T)
13693     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13694 
13695   // Now continue drilling into this expression.
13696 
13697   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13698     // The bound subexpressions in a PseudoObjectExpr are not reachable
13699     // as transitive children.
13700     // FIXME: Use a more uniform representation for this.
13701     for (auto *SE : POE->semantics())
13702       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13703         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13704   }
13705 
13706   // Skip past explicit casts.
13707   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13708     E = CE->getSubExpr()->IgnoreParenImpCasts();
13709     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13710       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13711     WorkList.push_back({E, CC, IsListInit});
13712     return;
13713   }
13714 
13715   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13716     // Do a somewhat different check with comparison operators.
13717     if (BO->isComparisonOp())
13718       return AnalyzeComparison(S, BO);
13719 
13720     // And with simple assignments.
13721     if (BO->getOpcode() == BO_Assign)
13722       return AnalyzeAssignment(S, BO);
13723     // And with compound assignments.
13724     if (BO->isAssignmentOp())
13725       return AnalyzeCompoundAssignment(S, BO);
13726   }
13727 
13728   // These break the otherwise-useful invariant below.  Fortunately,
13729   // we don't really need to recurse into them, because any internal
13730   // expressions should have been analyzed already when they were
13731   // built into statements.
13732   if (isa<StmtExpr>(E)) return;
13733 
13734   // Don't descend into unevaluated contexts.
13735   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13736 
13737   // Now just recurse over the expression's children.
13738   CC = E->getExprLoc();
13739   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13740   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13741   for (Stmt *SubStmt : E->children()) {
13742     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13743     if (!ChildExpr)
13744       continue;
13745 
13746     if (IsLogicalAndOperator &&
13747         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13748       // Ignore checking string literals that are in logical and operators.
13749       // This is a common pattern for asserts.
13750       continue;
13751     WorkList.push_back({ChildExpr, CC, IsListInit});
13752   }
13753 
13754   if (BO && BO->isLogicalOp()) {
13755     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13756     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13757       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13758 
13759     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13760     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13761       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13762   }
13763 
13764   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13765     if (U->getOpcode() == UO_LNot) {
13766       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13767     } else if (U->getOpcode() != UO_AddrOf) {
13768       if (U->getSubExpr()->getType()->isAtomicType())
13769         S.Diag(U->getSubExpr()->getBeginLoc(),
13770                diag::warn_atomic_implicit_seq_cst);
13771     }
13772   }
13773 }
13774 
13775 /// AnalyzeImplicitConversions - Find and report any interesting
13776 /// implicit conversions in the given expression.  There are a couple
13777 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13778 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13779                                        bool IsListInit/*= false*/) {
13780   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13781   WorkList.push_back({OrigE, CC, IsListInit});
13782   while (!WorkList.empty())
13783     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13784 }
13785 
13786 /// Diagnose integer type and any valid implicit conversion to it.
13787 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13788   // Taking into account implicit conversions,
13789   // allow any integer.
13790   if (!E->getType()->isIntegerType()) {
13791     S.Diag(E->getBeginLoc(),
13792            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13793     return true;
13794   }
13795   // Potentially emit standard warnings for implicit conversions if enabled
13796   // using -Wconversion.
13797   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13798   return false;
13799 }
13800 
13801 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13802 // Returns true when emitting a warning about taking the address of a reference.
13803 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13804                               const PartialDiagnostic &PD) {
13805   E = E->IgnoreParenImpCasts();
13806 
13807   const FunctionDecl *FD = nullptr;
13808 
13809   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13810     if (!DRE->getDecl()->getType()->isReferenceType())
13811       return false;
13812   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13813     if (!M->getMemberDecl()->getType()->isReferenceType())
13814       return false;
13815   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13816     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13817       return false;
13818     FD = Call->getDirectCallee();
13819   } else {
13820     return false;
13821   }
13822 
13823   SemaRef.Diag(E->getExprLoc(), PD);
13824 
13825   // If possible, point to location of function.
13826   if (FD) {
13827     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13828   }
13829 
13830   return true;
13831 }
13832 
13833 // Returns true if the SourceLocation is expanded from any macro body.
13834 // Returns false if the SourceLocation is invalid, is from not in a macro
13835 // expansion, or is from expanded from a top-level macro argument.
13836 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13837   if (Loc.isInvalid())
13838     return false;
13839 
13840   while (Loc.isMacroID()) {
13841     if (SM.isMacroBodyExpansion(Loc))
13842       return true;
13843     Loc = SM.getImmediateMacroCallerLoc(Loc);
13844   }
13845 
13846   return false;
13847 }
13848 
13849 /// Diagnose pointers that are always non-null.
13850 /// \param E the expression containing the pointer
13851 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13852 /// compared to a null pointer
13853 /// \param IsEqual True when the comparison is equal to a null pointer
13854 /// \param Range Extra SourceRange to highlight in the diagnostic
13855 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13856                                         Expr::NullPointerConstantKind NullKind,
13857                                         bool IsEqual, SourceRange Range) {
13858   if (!E)
13859     return;
13860 
13861   // Don't warn inside macros.
13862   if (E->getExprLoc().isMacroID()) {
13863     const SourceManager &SM = getSourceManager();
13864     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13865         IsInAnyMacroBody(SM, Range.getBegin()))
13866       return;
13867   }
13868   E = E->IgnoreImpCasts();
13869 
13870   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13871 
13872   if (isa<CXXThisExpr>(E)) {
13873     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13874                                 : diag::warn_this_bool_conversion;
13875     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13876     return;
13877   }
13878 
13879   bool IsAddressOf = false;
13880 
13881   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13882     if (UO->getOpcode() != UO_AddrOf)
13883       return;
13884     IsAddressOf = true;
13885     E = UO->getSubExpr();
13886   }
13887 
13888   if (IsAddressOf) {
13889     unsigned DiagID = IsCompare
13890                           ? diag::warn_address_of_reference_null_compare
13891                           : diag::warn_address_of_reference_bool_conversion;
13892     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13893                                          << IsEqual;
13894     if (CheckForReference(*this, E, PD)) {
13895       return;
13896     }
13897   }
13898 
13899   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13900     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13901     std::string Str;
13902     llvm::raw_string_ostream S(Str);
13903     E->printPretty(S, nullptr, getPrintingPolicy());
13904     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13905                                 : diag::warn_cast_nonnull_to_bool;
13906     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13907       << E->getSourceRange() << Range << IsEqual;
13908     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13909   };
13910 
13911   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13912   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13913     if (auto *Callee = Call->getDirectCallee()) {
13914       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13915         ComplainAboutNonnullParamOrCall(A);
13916         return;
13917       }
13918     }
13919   }
13920 
13921   // Expect to find a single Decl.  Skip anything more complicated.
13922   ValueDecl *D = nullptr;
13923   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13924     D = R->getDecl();
13925   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13926     D = M->getMemberDecl();
13927   }
13928 
13929   // Weak Decls can be null.
13930   if (!D || D->isWeak())
13931     return;
13932 
13933   // Check for parameter decl with nonnull attribute
13934   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13935     if (getCurFunction() &&
13936         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13937       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13938         ComplainAboutNonnullParamOrCall(A);
13939         return;
13940       }
13941 
13942       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13943         // Skip function template not specialized yet.
13944         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13945           return;
13946         auto ParamIter = llvm::find(FD->parameters(), PV);
13947         assert(ParamIter != FD->param_end());
13948         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13949 
13950         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13951           if (!NonNull->args_size()) {
13952               ComplainAboutNonnullParamOrCall(NonNull);
13953               return;
13954           }
13955 
13956           for (const ParamIdx &ArgNo : NonNull->args()) {
13957             if (ArgNo.getASTIndex() == ParamNo) {
13958               ComplainAboutNonnullParamOrCall(NonNull);
13959               return;
13960             }
13961           }
13962         }
13963       }
13964     }
13965   }
13966 
13967   QualType T = D->getType();
13968   const bool IsArray = T->isArrayType();
13969   const bool IsFunction = T->isFunctionType();
13970 
13971   // Address of function is used to silence the function warning.
13972   if (IsAddressOf && IsFunction) {
13973     return;
13974   }
13975 
13976   // Found nothing.
13977   if (!IsAddressOf && !IsFunction && !IsArray)
13978     return;
13979 
13980   // Pretty print the expression for the diagnostic.
13981   std::string Str;
13982   llvm::raw_string_ostream S(Str);
13983   E->printPretty(S, nullptr, getPrintingPolicy());
13984 
13985   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13986                               : diag::warn_impcast_pointer_to_bool;
13987   enum {
13988     AddressOf,
13989     FunctionPointer,
13990     ArrayPointer
13991   } DiagType;
13992   if (IsAddressOf)
13993     DiagType = AddressOf;
13994   else if (IsFunction)
13995     DiagType = FunctionPointer;
13996   else if (IsArray)
13997     DiagType = ArrayPointer;
13998   else
13999     llvm_unreachable("Could not determine diagnostic.");
14000   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14001                                 << Range << IsEqual;
14002 
14003   if (!IsFunction)
14004     return;
14005 
14006   // Suggest '&' to silence the function warning.
14007   Diag(E->getExprLoc(), diag::note_function_warning_silence)
14008       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
14009 
14010   // Check to see if '()' fixit should be emitted.
14011   QualType ReturnType;
14012   UnresolvedSet<4> NonTemplateOverloads;
14013   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
14014   if (ReturnType.isNull())
14015     return;
14016 
14017   if (IsCompare) {
14018     // There are two cases here.  If there is null constant, the only suggest
14019     // for a pointer return type.  If the null is 0, then suggest if the return
14020     // type is a pointer or an integer type.
14021     if (!ReturnType->isPointerType()) {
14022       if (NullKind == Expr::NPCK_ZeroExpression ||
14023           NullKind == Expr::NPCK_ZeroLiteral) {
14024         if (!ReturnType->isIntegerType())
14025           return;
14026       } else {
14027         return;
14028       }
14029     }
14030   } else { // !IsCompare
14031     // For function to bool, only suggest if the function pointer has bool
14032     // return type.
14033     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
14034       return;
14035   }
14036   Diag(E->getExprLoc(), diag::note_function_to_function_call)
14037       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
14038 }
14039 
14040 /// Diagnoses "dangerous" implicit conversions within the given
14041 /// expression (which is a full expression).  Implements -Wconversion
14042 /// and -Wsign-compare.
14043 ///
14044 /// \param CC the "context" location of the implicit conversion, i.e.
14045 ///   the most location of the syntactic entity requiring the implicit
14046 ///   conversion
14047 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14048   // Don't diagnose in unevaluated contexts.
14049   if (isUnevaluatedContext())
14050     return;
14051 
14052   // Don't diagnose for value- or type-dependent expressions.
14053   if (E->isTypeDependent() || E->isValueDependent())
14054     return;
14055 
14056   // Check for array bounds violations in cases where the check isn't triggered
14057   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14058   // ArraySubscriptExpr is on the RHS of a variable initialization.
14059   CheckArrayAccess(E);
14060 
14061   // This is not the right CC for (e.g.) a variable initialization.
14062   AnalyzeImplicitConversions(*this, E, CC);
14063 }
14064 
14065 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
14066 /// Input argument E is a logical expression.
14067 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14068   ::CheckBoolLikeConversion(*this, E, CC);
14069 }
14070 
14071 /// Diagnose when expression is an integer constant expression and its evaluation
14072 /// results in integer overflow
14073 void Sema::CheckForIntOverflow (Expr *E) {
14074   // Use a work list to deal with nested struct initializers.
14075   SmallVector<Expr *, 2> Exprs(1, E);
14076 
14077   do {
14078     Expr *OriginalE = Exprs.pop_back_val();
14079     Expr *E = OriginalE->IgnoreParenCasts();
14080 
14081     if (isa<BinaryOperator>(E)) {
14082       E->EvaluateForOverflow(Context);
14083       continue;
14084     }
14085 
14086     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
14087       Exprs.append(InitList->inits().begin(), InitList->inits().end());
14088     else if (isa<ObjCBoxedExpr>(OriginalE))
14089       E->EvaluateForOverflow(Context);
14090     else if (auto Call = dyn_cast<CallExpr>(E))
14091       Exprs.append(Call->arg_begin(), Call->arg_end());
14092     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
14093       Exprs.append(Message->arg_begin(), Message->arg_end());
14094   } while (!Exprs.empty());
14095 }
14096 
14097 namespace {
14098 
14099 /// Visitor for expressions which looks for unsequenced operations on the
14100 /// same object.
14101 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14102   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14103 
14104   /// A tree of sequenced regions within an expression. Two regions are
14105   /// unsequenced if one is an ancestor or a descendent of the other. When we
14106   /// finish processing an expression with sequencing, such as a comma
14107   /// expression, we fold its tree nodes into its parent, since they are
14108   /// unsequenced with respect to nodes we will visit later.
14109   class SequenceTree {
14110     struct Value {
14111       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14112       unsigned Parent : 31;
14113       unsigned Merged : 1;
14114     };
14115     SmallVector<Value, 8> Values;
14116 
14117   public:
14118     /// A region within an expression which may be sequenced with respect
14119     /// to some other region.
14120     class Seq {
14121       friend class SequenceTree;
14122 
14123       unsigned Index;
14124 
14125       explicit Seq(unsigned N) : Index(N) {}
14126 
14127     public:
14128       Seq() : Index(0) {}
14129     };
14130 
14131     SequenceTree() { Values.push_back(Value(0)); }
14132     Seq root() const { return Seq(0); }
14133 
14134     /// Create a new sequence of operations, which is an unsequenced
14135     /// subset of \p Parent. This sequence of operations is sequenced with
14136     /// respect to other children of \p Parent.
14137     Seq allocate(Seq Parent) {
14138       Values.push_back(Value(Parent.Index));
14139       return Seq(Values.size() - 1);
14140     }
14141 
14142     /// Merge a sequence of operations into its parent.
14143     void merge(Seq S) {
14144       Values[S.Index].Merged = true;
14145     }
14146 
14147     /// Determine whether two operations are unsequenced. This operation
14148     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14149     /// should have been merged into its parent as appropriate.
14150     bool isUnsequenced(Seq Cur, Seq Old) {
14151       unsigned C = representative(Cur.Index);
14152       unsigned Target = representative(Old.Index);
14153       while (C >= Target) {
14154         if (C == Target)
14155           return true;
14156         C = Values[C].Parent;
14157       }
14158       return false;
14159     }
14160 
14161   private:
14162     /// Pick a representative for a sequence.
14163     unsigned representative(unsigned K) {
14164       if (Values[K].Merged)
14165         // Perform path compression as we go.
14166         return Values[K].Parent = representative(Values[K].Parent);
14167       return K;
14168     }
14169   };
14170 
14171   /// An object for which we can track unsequenced uses.
14172   using Object = const NamedDecl *;
14173 
14174   /// Different flavors of object usage which we track. We only track the
14175   /// least-sequenced usage of each kind.
14176   enum UsageKind {
14177     /// A read of an object. Multiple unsequenced reads are OK.
14178     UK_Use,
14179 
14180     /// A modification of an object which is sequenced before the value
14181     /// computation of the expression, such as ++n in C++.
14182     UK_ModAsValue,
14183 
14184     /// A modification of an object which is not sequenced before the value
14185     /// computation of the expression, such as n++.
14186     UK_ModAsSideEffect,
14187 
14188     UK_Count = UK_ModAsSideEffect + 1
14189   };
14190 
14191   /// Bundle together a sequencing region and the expression corresponding
14192   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14193   struct Usage {
14194     const Expr *UsageExpr;
14195     SequenceTree::Seq Seq;
14196 
14197     Usage() : UsageExpr(nullptr) {}
14198   };
14199 
14200   struct UsageInfo {
14201     Usage Uses[UK_Count];
14202 
14203     /// Have we issued a diagnostic for this object already?
14204     bool Diagnosed;
14205 
14206     UsageInfo() : Diagnosed(false) {}
14207   };
14208   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14209 
14210   Sema &SemaRef;
14211 
14212   /// Sequenced regions within the expression.
14213   SequenceTree Tree;
14214 
14215   /// Declaration modifications and references which we have seen.
14216   UsageInfoMap UsageMap;
14217 
14218   /// The region we are currently within.
14219   SequenceTree::Seq Region;
14220 
14221   /// Filled in with declarations which were modified as a side-effect
14222   /// (that is, post-increment operations).
14223   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14224 
14225   /// Expressions to check later. We defer checking these to reduce
14226   /// stack usage.
14227   SmallVectorImpl<const Expr *> &WorkList;
14228 
14229   /// RAII object wrapping the visitation of a sequenced subexpression of an
14230   /// expression. At the end of this process, the side-effects of the evaluation
14231   /// become sequenced with respect to the value computation of the result, so
14232   /// we downgrade any UK_ModAsSideEffect within the evaluation to
14233   /// UK_ModAsValue.
14234   struct SequencedSubexpression {
14235     SequencedSubexpression(SequenceChecker &Self)
14236       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14237       Self.ModAsSideEffect = &ModAsSideEffect;
14238     }
14239 
14240     ~SequencedSubexpression() {
14241       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14242         // Add a new usage with usage kind UK_ModAsValue, and then restore
14243         // the previous usage with UK_ModAsSideEffect (thus clearing it if
14244         // the previous one was empty).
14245         UsageInfo &UI = Self.UsageMap[M.first];
14246         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14247         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14248         SideEffectUsage = M.second;
14249       }
14250       Self.ModAsSideEffect = OldModAsSideEffect;
14251     }
14252 
14253     SequenceChecker &Self;
14254     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14255     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14256   };
14257 
14258   /// RAII object wrapping the visitation of a subexpression which we might
14259   /// choose to evaluate as a constant. If any subexpression is evaluated and
14260   /// found to be non-constant, this allows us to suppress the evaluation of
14261   /// the outer expression.
14262   class EvaluationTracker {
14263   public:
14264     EvaluationTracker(SequenceChecker &Self)
14265         : Self(Self), Prev(Self.EvalTracker) {
14266       Self.EvalTracker = this;
14267     }
14268 
14269     ~EvaluationTracker() {
14270       Self.EvalTracker = Prev;
14271       if (Prev)
14272         Prev->EvalOK &= EvalOK;
14273     }
14274 
14275     bool evaluate(const Expr *E, bool &Result) {
14276       if (!EvalOK || E->isValueDependent())
14277         return false;
14278       EvalOK = E->EvaluateAsBooleanCondition(
14279           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
14280       return EvalOK;
14281     }
14282 
14283   private:
14284     SequenceChecker &Self;
14285     EvaluationTracker *Prev;
14286     bool EvalOK = true;
14287   } *EvalTracker = nullptr;
14288 
14289   /// Find the object which is produced by the specified expression,
14290   /// if any.
14291   Object getObject(const Expr *E, bool Mod) const {
14292     E = E->IgnoreParenCasts();
14293     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14294       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14295         return getObject(UO->getSubExpr(), Mod);
14296     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14297       if (BO->getOpcode() == BO_Comma)
14298         return getObject(BO->getRHS(), Mod);
14299       if (Mod && BO->isAssignmentOp())
14300         return getObject(BO->getLHS(), Mod);
14301     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14302       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14303       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14304         return ME->getMemberDecl();
14305     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14306       // FIXME: If this is a reference, map through to its value.
14307       return DRE->getDecl();
14308     return nullptr;
14309   }
14310 
14311   /// Note that an object \p O was modified or used by an expression
14312   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14313   /// the object \p O as obtained via the \p UsageMap.
14314   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14315     // Get the old usage for the given object and usage kind.
14316     Usage &U = UI.Uses[UK];
14317     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14318       // If we have a modification as side effect and are in a sequenced
14319       // subexpression, save the old Usage so that we can restore it later
14320       // in SequencedSubexpression::~SequencedSubexpression.
14321       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14322         ModAsSideEffect->push_back(std::make_pair(O, U));
14323       // Then record the new usage with the current sequencing region.
14324       U.UsageExpr = UsageExpr;
14325       U.Seq = Region;
14326     }
14327   }
14328 
14329   /// Check whether a modification or use of an object \p O in an expression
14330   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14331   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14332   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14333   /// usage and false we are checking for a mod-use unsequenced usage.
14334   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14335                   UsageKind OtherKind, bool IsModMod) {
14336     if (UI.Diagnosed)
14337       return;
14338 
14339     const Usage &U = UI.Uses[OtherKind];
14340     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14341       return;
14342 
14343     const Expr *Mod = U.UsageExpr;
14344     const Expr *ModOrUse = UsageExpr;
14345     if (OtherKind == UK_Use)
14346       std::swap(Mod, ModOrUse);
14347 
14348     SemaRef.DiagRuntimeBehavior(
14349         Mod->getExprLoc(), {Mod, ModOrUse},
14350         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14351                                : diag::warn_unsequenced_mod_use)
14352             << O << SourceRange(ModOrUse->getExprLoc()));
14353     UI.Diagnosed = true;
14354   }
14355 
14356   // A note on note{Pre, Post}{Use, Mod}:
14357   //
14358   // (It helps to follow the algorithm with an expression such as
14359   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14360   //  operations before C++17 and both are well-defined in C++17).
14361   //
14362   // When visiting a node which uses/modify an object we first call notePreUse
14363   // or notePreMod before visiting its sub-expression(s). At this point the
14364   // children of the current node have not yet been visited and so the eventual
14365   // uses/modifications resulting from the children of the current node have not
14366   // been recorded yet.
14367   //
14368   // We then visit the children of the current node. After that notePostUse or
14369   // notePostMod is called. These will 1) detect an unsequenced modification
14370   // as side effect (as in "k++ + k") and 2) add a new usage with the
14371   // appropriate usage kind.
14372   //
14373   // We also have to be careful that some operation sequences modification as
14374   // side effect as well (for example: || or ,). To account for this we wrap
14375   // the visitation of such a sub-expression (for example: the LHS of || or ,)
14376   // with SequencedSubexpression. SequencedSubexpression is an RAII object
14377   // which record usages which are modifications as side effect, and then
14378   // downgrade them (or more accurately restore the previous usage which was a
14379   // modification as side effect) when exiting the scope of the sequenced
14380   // subexpression.
14381 
14382   void notePreUse(Object O, const Expr *UseExpr) {
14383     UsageInfo &UI = UsageMap[O];
14384     // Uses conflict with other modifications.
14385     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14386   }
14387 
14388   void notePostUse(Object O, const Expr *UseExpr) {
14389     UsageInfo &UI = UsageMap[O];
14390     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14391                /*IsModMod=*/false);
14392     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14393   }
14394 
14395   void notePreMod(Object O, const Expr *ModExpr) {
14396     UsageInfo &UI = UsageMap[O];
14397     // Modifications conflict with other modifications and with uses.
14398     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14399     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14400   }
14401 
14402   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14403     UsageInfo &UI = UsageMap[O];
14404     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14405                /*IsModMod=*/true);
14406     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14407   }
14408 
14409 public:
14410   SequenceChecker(Sema &S, const Expr *E,
14411                   SmallVectorImpl<const Expr *> &WorkList)
14412       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14413     Visit(E);
14414     // Silence a -Wunused-private-field since WorkList is now unused.
14415     // TODO: Evaluate if it can be used, and if not remove it.
14416     (void)this->WorkList;
14417   }
14418 
14419   void VisitStmt(const Stmt *S) {
14420     // Skip all statements which aren't expressions for now.
14421   }
14422 
14423   void VisitExpr(const Expr *E) {
14424     // By default, just recurse to evaluated subexpressions.
14425     Base::VisitStmt(E);
14426   }
14427 
14428   void VisitCastExpr(const CastExpr *E) {
14429     Object O = Object();
14430     if (E->getCastKind() == CK_LValueToRValue)
14431       O = getObject(E->getSubExpr(), false);
14432 
14433     if (O)
14434       notePreUse(O, E);
14435     VisitExpr(E);
14436     if (O)
14437       notePostUse(O, E);
14438   }
14439 
14440   void VisitSequencedExpressions(const Expr *SequencedBefore,
14441                                  const Expr *SequencedAfter) {
14442     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14443     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14444     SequenceTree::Seq OldRegion = Region;
14445 
14446     {
14447       SequencedSubexpression SeqBefore(*this);
14448       Region = BeforeRegion;
14449       Visit(SequencedBefore);
14450     }
14451 
14452     Region = AfterRegion;
14453     Visit(SequencedAfter);
14454 
14455     Region = OldRegion;
14456 
14457     Tree.merge(BeforeRegion);
14458     Tree.merge(AfterRegion);
14459   }
14460 
14461   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14462     // C++17 [expr.sub]p1:
14463     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14464     //   expression E1 is sequenced before the expression E2.
14465     if (SemaRef.getLangOpts().CPlusPlus17)
14466       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14467     else {
14468       Visit(ASE->getLHS());
14469       Visit(ASE->getRHS());
14470     }
14471   }
14472 
14473   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14474   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14475   void VisitBinPtrMem(const BinaryOperator *BO) {
14476     // C++17 [expr.mptr.oper]p4:
14477     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14478     //  the expression E1 is sequenced before the expression E2.
14479     if (SemaRef.getLangOpts().CPlusPlus17)
14480       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14481     else {
14482       Visit(BO->getLHS());
14483       Visit(BO->getRHS());
14484     }
14485   }
14486 
14487   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14488   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14489   void VisitBinShlShr(const BinaryOperator *BO) {
14490     // C++17 [expr.shift]p4:
14491     //  The expression E1 is sequenced before the expression E2.
14492     if (SemaRef.getLangOpts().CPlusPlus17)
14493       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14494     else {
14495       Visit(BO->getLHS());
14496       Visit(BO->getRHS());
14497     }
14498   }
14499 
14500   void VisitBinComma(const BinaryOperator *BO) {
14501     // C++11 [expr.comma]p1:
14502     //   Every value computation and side effect associated with the left
14503     //   expression is sequenced before every value computation and side
14504     //   effect associated with the right expression.
14505     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14506   }
14507 
14508   void VisitBinAssign(const BinaryOperator *BO) {
14509     SequenceTree::Seq RHSRegion;
14510     SequenceTree::Seq LHSRegion;
14511     if (SemaRef.getLangOpts().CPlusPlus17) {
14512       RHSRegion = Tree.allocate(Region);
14513       LHSRegion = Tree.allocate(Region);
14514     } else {
14515       RHSRegion = Region;
14516       LHSRegion = Region;
14517     }
14518     SequenceTree::Seq OldRegion = Region;
14519 
14520     // C++11 [expr.ass]p1:
14521     //  [...] the assignment is sequenced after the value computation
14522     //  of the right and left operands, [...]
14523     //
14524     // so check it before inspecting the operands and update the
14525     // map afterwards.
14526     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14527     if (O)
14528       notePreMod(O, BO);
14529 
14530     if (SemaRef.getLangOpts().CPlusPlus17) {
14531       // C++17 [expr.ass]p1:
14532       //  [...] The right operand is sequenced before the left operand. [...]
14533       {
14534         SequencedSubexpression SeqBefore(*this);
14535         Region = RHSRegion;
14536         Visit(BO->getRHS());
14537       }
14538 
14539       Region = LHSRegion;
14540       Visit(BO->getLHS());
14541 
14542       if (O && isa<CompoundAssignOperator>(BO))
14543         notePostUse(O, BO);
14544 
14545     } else {
14546       // C++11 does not specify any sequencing between the LHS and RHS.
14547       Region = LHSRegion;
14548       Visit(BO->getLHS());
14549 
14550       if (O && isa<CompoundAssignOperator>(BO))
14551         notePostUse(O, BO);
14552 
14553       Region = RHSRegion;
14554       Visit(BO->getRHS());
14555     }
14556 
14557     // C++11 [expr.ass]p1:
14558     //  the assignment is sequenced [...] before the value computation of the
14559     //  assignment expression.
14560     // C11 6.5.16/3 has no such rule.
14561     Region = OldRegion;
14562     if (O)
14563       notePostMod(O, BO,
14564                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14565                                                   : UK_ModAsSideEffect);
14566     if (SemaRef.getLangOpts().CPlusPlus17) {
14567       Tree.merge(RHSRegion);
14568       Tree.merge(LHSRegion);
14569     }
14570   }
14571 
14572   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14573     VisitBinAssign(CAO);
14574   }
14575 
14576   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14577   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14578   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14579     Object O = getObject(UO->getSubExpr(), true);
14580     if (!O)
14581       return VisitExpr(UO);
14582 
14583     notePreMod(O, UO);
14584     Visit(UO->getSubExpr());
14585     // C++11 [expr.pre.incr]p1:
14586     //   the expression ++x is equivalent to x+=1
14587     notePostMod(O, UO,
14588                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14589                                                 : UK_ModAsSideEffect);
14590   }
14591 
14592   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14593   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14594   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14595     Object O = getObject(UO->getSubExpr(), true);
14596     if (!O)
14597       return VisitExpr(UO);
14598 
14599     notePreMod(O, UO);
14600     Visit(UO->getSubExpr());
14601     notePostMod(O, UO, UK_ModAsSideEffect);
14602   }
14603 
14604   void VisitBinLOr(const BinaryOperator *BO) {
14605     // C++11 [expr.log.or]p2:
14606     //  If the second expression is evaluated, every value computation and
14607     //  side effect associated with the first expression is sequenced before
14608     //  every value computation and side effect associated with the
14609     //  second expression.
14610     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14611     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14612     SequenceTree::Seq OldRegion = Region;
14613 
14614     EvaluationTracker Eval(*this);
14615     {
14616       SequencedSubexpression Sequenced(*this);
14617       Region = LHSRegion;
14618       Visit(BO->getLHS());
14619     }
14620 
14621     // C++11 [expr.log.or]p1:
14622     //  [...] the second operand is not evaluated if the first operand
14623     //  evaluates to true.
14624     bool EvalResult = false;
14625     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14626     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14627     if (ShouldVisitRHS) {
14628       Region = RHSRegion;
14629       Visit(BO->getRHS());
14630     }
14631 
14632     Region = OldRegion;
14633     Tree.merge(LHSRegion);
14634     Tree.merge(RHSRegion);
14635   }
14636 
14637   void VisitBinLAnd(const BinaryOperator *BO) {
14638     // C++11 [expr.log.and]p2:
14639     //  If the second expression is evaluated, every value computation and
14640     //  side effect associated with the first expression is sequenced before
14641     //  every value computation and side effect associated with the
14642     //  second expression.
14643     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14644     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14645     SequenceTree::Seq OldRegion = Region;
14646 
14647     EvaluationTracker Eval(*this);
14648     {
14649       SequencedSubexpression Sequenced(*this);
14650       Region = LHSRegion;
14651       Visit(BO->getLHS());
14652     }
14653 
14654     // C++11 [expr.log.and]p1:
14655     //  [...] the second operand is not evaluated if the first operand is false.
14656     bool EvalResult = false;
14657     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14658     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14659     if (ShouldVisitRHS) {
14660       Region = RHSRegion;
14661       Visit(BO->getRHS());
14662     }
14663 
14664     Region = OldRegion;
14665     Tree.merge(LHSRegion);
14666     Tree.merge(RHSRegion);
14667   }
14668 
14669   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14670     // C++11 [expr.cond]p1:
14671     //  [...] Every value computation and side effect associated with the first
14672     //  expression is sequenced before every value computation and side effect
14673     //  associated with the second or third expression.
14674     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14675 
14676     // No sequencing is specified between the true and false expression.
14677     // However since exactly one of both is going to be evaluated we can
14678     // consider them to be sequenced. This is needed to avoid warning on
14679     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14680     // both the true and false expressions because we can't evaluate x.
14681     // This will still allow us to detect an expression like (pre C++17)
14682     // "(x ? y += 1 : y += 2) = y".
14683     //
14684     // We don't wrap the visitation of the true and false expression with
14685     // SequencedSubexpression because we don't want to downgrade modifications
14686     // as side effect in the true and false expressions after the visition
14687     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14688     // not warn between the two "y++", but we should warn between the "y++"
14689     // and the "y".
14690     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14691     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14692     SequenceTree::Seq OldRegion = Region;
14693 
14694     EvaluationTracker Eval(*this);
14695     {
14696       SequencedSubexpression Sequenced(*this);
14697       Region = ConditionRegion;
14698       Visit(CO->getCond());
14699     }
14700 
14701     // C++11 [expr.cond]p1:
14702     // [...] The first expression is contextually converted to bool (Clause 4).
14703     // It is evaluated and if it is true, the result of the conditional
14704     // expression is the value of the second expression, otherwise that of the
14705     // third expression. Only one of the second and third expressions is
14706     // evaluated. [...]
14707     bool EvalResult = false;
14708     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14709     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14710     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14711     if (ShouldVisitTrueExpr) {
14712       Region = TrueRegion;
14713       Visit(CO->getTrueExpr());
14714     }
14715     if (ShouldVisitFalseExpr) {
14716       Region = FalseRegion;
14717       Visit(CO->getFalseExpr());
14718     }
14719 
14720     Region = OldRegion;
14721     Tree.merge(ConditionRegion);
14722     Tree.merge(TrueRegion);
14723     Tree.merge(FalseRegion);
14724   }
14725 
14726   void VisitCallExpr(const CallExpr *CE) {
14727     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14728 
14729     if (CE->isUnevaluatedBuiltinCall(Context))
14730       return;
14731 
14732     // C++11 [intro.execution]p15:
14733     //   When calling a function [...], every value computation and side effect
14734     //   associated with any argument expression, or with the postfix expression
14735     //   designating the called function, is sequenced before execution of every
14736     //   expression or statement in the body of the function [and thus before
14737     //   the value computation of its result].
14738     SequencedSubexpression Sequenced(*this);
14739     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14740       // C++17 [expr.call]p5
14741       //   The postfix-expression is sequenced before each expression in the
14742       //   expression-list and any default argument. [...]
14743       SequenceTree::Seq CalleeRegion;
14744       SequenceTree::Seq OtherRegion;
14745       if (SemaRef.getLangOpts().CPlusPlus17) {
14746         CalleeRegion = Tree.allocate(Region);
14747         OtherRegion = Tree.allocate(Region);
14748       } else {
14749         CalleeRegion = Region;
14750         OtherRegion = Region;
14751       }
14752       SequenceTree::Seq OldRegion = Region;
14753 
14754       // Visit the callee expression first.
14755       Region = CalleeRegion;
14756       if (SemaRef.getLangOpts().CPlusPlus17) {
14757         SequencedSubexpression Sequenced(*this);
14758         Visit(CE->getCallee());
14759       } else {
14760         Visit(CE->getCallee());
14761       }
14762 
14763       // Then visit the argument expressions.
14764       Region = OtherRegion;
14765       for (const Expr *Argument : CE->arguments())
14766         Visit(Argument);
14767 
14768       Region = OldRegion;
14769       if (SemaRef.getLangOpts().CPlusPlus17) {
14770         Tree.merge(CalleeRegion);
14771         Tree.merge(OtherRegion);
14772       }
14773     });
14774   }
14775 
14776   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14777     // C++17 [over.match.oper]p2:
14778     //   [...] the operator notation is first transformed to the equivalent
14779     //   function-call notation as summarized in Table 12 (where @ denotes one
14780     //   of the operators covered in the specified subclause). However, the
14781     //   operands are sequenced in the order prescribed for the built-in
14782     //   operator (Clause 8).
14783     //
14784     // From the above only overloaded binary operators and overloaded call
14785     // operators have sequencing rules in C++17 that we need to handle
14786     // separately.
14787     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14788         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14789       return VisitCallExpr(CXXOCE);
14790 
14791     enum {
14792       NoSequencing,
14793       LHSBeforeRHS,
14794       RHSBeforeLHS,
14795       LHSBeforeRest
14796     } SequencingKind;
14797     switch (CXXOCE->getOperator()) {
14798     case OO_Equal:
14799     case OO_PlusEqual:
14800     case OO_MinusEqual:
14801     case OO_StarEqual:
14802     case OO_SlashEqual:
14803     case OO_PercentEqual:
14804     case OO_CaretEqual:
14805     case OO_AmpEqual:
14806     case OO_PipeEqual:
14807     case OO_LessLessEqual:
14808     case OO_GreaterGreaterEqual:
14809       SequencingKind = RHSBeforeLHS;
14810       break;
14811 
14812     case OO_LessLess:
14813     case OO_GreaterGreater:
14814     case OO_AmpAmp:
14815     case OO_PipePipe:
14816     case OO_Comma:
14817     case OO_ArrowStar:
14818     case OO_Subscript:
14819       SequencingKind = LHSBeforeRHS;
14820       break;
14821 
14822     case OO_Call:
14823       SequencingKind = LHSBeforeRest;
14824       break;
14825 
14826     default:
14827       SequencingKind = NoSequencing;
14828       break;
14829     }
14830 
14831     if (SequencingKind == NoSequencing)
14832       return VisitCallExpr(CXXOCE);
14833 
14834     // This is a call, so all subexpressions are sequenced before the result.
14835     SequencedSubexpression Sequenced(*this);
14836 
14837     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14838       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14839              "Should only get there with C++17 and above!");
14840       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14841              "Should only get there with an overloaded binary operator"
14842              " or an overloaded call operator!");
14843 
14844       if (SequencingKind == LHSBeforeRest) {
14845         assert(CXXOCE->getOperator() == OO_Call &&
14846                "We should only have an overloaded call operator here!");
14847 
14848         // This is very similar to VisitCallExpr, except that we only have the
14849         // C++17 case. The postfix-expression is the first argument of the
14850         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14851         // are in the following arguments.
14852         //
14853         // Note that we intentionally do not visit the callee expression since
14854         // it is just a decayed reference to a function.
14855         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14856         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14857         SequenceTree::Seq OldRegion = Region;
14858 
14859         assert(CXXOCE->getNumArgs() >= 1 &&
14860                "An overloaded call operator must have at least one argument"
14861                " for the postfix-expression!");
14862         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14863         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14864                                           CXXOCE->getNumArgs() - 1);
14865 
14866         // Visit the postfix-expression first.
14867         {
14868           Region = PostfixExprRegion;
14869           SequencedSubexpression Sequenced(*this);
14870           Visit(PostfixExpr);
14871         }
14872 
14873         // Then visit the argument expressions.
14874         Region = ArgsRegion;
14875         for (const Expr *Arg : Args)
14876           Visit(Arg);
14877 
14878         Region = OldRegion;
14879         Tree.merge(PostfixExprRegion);
14880         Tree.merge(ArgsRegion);
14881       } else {
14882         assert(CXXOCE->getNumArgs() == 2 &&
14883                "Should only have two arguments here!");
14884         assert((SequencingKind == LHSBeforeRHS ||
14885                 SequencingKind == RHSBeforeLHS) &&
14886                "Unexpected sequencing kind!");
14887 
14888         // We do not visit the callee expression since it is just a decayed
14889         // reference to a function.
14890         const Expr *E1 = CXXOCE->getArg(0);
14891         const Expr *E2 = CXXOCE->getArg(1);
14892         if (SequencingKind == RHSBeforeLHS)
14893           std::swap(E1, E2);
14894 
14895         return VisitSequencedExpressions(E1, E2);
14896       }
14897     });
14898   }
14899 
14900   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14901     // This is a call, so all subexpressions are sequenced before the result.
14902     SequencedSubexpression Sequenced(*this);
14903 
14904     if (!CCE->isListInitialization())
14905       return VisitExpr(CCE);
14906 
14907     // In C++11, list initializations are sequenced.
14908     SmallVector<SequenceTree::Seq, 32> Elts;
14909     SequenceTree::Seq Parent = Region;
14910     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14911                                               E = CCE->arg_end();
14912          I != E; ++I) {
14913       Region = Tree.allocate(Parent);
14914       Elts.push_back(Region);
14915       Visit(*I);
14916     }
14917 
14918     // Forget that the initializers are sequenced.
14919     Region = Parent;
14920     for (unsigned I = 0; I < Elts.size(); ++I)
14921       Tree.merge(Elts[I]);
14922   }
14923 
14924   void VisitInitListExpr(const InitListExpr *ILE) {
14925     if (!SemaRef.getLangOpts().CPlusPlus11)
14926       return VisitExpr(ILE);
14927 
14928     // In C++11, list initializations are sequenced.
14929     SmallVector<SequenceTree::Seq, 32> Elts;
14930     SequenceTree::Seq Parent = Region;
14931     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14932       const Expr *E = ILE->getInit(I);
14933       if (!E)
14934         continue;
14935       Region = Tree.allocate(Parent);
14936       Elts.push_back(Region);
14937       Visit(E);
14938     }
14939 
14940     // Forget that the initializers are sequenced.
14941     Region = Parent;
14942     for (unsigned I = 0; I < Elts.size(); ++I)
14943       Tree.merge(Elts[I]);
14944   }
14945 };
14946 
14947 } // namespace
14948 
14949 void Sema::CheckUnsequencedOperations(const Expr *E) {
14950   SmallVector<const Expr *, 8> WorkList;
14951   WorkList.push_back(E);
14952   while (!WorkList.empty()) {
14953     const Expr *Item = WorkList.pop_back_val();
14954     SequenceChecker(*this, Item, WorkList);
14955   }
14956 }
14957 
14958 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14959                               bool IsConstexpr) {
14960   llvm::SaveAndRestore<bool> ConstantContext(
14961       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14962   CheckImplicitConversions(E, CheckLoc);
14963   if (!E->isInstantiationDependent())
14964     CheckUnsequencedOperations(E);
14965   if (!IsConstexpr && !E->isValueDependent())
14966     CheckForIntOverflow(E);
14967   DiagnoseMisalignedMembers();
14968 }
14969 
14970 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14971                                        FieldDecl *BitField,
14972                                        Expr *Init) {
14973   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14974 }
14975 
14976 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14977                                          SourceLocation Loc) {
14978   if (!PType->isVariablyModifiedType())
14979     return;
14980   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14981     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14982     return;
14983   }
14984   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14985     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14986     return;
14987   }
14988   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14989     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14990     return;
14991   }
14992 
14993   const ArrayType *AT = S.Context.getAsArrayType(PType);
14994   if (!AT)
14995     return;
14996 
14997   if (AT->getSizeModifier() != ArrayType::Star) {
14998     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14999     return;
15000   }
15001 
15002   S.Diag(Loc, diag::err_array_star_in_function_definition);
15003 }
15004 
15005 /// CheckParmsForFunctionDef - Check that the parameters of the given
15006 /// function are appropriate for the definition of a function. This
15007 /// takes care of any checks that cannot be performed on the
15008 /// declaration itself, e.g., that the types of each of the function
15009 /// parameters are complete.
15010 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
15011                                     bool CheckParameterNames) {
15012   bool HasInvalidParm = false;
15013   for (ParmVarDecl *Param : Parameters) {
15014     // C99 6.7.5.3p4: the parameters in a parameter type list in a
15015     // function declarator that is part of a function definition of
15016     // that function shall not have incomplete type.
15017     //
15018     // This is also C++ [dcl.fct]p6.
15019     if (!Param->isInvalidDecl() &&
15020         RequireCompleteType(Param->getLocation(), Param->getType(),
15021                             diag::err_typecheck_decl_incomplete_type)) {
15022       Param->setInvalidDecl();
15023       HasInvalidParm = true;
15024     }
15025 
15026     // C99 6.9.1p5: If the declarator includes a parameter type list, the
15027     // declaration of each parameter shall include an identifier.
15028     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15029         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15030       // Diagnose this as an extension in C17 and earlier.
15031       if (!getLangOpts().C2x)
15032         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15033     }
15034 
15035     // C99 6.7.5.3p12:
15036     //   If the function declarator is not part of a definition of that
15037     //   function, parameters may have incomplete type and may use the [*]
15038     //   notation in their sequences of declarator specifiers to specify
15039     //   variable length array types.
15040     QualType PType = Param->getOriginalType();
15041     // FIXME: This diagnostic should point the '[*]' if source-location
15042     // information is added for it.
15043     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
15044 
15045     // If the parameter is a c++ class type and it has to be destructed in the
15046     // callee function, declare the destructor so that it can be called by the
15047     // callee function. Do not perform any direct access check on the dtor here.
15048     if (!Param->isInvalidDecl()) {
15049       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15050         if (!ClassDecl->isInvalidDecl() &&
15051             !ClassDecl->hasIrrelevantDestructor() &&
15052             !ClassDecl->isDependentContext() &&
15053             ClassDecl->isParamDestroyedInCallee()) {
15054           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15055           MarkFunctionReferenced(Param->getLocation(), Destructor);
15056           DiagnoseUseOfDecl(Destructor, Param->getLocation());
15057         }
15058       }
15059     }
15060 
15061     // Parameters with the pass_object_size attribute only need to be marked
15062     // constant at function definitions. Because we lack information about
15063     // whether we're on a declaration or definition when we're instantiating the
15064     // attribute, we need to check for constness here.
15065     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15066       if (!Param->getType().isConstQualified())
15067         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
15068             << Attr->getSpelling() << 1;
15069 
15070     // Check for parameter names shadowing fields from the class.
15071     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15072       // The owning context for the parameter should be the function, but we
15073       // want to see if this function's declaration context is a record.
15074       DeclContext *DC = Param->getDeclContext();
15075       if (DC && DC->isFunctionOrMethod()) {
15076         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
15077           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
15078                                      RD, /*DeclIsField*/ false);
15079       }
15080     }
15081   }
15082 
15083   return HasInvalidParm;
15084 }
15085 
15086 Optional<std::pair<CharUnits, CharUnits>>
15087 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
15088 
15089 /// Compute the alignment and offset of the base class object given the
15090 /// derived-to-base cast expression and the alignment and offset of the derived
15091 /// class object.
15092 static std::pair<CharUnits, CharUnits>
15093 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
15094                                    CharUnits BaseAlignment, CharUnits Offset,
15095                                    ASTContext &Ctx) {
15096   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15097        ++PathI) {
15098     const CXXBaseSpecifier *Base = *PathI;
15099     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15100     if (Base->isVirtual()) {
15101       // The complete object may have a lower alignment than the non-virtual
15102       // alignment of the base, in which case the base may be misaligned. Choose
15103       // the smaller of the non-virtual alignment and BaseAlignment, which is a
15104       // conservative lower bound of the complete object alignment.
15105       CharUnits NonVirtualAlignment =
15106           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
15107       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15108       Offset = CharUnits::Zero();
15109     } else {
15110       const ASTRecordLayout &RL =
15111           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
15112       Offset += RL.getBaseClassOffset(BaseDecl);
15113     }
15114     DerivedType = Base->getType();
15115   }
15116 
15117   return std::make_pair(BaseAlignment, Offset);
15118 }
15119 
15120 /// Compute the alignment and offset of a binary additive operator.
15121 static Optional<std::pair<CharUnits, CharUnits>>
15122 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
15123                                      bool IsSub, ASTContext &Ctx) {
15124   QualType PointeeType = PtrE->getType()->getPointeeType();
15125 
15126   if (!PointeeType->isConstantSizeType())
15127     return llvm::None;
15128 
15129   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
15130 
15131   if (!P)
15132     return llvm::None;
15133 
15134   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
15135   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15136     CharUnits Offset = EltSize * IdxRes->getExtValue();
15137     if (IsSub)
15138       Offset = -Offset;
15139     return std::make_pair(P->first, P->second + Offset);
15140   }
15141 
15142   // If the integer expression isn't a constant expression, compute the lower
15143   // bound of the alignment using the alignment and offset of the pointer
15144   // expression and the element size.
15145   return std::make_pair(
15146       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15147       CharUnits::Zero());
15148 }
15149 
15150 /// This helper function takes an lvalue expression and returns the alignment of
15151 /// a VarDecl and a constant offset from the VarDecl.
15152 Optional<std::pair<CharUnits, CharUnits>>
15153 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
15154   E = E->IgnoreParens();
15155   switch (E->getStmtClass()) {
15156   default:
15157     break;
15158   case Stmt::CStyleCastExprClass:
15159   case Stmt::CXXStaticCastExprClass:
15160   case Stmt::ImplicitCastExprClass: {
15161     auto *CE = cast<CastExpr>(E);
15162     const Expr *From = CE->getSubExpr();
15163     switch (CE->getCastKind()) {
15164     default:
15165       break;
15166     case CK_NoOp:
15167       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15168     case CK_UncheckedDerivedToBase:
15169     case CK_DerivedToBase: {
15170       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15171       if (!P)
15172         break;
15173       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15174                                                 P->second, Ctx);
15175     }
15176     }
15177     break;
15178   }
15179   case Stmt::ArraySubscriptExprClass: {
15180     auto *ASE = cast<ArraySubscriptExpr>(E);
15181     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
15182                                                 false, Ctx);
15183   }
15184   case Stmt::DeclRefExprClass: {
15185     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15186       // FIXME: If VD is captured by copy or is an escaping __block variable,
15187       // use the alignment of VD's type.
15188       if (!VD->getType()->isReferenceType())
15189         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15190       if (VD->hasInit())
15191         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15192     }
15193     break;
15194   }
15195   case Stmt::MemberExprClass: {
15196     auto *ME = cast<MemberExpr>(E);
15197     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15198     if (!FD || FD->getType()->isReferenceType() ||
15199         FD->getParent()->isInvalidDecl())
15200       break;
15201     Optional<std::pair<CharUnits, CharUnits>> P;
15202     if (ME->isArrow())
15203       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15204     else
15205       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15206     if (!P)
15207       break;
15208     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15209     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15210     return std::make_pair(P->first,
15211                           P->second + CharUnits::fromQuantity(Offset));
15212   }
15213   case Stmt::UnaryOperatorClass: {
15214     auto *UO = cast<UnaryOperator>(E);
15215     switch (UO->getOpcode()) {
15216     default:
15217       break;
15218     case UO_Deref:
15219       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
15220     }
15221     break;
15222   }
15223   case Stmt::BinaryOperatorClass: {
15224     auto *BO = cast<BinaryOperator>(E);
15225     auto Opcode = BO->getOpcode();
15226     switch (Opcode) {
15227     default:
15228       break;
15229     case BO_Comma:
15230       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
15231     }
15232     break;
15233   }
15234   }
15235   return llvm::None;
15236 }
15237 
15238 /// This helper function takes a pointer expression and returns the alignment of
15239 /// a VarDecl and a constant offset from the VarDecl.
15240 Optional<std::pair<CharUnits, CharUnits>>
15241 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
15242   E = E->IgnoreParens();
15243   switch (E->getStmtClass()) {
15244   default:
15245     break;
15246   case Stmt::CStyleCastExprClass:
15247   case Stmt::CXXStaticCastExprClass:
15248   case Stmt::ImplicitCastExprClass: {
15249     auto *CE = cast<CastExpr>(E);
15250     const Expr *From = CE->getSubExpr();
15251     switch (CE->getCastKind()) {
15252     default:
15253       break;
15254     case CK_NoOp:
15255       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15256     case CK_ArrayToPointerDecay:
15257       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15258     case CK_UncheckedDerivedToBase:
15259     case CK_DerivedToBase: {
15260       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15261       if (!P)
15262         break;
15263       return getDerivedToBaseAlignmentAndOffset(
15264           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15265     }
15266     }
15267     break;
15268   }
15269   case Stmt::CXXThisExprClass: {
15270     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15271     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
15272     return std::make_pair(Alignment, CharUnits::Zero());
15273   }
15274   case Stmt::UnaryOperatorClass: {
15275     auto *UO = cast<UnaryOperator>(E);
15276     if (UO->getOpcode() == UO_AddrOf)
15277       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
15278     break;
15279   }
15280   case Stmt::BinaryOperatorClass: {
15281     auto *BO = cast<BinaryOperator>(E);
15282     auto Opcode = BO->getOpcode();
15283     switch (Opcode) {
15284     default:
15285       break;
15286     case BO_Add:
15287     case BO_Sub: {
15288       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15289       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15290         std::swap(LHS, RHS);
15291       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15292                                                   Ctx);
15293     }
15294     case BO_Comma:
15295       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15296     }
15297     break;
15298   }
15299   }
15300   return llvm::None;
15301 }
15302 
15303 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
15304   // See if we can compute the alignment of a VarDecl and an offset from it.
15305   Optional<std::pair<CharUnits, CharUnits>> P =
15306       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
15307 
15308   if (P)
15309     return P->first.alignmentAtOffset(P->second);
15310 
15311   // If that failed, return the type's alignment.
15312   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
15313 }
15314 
15315 /// CheckCastAlign - Implements -Wcast-align, which warns when a
15316 /// pointer cast increases the alignment requirements.
15317 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
15318   // This is actually a lot of work to potentially be doing on every
15319   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15320   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15321     return;
15322 
15323   // Ignore dependent types.
15324   if (T->isDependentType() || Op->getType()->isDependentType())
15325     return;
15326 
15327   // Require that the destination be a pointer type.
15328   const PointerType *DestPtr = T->getAs<PointerType>();
15329   if (!DestPtr) return;
15330 
15331   // If the destination has alignment 1, we're done.
15332   QualType DestPointee = DestPtr->getPointeeType();
15333   if (DestPointee->isIncompleteType()) return;
15334   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15335   if (DestAlign.isOne()) return;
15336 
15337   // Require that the source be a pointer type.
15338   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15339   if (!SrcPtr) return;
15340   QualType SrcPointee = SrcPtr->getPointeeType();
15341 
15342   // Explicitly allow casts from cv void*.  We already implicitly
15343   // allowed casts to cv void*, since they have alignment 1.
15344   // Also allow casts involving incomplete types, which implicitly
15345   // includes 'void'.
15346   if (SrcPointee->isIncompleteType()) return;
15347 
15348   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15349 
15350   if (SrcAlign >= DestAlign) return;
15351 
15352   Diag(TRange.getBegin(), diag::warn_cast_align)
15353     << Op->getType() << T
15354     << static_cast<unsigned>(SrcAlign.getQuantity())
15355     << static_cast<unsigned>(DestAlign.getQuantity())
15356     << TRange << Op->getSourceRange();
15357 }
15358 
15359 /// Check whether this array fits the idiom of a size-one tail padded
15360 /// array member of a struct.
15361 ///
15362 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
15363 /// commonly used to emulate flexible arrays in C89 code.
15364 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
15365                                     const NamedDecl *ND) {
15366   if (Size != 1 || !ND) return false;
15367 
15368   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
15369   if (!FD) return false;
15370 
15371   // Don't consider sizes resulting from macro expansions or template argument
15372   // substitution to form C89 tail-padded arrays.
15373 
15374   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
15375   while (TInfo) {
15376     TypeLoc TL = TInfo->getTypeLoc();
15377     // Look through typedefs.
15378     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
15379       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
15380       TInfo = TDL->getTypeSourceInfo();
15381       continue;
15382     }
15383     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
15384       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
15385       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
15386         return false;
15387     }
15388     break;
15389   }
15390 
15391   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
15392   if (!RD) return false;
15393   if (RD->isUnion()) return false;
15394   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15395     if (!CRD->isStandardLayout()) return false;
15396   }
15397 
15398   // See if this is the last field decl in the record.
15399   const Decl *D = FD;
15400   while ((D = D->getNextDeclInContext()))
15401     if (isa<FieldDecl>(D))
15402       return false;
15403   return true;
15404 }
15405 
15406 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15407                             const ArraySubscriptExpr *ASE,
15408                             bool AllowOnePastEnd, bool IndexNegated) {
15409   // Already diagnosed by the constant evaluator.
15410   if (isConstantEvaluated())
15411     return;
15412 
15413   IndexExpr = IndexExpr->IgnoreParenImpCasts();
15414   if (IndexExpr->isValueDependent())
15415     return;
15416 
15417   const Type *EffectiveType =
15418       BaseExpr->getType()->getPointeeOrArrayElementType();
15419   BaseExpr = BaseExpr->IgnoreParenCasts();
15420   const ConstantArrayType *ArrayTy =
15421       Context.getAsConstantArrayType(BaseExpr->getType());
15422 
15423   const Type *BaseType =
15424       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15425   bool IsUnboundedArray = (BaseType == nullptr);
15426   if (EffectiveType->isDependentType() ||
15427       (!IsUnboundedArray && BaseType->isDependentType()))
15428     return;
15429 
15430   Expr::EvalResult Result;
15431   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15432     return;
15433 
15434   llvm::APSInt index = Result.Val.getInt();
15435   if (IndexNegated) {
15436     index.setIsUnsigned(false);
15437     index = -index;
15438   }
15439 
15440   const NamedDecl *ND = nullptr;
15441   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15442     ND = DRE->getDecl();
15443   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
15444     ND = ME->getMemberDecl();
15445 
15446   if (IsUnboundedArray) {
15447     if (index.isUnsigned() || !index.isNegative()) {
15448       const auto &ASTC = getASTContext();
15449       unsigned AddrBits =
15450           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
15451               EffectiveType->getCanonicalTypeInternal()));
15452       if (index.getBitWidth() < AddrBits)
15453         index = index.zext(AddrBits);
15454       Optional<CharUnits> ElemCharUnits =
15455           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15456       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15457       // pointer) bounds-checking isn't meaningful.
15458       if (!ElemCharUnits)
15459         return;
15460       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15461       // If index has more active bits than address space, we already know
15462       // we have a bounds violation to warn about.  Otherwise, compute
15463       // address of (index + 1)th element, and warn about bounds violation
15464       // only if that address exceeds address space.
15465       if (index.getActiveBits() <= AddrBits) {
15466         bool Overflow;
15467         llvm::APInt Product(index);
15468         Product += 1;
15469         Product = Product.umul_ov(ElemBytes, Overflow);
15470         if (!Overflow && Product.getActiveBits() <= AddrBits)
15471           return;
15472       }
15473 
15474       // Need to compute max possible elements in address space, since that
15475       // is included in diag message.
15476       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15477       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15478       MaxElems += 1;
15479       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15480       MaxElems = MaxElems.udiv(ElemBytes);
15481 
15482       unsigned DiagID =
15483           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15484               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15485 
15486       // Diag message shows element size in bits and in "bytes" (platform-
15487       // dependent CharUnits)
15488       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15489                           PDiag(DiagID)
15490                               << toString(index, 10, true) << AddrBits
15491                               << (unsigned)ASTC.toBits(*ElemCharUnits)
15492                               << toString(ElemBytes, 10, false)
15493                               << toString(MaxElems, 10, false)
15494                               << (unsigned)MaxElems.getLimitedValue(~0U)
15495                               << IndexExpr->getSourceRange());
15496 
15497       if (!ND) {
15498         // Try harder to find a NamedDecl to point at in the note.
15499         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15500           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15501         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15502           ND = DRE->getDecl();
15503         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15504           ND = ME->getMemberDecl();
15505       }
15506 
15507       if (ND)
15508         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15509                             PDiag(diag::note_array_declared_here) << ND);
15510     }
15511     return;
15512   }
15513 
15514   if (index.isUnsigned() || !index.isNegative()) {
15515     // It is possible that the type of the base expression after
15516     // IgnoreParenCasts is incomplete, even though the type of the base
15517     // expression before IgnoreParenCasts is complete (see PR39746 for an
15518     // example). In this case we have no information about whether the array
15519     // access exceeds the array bounds. However we can still diagnose an array
15520     // access which precedes the array bounds.
15521     if (BaseType->isIncompleteType())
15522       return;
15523 
15524     llvm::APInt size = ArrayTy->getSize();
15525     if (!size.isStrictlyPositive())
15526       return;
15527 
15528     if (BaseType != EffectiveType) {
15529       // Make sure we're comparing apples to apples when comparing index to size
15530       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15531       uint64_t array_typesize = Context.getTypeSize(BaseType);
15532       // Handle ptrarith_typesize being zero, such as when casting to void*
15533       if (!ptrarith_typesize) ptrarith_typesize = 1;
15534       if (ptrarith_typesize != array_typesize) {
15535         // There's a cast to a different size type involved
15536         uint64_t ratio = array_typesize / ptrarith_typesize;
15537         // TODO: Be smarter about handling cases where array_typesize is not a
15538         // multiple of ptrarith_typesize
15539         if (ptrarith_typesize * ratio == array_typesize)
15540           size *= llvm::APInt(size.getBitWidth(), ratio);
15541       }
15542     }
15543 
15544     if (size.getBitWidth() > index.getBitWidth())
15545       index = index.zext(size.getBitWidth());
15546     else if (size.getBitWidth() < index.getBitWidth())
15547       size = size.zext(index.getBitWidth());
15548 
15549     // For array subscripting the index must be less than size, but for pointer
15550     // arithmetic also allow the index (offset) to be equal to size since
15551     // computing the next address after the end of the array is legal and
15552     // commonly done e.g. in C++ iterators and range-based for loops.
15553     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15554       return;
15555 
15556     // Also don't warn for arrays of size 1 which are members of some
15557     // structure. These are often used to approximate flexible arrays in C89
15558     // code.
15559     if (IsTailPaddedMemberArray(*this, size, ND))
15560       return;
15561 
15562     // Suppress the warning if the subscript expression (as identified by the
15563     // ']' location) and the index expression are both from macro expansions
15564     // within a system header.
15565     if (ASE) {
15566       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15567           ASE->getRBracketLoc());
15568       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15569         SourceLocation IndexLoc =
15570             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15571         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15572           return;
15573       }
15574     }
15575 
15576     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15577                           : diag::warn_ptr_arith_exceeds_bounds;
15578 
15579     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15580                         PDiag(DiagID) << toString(index, 10, true)
15581                                       << toString(size, 10, true)
15582                                       << (unsigned)size.getLimitedValue(~0U)
15583                                       << IndexExpr->getSourceRange());
15584   } else {
15585     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15586     if (!ASE) {
15587       DiagID = diag::warn_ptr_arith_precedes_bounds;
15588       if (index.isNegative()) index = -index;
15589     }
15590 
15591     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15592                         PDiag(DiagID) << toString(index, 10, true)
15593                                       << IndexExpr->getSourceRange());
15594   }
15595 
15596   if (!ND) {
15597     // Try harder to find a NamedDecl to point at in the note.
15598     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15599       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15600     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15601       ND = DRE->getDecl();
15602     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15603       ND = ME->getMemberDecl();
15604   }
15605 
15606   if (ND)
15607     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15608                         PDiag(diag::note_array_declared_here) << ND);
15609 }
15610 
15611 void Sema::CheckArrayAccess(const Expr *expr) {
15612   int AllowOnePastEnd = 0;
15613   while (expr) {
15614     expr = expr->IgnoreParenImpCasts();
15615     switch (expr->getStmtClass()) {
15616       case Stmt::ArraySubscriptExprClass: {
15617         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15618         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15619                          AllowOnePastEnd > 0);
15620         expr = ASE->getBase();
15621         break;
15622       }
15623       case Stmt::MemberExprClass: {
15624         expr = cast<MemberExpr>(expr)->getBase();
15625         break;
15626       }
15627       case Stmt::OMPArraySectionExprClass: {
15628         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15629         if (ASE->getLowerBound())
15630           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15631                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15632         return;
15633       }
15634       case Stmt::UnaryOperatorClass: {
15635         // Only unwrap the * and & unary operators
15636         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15637         expr = UO->getSubExpr();
15638         switch (UO->getOpcode()) {
15639           case UO_AddrOf:
15640             AllowOnePastEnd++;
15641             break;
15642           case UO_Deref:
15643             AllowOnePastEnd--;
15644             break;
15645           default:
15646             return;
15647         }
15648         break;
15649       }
15650       case Stmt::ConditionalOperatorClass: {
15651         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15652         if (const Expr *lhs = cond->getLHS())
15653           CheckArrayAccess(lhs);
15654         if (const Expr *rhs = cond->getRHS())
15655           CheckArrayAccess(rhs);
15656         return;
15657       }
15658       case Stmt::CXXOperatorCallExprClass: {
15659         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15660         for (const auto *Arg : OCE->arguments())
15661           CheckArrayAccess(Arg);
15662         return;
15663       }
15664       default:
15665         return;
15666     }
15667   }
15668 }
15669 
15670 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15671 
15672 namespace {
15673 
15674 struct RetainCycleOwner {
15675   VarDecl *Variable = nullptr;
15676   SourceRange Range;
15677   SourceLocation Loc;
15678   bool Indirect = false;
15679 
15680   RetainCycleOwner() = default;
15681 
15682   void setLocsFrom(Expr *e) {
15683     Loc = e->getExprLoc();
15684     Range = e->getSourceRange();
15685   }
15686 };
15687 
15688 } // namespace
15689 
15690 /// Consider whether capturing the given variable can possibly lead to
15691 /// a retain cycle.
15692 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15693   // In ARC, it's captured strongly iff the variable has __strong
15694   // lifetime.  In MRR, it's captured strongly if the variable is
15695   // __block and has an appropriate type.
15696   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15697     return false;
15698 
15699   owner.Variable = var;
15700   if (ref)
15701     owner.setLocsFrom(ref);
15702   return true;
15703 }
15704 
15705 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15706   while (true) {
15707     e = e->IgnoreParens();
15708     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15709       switch (cast->getCastKind()) {
15710       case CK_BitCast:
15711       case CK_LValueBitCast:
15712       case CK_LValueToRValue:
15713       case CK_ARCReclaimReturnedObject:
15714         e = cast->getSubExpr();
15715         continue;
15716 
15717       default:
15718         return false;
15719       }
15720     }
15721 
15722     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15723       ObjCIvarDecl *ivar = ref->getDecl();
15724       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15725         return false;
15726 
15727       // Try to find a retain cycle in the base.
15728       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15729         return false;
15730 
15731       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15732       owner.Indirect = true;
15733       return true;
15734     }
15735 
15736     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15737       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15738       if (!var) return false;
15739       return considerVariable(var, ref, owner);
15740     }
15741 
15742     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15743       if (member->isArrow()) return false;
15744 
15745       // Don't count this as an indirect ownership.
15746       e = member->getBase();
15747       continue;
15748     }
15749 
15750     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15751       // Only pay attention to pseudo-objects on property references.
15752       ObjCPropertyRefExpr *pre
15753         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15754                                               ->IgnoreParens());
15755       if (!pre) return false;
15756       if (pre->isImplicitProperty()) return false;
15757       ObjCPropertyDecl *property = pre->getExplicitProperty();
15758       if (!property->isRetaining() &&
15759           !(property->getPropertyIvarDecl() &&
15760             property->getPropertyIvarDecl()->getType()
15761               .getObjCLifetime() == Qualifiers::OCL_Strong))
15762           return false;
15763 
15764       owner.Indirect = true;
15765       if (pre->isSuperReceiver()) {
15766         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15767         if (!owner.Variable)
15768           return false;
15769         owner.Loc = pre->getLocation();
15770         owner.Range = pre->getSourceRange();
15771         return true;
15772       }
15773       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15774                               ->getSourceExpr());
15775       continue;
15776     }
15777 
15778     // Array ivars?
15779 
15780     return false;
15781   }
15782 }
15783 
15784 namespace {
15785 
15786   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15787     ASTContext &Context;
15788     VarDecl *Variable;
15789     Expr *Capturer = nullptr;
15790     bool VarWillBeReased = false;
15791 
15792     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15793         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15794           Context(Context), Variable(variable) {}
15795 
15796     void VisitDeclRefExpr(DeclRefExpr *ref) {
15797       if (ref->getDecl() == Variable && !Capturer)
15798         Capturer = ref;
15799     }
15800 
15801     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15802       if (Capturer) return;
15803       Visit(ref->getBase());
15804       if (Capturer && ref->isFreeIvar())
15805         Capturer = ref;
15806     }
15807 
15808     void VisitBlockExpr(BlockExpr *block) {
15809       // Look inside nested blocks
15810       if (block->getBlockDecl()->capturesVariable(Variable))
15811         Visit(block->getBlockDecl()->getBody());
15812     }
15813 
15814     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15815       if (Capturer) return;
15816       if (OVE->getSourceExpr())
15817         Visit(OVE->getSourceExpr());
15818     }
15819 
15820     void VisitBinaryOperator(BinaryOperator *BinOp) {
15821       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15822         return;
15823       Expr *LHS = BinOp->getLHS();
15824       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15825         if (DRE->getDecl() != Variable)
15826           return;
15827         if (Expr *RHS = BinOp->getRHS()) {
15828           RHS = RHS->IgnoreParenCasts();
15829           Optional<llvm::APSInt> Value;
15830           VarWillBeReased =
15831               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15832                *Value == 0);
15833         }
15834       }
15835     }
15836   };
15837 
15838 } // namespace
15839 
15840 /// Check whether the given argument is a block which captures a
15841 /// variable.
15842 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15843   assert(owner.Variable && owner.Loc.isValid());
15844 
15845   e = e->IgnoreParenCasts();
15846 
15847   // Look through [^{...} copy] and Block_copy(^{...}).
15848   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15849     Selector Cmd = ME->getSelector();
15850     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15851       e = ME->getInstanceReceiver();
15852       if (!e)
15853         return nullptr;
15854       e = e->IgnoreParenCasts();
15855     }
15856   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15857     if (CE->getNumArgs() == 1) {
15858       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15859       if (Fn) {
15860         const IdentifierInfo *FnI = Fn->getIdentifier();
15861         if (FnI && FnI->isStr("_Block_copy")) {
15862           e = CE->getArg(0)->IgnoreParenCasts();
15863         }
15864       }
15865     }
15866   }
15867 
15868   BlockExpr *block = dyn_cast<BlockExpr>(e);
15869   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15870     return nullptr;
15871 
15872   FindCaptureVisitor visitor(S.Context, owner.Variable);
15873   visitor.Visit(block->getBlockDecl()->getBody());
15874   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15875 }
15876 
15877 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15878                                 RetainCycleOwner &owner) {
15879   assert(capturer);
15880   assert(owner.Variable && owner.Loc.isValid());
15881 
15882   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15883     << owner.Variable << capturer->getSourceRange();
15884   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15885     << owner.Indirect << owner.Range;
15886 }
15887 
15888 /// Check for a keyword selector that starts with the word 'add' or
15889 /// 'set'.
15890 static bool isSetterLikeSelector(Selector sel) {
15891   if (sel.isUnarySelector()) return false;
15892 
15893   StringRef str = sel.getNameForSlot(0);
15894   while (!str.empty() && str.front() == '_') str = str.substr(1);
15895   if (str.startswith("set"))
15896     str = str.substr(3);
15897   else if (str.startswith("add")) {
15898     // Specially allow 'addOperationWithBlock:'.
15899     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15900       return false;
15901     str = str.substr(3);
15902   }
15903   else
15904     return false;
15905 
15906   if (str.empty()) return true;
15907   return !isLowercase(str.front());
15908 }
15909 
15910 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15911                                                     ObjCMessageExpr *Message) {
15912   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15913                                                 Message->getReceiverInterface(),
15914                                                 NSAPI::ClassId_NSMutableArray);
15915   if (!IsMutableArray) {
15916     return None;
15917   }
15918 
15919   Selector Sel = Message->getSelector();
15920 
15921   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15922     S.NSAPIObj->getNSArrayMethodKind(Sel);
15923   if (!MKOpt) {
15924     return None;
15925   }
15926 
15927   NSAPI::NSArrayMethodKind MK = *MKOpt;
15928 
15929   switch (MK) {
15930     case NSAPI::NSMutableArr_addObject:
15931     case NSAPI::NSMutableArr_insertObjectAtIndex:
15932     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15933       return 0;
15934     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15935       return 1;
15936 
15937     default:
15938       return None;
15939   }
15940 
15941   return None;
15942 }
15943 
15944 static
15945 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15946                                                   ObjCMessageExpr *Message) {
15947   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15948                                             Message->getReceiverInterface(),
15949                                             NSAPI::ClassId_NSMutableDictionary);
15950   if (!IsMutableDictionary) {
15951     return None;
15952   }
15953 
15954   Selector Sel = Message->getSelector();
15955 
15956   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15957     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15958   if (!MKOpt) {
15959     return None;
15960   }
15961 
15962   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15963 
15964   switch (MK) {
15965     case NSAPI::NSMutableDict_setObjectForKey:
15966     case NSAPI::NSMutableDict_setValueForKey:
15967     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15968       return 0;
15969 
15970     default:
15971       return None;
15972   }
15973 
15974   return None;
15975 }
15976 
15977 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15978   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15979                                                 Message->getReceiverInterface(),
15980                                                 NSAPI::ClassId_NSMutableSet);
15981 
15982   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15983                                             Message->getReceiverInterface(),
15984                                             NSAPI::ClassId_NSMutableOrderedSet);
15985   if (!IsMutableSet && !IsMutableOrderedSet) {
15986     return None;
15987   }
15988 
15989   Selector Sel = Message->getSelector();
15990 
15991   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15992   if (!MKOpt) {
15993     return None;
15994   }
15995 
15996   NSAPI::NSSetMethodKind MK = *MKOpt;
15997 
15998   switch (MK) {
15999     case NSAPI::NSMutableSet_addObject:
16000     case NSAPI::NSOrderedSet_setObjectAtIndex:
16001     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
16002     case NSAPI::NSOrderedSet_insertObjectAtIndex:
16003       return 0;
16004     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
16005       return 1;
16006   }
16007 
16008   return None;
16009 }
16010 
16011 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
16012   if (!Message->isInstanceMessage()) {
16013     return;
16014   }
16015 
16016   Optional<int> ArgOpt;
16017 
16018   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
16019       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
16020       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
16021     return;
16022   }
16023 
16024   int ArgIndex = *ArgOpt;
16025 
16026   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
16027   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
16028     Arg = OE->getSourceExpr()->IgnoreImpCasts();
16029   }
16030 
16031   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
16032     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
16033       if (ArgRE->isObjCSelfExpr()) {
16034         Diag(Message->getSourceRange().getBegin(),
16035              diag::warn_objc_circular_container)
16036           << ArgRE->getDecl() << StringRef("'super'");
16037       }
16038     }
16039   } else {
16040     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
16041 
16042     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
16043       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
16044     }
16045 
16046     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
16047       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
16048         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
16049           ValueDecl *Decl = ReceiverRE->getDecl();
16050           Diag(Message->getSourceRange().getBegin(),
16051                diag::warn_objc_circular_container)
16052             << Decl << Decl;
16053           if (!ArgRE->isObjCSelfExpr()) {
16054             Diag(Decl->getLocation(),
16055                  diag::note_objc_circular_container_declared_here)
16056               << Decl;
16057           }
16058         }
16059       }
16060     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
16061       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
16062         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
16063           ObjCIvarDecl *Decl = IvarRE->getDecl();
16064           Diag(Message->getSourceRange().getBegin(),
16065                diag::warn_objc_circular_container)
16066             << Decl << Decl;
16067           Diag(Decl->getLocation(),
16068                diag::note_objc_circular_container_declared_here)
16069             << Decl;
16070         }
16071       }
16072     }
16073   }
16074 }
16075 
16076 /// Check a message send to see if it's likely to cause a retain cycle.
16077 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
16078   // Only check instance methods whose selector looks like a setter.
16079   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
16080     return;
16081 
16082   // Try to find a variable that the receiver is strongly owned by.
16083   RetainCycleOwner owner;
16084   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
16085     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
16086       return;
16087   } else {
16088     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
16089     owner.Variable = getCurMethodDecl()->getSelfDecl();
16090     owner.Loc = msg->getSuperLoc();
16091     owner.Range = msg->getSuperLoc();
16092   }
16093 
16094   // Check whether the receiver is captured by any of the arguments.
16095   const ObjCMethodDecl *MD = msg->getMethodDecl();
16096   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
16097     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
16098       // noescape blocks should not be retained by the method.
16099       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
16100         continue;
16101       return diagnoseRetainCycle(*this, capturer, owner);
16102     }
16103   }
16104 }
16105 
16106 /// Check a property assign to see if it's likely to cause a retain cycle.
16107 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
16108   RetainCycleOwner owner;
16109   if (!findRetainCycleOwner(*this, receiver, owner))
16110     return;
16111 
16112   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
16113     diagnoseRetainCycle(*this, capturer, owner);
16114 }
16115 
16116 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
16117   RetainCycleOwner Owner;
16118   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
16119     return;
16120 
16121   // Because we don't have an expression for the variable, we have to set the
16122   // location explicitly here.
16123   Owner.Loc = Var->getLocation();
16124   Owner.Range = Var->getSourceRange();
16125 
16126   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
16127     diagnoseRetainCycle(*this, Capturer, Owner);
16128 }
16129 
16130 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
16131                                      Expr *RHS, bool isProperty) {
16132   // Check if RHS is an Objective-C object literal, which also can get
16133   // immediately zapped in a weak reference.  Note that we explicitly
16134   // allow ObjCStringLiterals, since those are designed to never really die.
16135   RHS = RHS->IgnoreParenImpCasts();
16136 
16137   // This enum needs to match with the 'select' in
16138   // warn_objc_arc_literal_assign (off-by-1).
16139   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
16140   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
16141     return false;
16142 
16143   S.Diag(Loc, diag::warn_arc_literal_assign)
16144     << (unsigned) Kind
16145     << (isProperty ? 0 : 1)
16146     << RHS->getSourceRange();
16147 
16148   return true;
16149 }
16150 
16151 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
16152                                     Qualifiers::ObjCLifetime LT,
16153                                     Expr *RHS, bool isProperty) {
16154   // Strip off any implicit cast added to get to the one ARC-specific.
16155   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16156     if (cast->getCastKind() == CK_ARCConsumeObject) {
16157       S.Diag(Loc, diag::warn_arc_retained_assign)
16158         << (LT == Qualifiers::OCL_ExplicitNone)
16159         << (isProperty ? 0 : 1)
16160         << RHS->getSourceRange();
16161       return true;
16162     }
16163     RHS = cast->getSubExpr();
16164   }
16165 
16166   if (LT == Qualifiers::OCL_Weak &&
16167       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16168     return true;
16169 
16170   return false;
16171 }
16172 
16173 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
16174                               QualType LHS, Expr *RHS) {
16175   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
16176 
16177   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
16178     return false;
16179 
16180   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
16181     return true;
16182 
16183   return false;
16184 }
16185 
16186 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
16187                               Expr *LHS, Expr *RHS) {
16188   QualType LHSType;
16189   // PropertyRef on LHS type need be directly obtained from
16190   // its declaration as it has a PseudoType.
16191   ObjCPropertyRefExpr *PRE
16192     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
16193   if (PRE && !PRE->isImplicitProperty()) {
16194     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16195     if (PD)
16196       LHSType = PD->getType();
16197   }
16198 
16199   if (LHSType.isNull())
16200     LHSType = LHS->getType();
16201 
16202   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
16203 
16204   if (LT == Qualifiers::OCL_Weak) {
16205     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
16206       getCurFunction()->markSafeWeakUse(LHS);
16207   }
16208 
16209   if (checkUnsafeAssigns(Loc, LHSType, RHS))
16210     return;
16211 
16212   // FIXME. Check for other life times.
16213   if (LT != Qualifiers::OCL_None)
16214     return;
16215 
16216   if (PRE) {
16217     if (PRE->isImplicitProperty())
16218       return;
16219     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16220     if (!PD)
16221       return;
16222 
16223     unsigned Attributes = PD->getPropertyAttributes();
16224     if (Attributes & ObjCPropertyAttribute::kind_assign) {
16225       // when 'assign' attribute was not explicitly specified
16226       // by user, ignore it and rely on property type itself
16227       // for lifetime info.
16228       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16229       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16230           LHSType->isObjCRetainableType())
16231         return;
16232 
16233       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16234         if (cast->getCastKind() == CK_ARCConsumeObject) {
16235           Diag(Loc, diag::warn_arc_retained_property_assign)
16236           << RHS->getSourceRange();
16237           return;
16238         }
16239         RHS = cast->getSubExpr();
16240       }
16241     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16242       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
16243         return;
16244     }
16245   }
16246 }
16247 
16248 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16249 
16250 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16251                                         SourceLocation StmtLoc,
16252                                         const NullStmt *Body) {
16253   // Do not warn if the body is a macro that expands to nothing, e.g:
16254   //
16255   // #define CALL(x)
16256   // if (condition)
16257   //   CALL(0);
16258   if (Body->hasLeadingEmptyMacro())
16259     return false;
16260 
16261   // Get line numbers of statement and body.
16262   bool StmtLineInvalid;
16263   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16264                                                       &StmtLineInvalid);
16265   if (StmtLineInvalid)
16266     return false;
16267 
16268   bool BodyLineInvalid;
16269   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16270                                                       &BodyLineInvalid);
16271   if (BodyLineInvalid)
16272     return false;
16273 
16274   // Warn if null statement and body are on the same line.
16275   if (StmtLine != BodyLine)
16276     return false;
16277 
16278   return true;
16279 }
16280 
16281 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
16282                                  const Stmt *Body,
16283                                  unsigned DiagID) {
16284   // Since this is a syntactic check, don't emit diagnostic for template
16285   // instantiations, this just adds noise.
16286   if (CurrentInstantiationScope)
16287     return;
16288 
16289   // The body should be a null statement.
16290   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16291   if (!NBody)
16292     return;
16293 
16294   // Do the usual checks.
16295   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16296     return;
16297 
16298   Diag(NBody->getSemiLoc(), DiagID);
16299   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16300 }
16301 
16302 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
16303                                  const Stmt *PossibleBody) {
16304   assert(!CurrentInstantiationScope); // Ensured by caller
16305 
16306   SourceLocation StmtLoc;
16307   const Stmt *Body;
16308   unsigned DiagID;
16309   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16310     StmtLoc = FS->getRParenLoc();
16311     Body = FS->getBody();
16312     DiagID = diag::warn_empty_for_body;
16313   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16314     StmtLoc = WS->getCond()->getSourceRange().getEnd();
16315     Body = WS->getBody();
16316     DiagID = diag::warn_empty_while_body;
16317   } else
16318     return; // Neither `for' nor `while'.
16319 
16320   // The body should be a null statement.
16321   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16322   if (!NBody)
16323     return;
16324 
16325   // Skip expensive checks if diagnostic is disabled.
16326   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16327     return;
16328 
16329   // Do the usual checks.
16330   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16331     return;
16332 
16333   // `for(...);' and `while(...);' are popular idioms, so in order to keep
16334   // noise level low, emit diagnostics only if for/while is followed by a
16335   // CompoundStmt, e.g.:
16336   //    for (int i = 0; i < n; i++);
16337   //    {
16338   //      a(i);
16339   //    }
16340   // or if for/while is followed by a statement with more indentation
16341   // than for/while itself:
16342   //    for (int i = 0; i < n; i++);
16343   //      a(i);
16344   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16345   if (!ProbableTypo) {
16346     bool BodyColInvalid;
16347     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16348         PossibleBody->getBeginLoc(), &BodyColInvalid);
16349     if (BodyColInvalid)
16350       return;
16351 
16352     bool StmtColInvalid;
16353     unsigned StmtCol =
16354         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16355     if (StmtColInvalid)
16356       return;
16357 
16358     if (BodyCol > StmtCol)
16359       ProbableTypo = true;
16360   }
16361 
16362   if (ProbableTypo) {
16363     Diag(NBody->getSemiLoc(), DiagID);
16364     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16365   }
16366 }
16367 
16368 //===--- CHECK: Warn on self move with std::move. -------------------------===//
16369 
16370 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
16371 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16372                              SourceLocation OpLoc) {
16373   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16374     return;
16375 
16376   if (inTemplateInstantiation())
16377     return;
16378 
16379   // Strip parens and casts away.
16380   LHSExpr = LHSExpr->IgnoreParenImpCasts();
16381   RHSExpr = RHSExpr->IgnoreParenImpCasts();
16382 
16383   // Check for a call expression
16384   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
16385   if (!CE || CE->getNumArgs() != 1)
16386     return;
16387 
16388   // Check for a call to std::move
16389   if (!CE->isCallToStdMove())
16390     return;
16391 
16392   // Get argument from std::move
16393   RHSExpr = CE->getArg(0);
16394 
16395   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16396   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16397 
16398   // Two DeclRefExpr's, check that the decls are the same.
16399   if (LHSDeclRef && RHSDeclRef) {
16400     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16401       return;
16402     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16403         RHSDeclRef->getDecl()->getCanonicalDecl())
16404       return;
16405 
16406     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16407                                         << LHSExpr->getSourceRange()
16408                                         << RHSExpr->getSourceRange();
16409     return;
16410   }
16411 
16412   // Member variables require a different approach to check for self moves.
16413   // MemberExpr's are the same if every nested MemberExpr refers to the same
16414   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16415   // the base Expr's are CXXThisExpr's.
16416   const Expr *LHSBase = LHSExpr;
16417   const Expr *RHSBase = RHSExpr;
16418   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16419   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16420   if (!LHSME || !RHSME)
16421     return;
16422 
16423   while (LHSME && RHSME) {
16424     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16425         RHSME->getMemberDecl()->getCanonicalDecl())
16426       return;
16427 
16428     LHSBase = LHSME->getBase();
16429     RHSBase = RHSME->getBase();
16430     LHSME = dyn_cast<MemberExpr>(LHSBase);
16431     RHSME = dyn_cast<MemberExpr>(RHSBase);
16432   }
16433 
16434   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16435   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16436   if (LHSDeclRef && RHSDeclRef) {
16437     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16438       return;
16439     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16440         RHSDeclRef->getDecl()->getCanonicalDecl())
16441       return;
16442 
16443     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16444                                         << LHSExpr->getSourceRange()
16445                                         << RHSExpr->getSourceRange();
16446     return;
16447   }
16448 
16449   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16450     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16451                                         << LHSExpr->getSourceRange()
16452                                         << RHSExpr->getSourceRange();
16453 }
16454 
16455 //===--- Layout compatibility ----------------------------------------------//
16456 
16457 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
16458 
16459 /// Check if two enumeration types are layout-compatible.
16460 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
16461   // C++11 [dcl.enum] p8:
16462   // Two enumeration types are layout-compatible if they have the same
16463   // underlying type.
16464   return ED1->isComplete() && ED2->isComplete() &&
16465          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16466 }
16467 
16468 /// Check if two fields are layout-compatible.
16469 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
16470                                FieldDecl *Field2) {
16471   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16472     return false;
16473 
16474   if (Field1->isBitField() != Field2->isBitField())
16475     return false;
16476 
16477   if (Field1->isBitField()) {
16478     // Make sure that the bit-fields are the same length.
16479     unsigned Bits1 = Field1->getBitWidthValue(C);
16480     unsigned Bits2 = Field2->getBitWidthValue(C);
16481 
16482     if (Bits1 != Bits2)
16483       return false;
16484   }
16485 
16486   return true;
16487 }
16488 
16489 /// Check if two standard-layout structs are layout-compatible.
16490 /// (C++11 [class.mem] p17)
16491 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
16492                                      RecordDecl *RD2) {
16493   // If both records are C++ classes, check that base classes match.
16494   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
16495     // If one of records is a CXXRecordDecl we are in C++ mode,
16496     // thus the other one is a CXXRecordDecl, too.
16497     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
16498     // Check number of base classes.
16499     if (D1CXX->getNumBases() != D2CXX->getNumBases())
16500       return false;
16501 
16502     // Check the base classes.
16503     for (CXXRecordDecl::base_class_const_iterator
16504                Base1 = D1CXX->bases_begin(),
16505            BaseEnd1 = D1CXX->bases_end(),
16506               Base2 = D2CXX->bases_begin();
16507          Base1 != BaseEnd1;
16508          ++Base1, ++Base2) {
16509       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16510         return false;
16511     }
16512   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16513     // If only RD2 is a C++ class, it should have zero base classes.
16514     if (D2CXX->getNumBases() > 0)
16515       return false;
16516   }
16517 
16518   // Check the fields.
16519   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16520                              Field2End = RD2->field_end(),
16521                              Field1 = RD1->field_begin(),
16522                              Field1End = RD1->field_end();
16523   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16524     if (!isLayoutCompatible(C, *Field1, *Field2))
16525       return false;
16526   }
16527   if (Field1 != Field1End || Field2 != Field2End)
16528     return false;
16529 
16530   return true;
16531 }
16532 
16533 /// Check if two standard-layout unions are layout-compatible.
16534 /// (C++11 [class.mem] p18)
16535 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16536                                     RecordDecl *RD2) {
16537   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16538   for (auto *Field2 : RD2->fields())
16539     UnmatchedFields.insert(Field2);
16540 
16541   for (auto *Field1 : RD1->fields()) {
16542     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16543         I = UnmatchedFields.begin(),
16544         E = UnmatchedFields.end();
16545 
16546     for ( ; I != E; ++I) {
16547       if (isLayoutCompatible(C, Field1, *I)) {
16548         bool Result = UnmatchedFields.erase(*I);
16549         (void) Result;
16550         assert(Result);
16551         break;
16552       }
16553     }
16554     if (I == E)
16555       return false;
16556   }
16557 
16558   return UnmatchedFields.empty();
16559 }
16560 
16561 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16562                                RecordDecl *RD2) {
16563   if (RD1->isUnion() != RD2->isUnion())
16564     return false;
16565 
16566   if (RD1->isUnion())
16567     return isLayoutCompatibleUnion(C, RD1, RD2);
16568   else
16569     return isLayoutCompatibleStruct(C, RD1, RD2);
16570 }
16571 
16572 /// Check if two types are layout-compatible in C++11 sense.
16573 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16574   if (T1.isNull() || T2.isNull())
16575     return false;
16576 
16577   // C++11 [basic.types] p11:
16578   // If two types T1 and T2 are the same type, then T1 and T2 are
16579   // layout-compatible types.
16580   if (C.hasSameType(T1, T2))
16581     return true;
16582 
16583   T1 = T1.getCanonicalType().getUnqualifiedType();
16584   T2 = T2.getCanonicalType().getUnqualifiedType();
16585 
16586   const Type::TypeClass TC1 = T1->getTypeClass();
16587   const Type::TypeClass TC2 = T2->getTypeClass();
16588 
16589   if (TC1 != TC2)
16590     return false;
16591 
16592   if (TC1 == Type::Enum) {
16593     return isLayoutCompatible(C,
16594                               cast<EnumType>(T1)->getDecl(),
16595                               cast<EnumType>(T2)->getDecl());
16596   } else if (TC1 == Type::Record) {
16597     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16598       return false;
16599 
16600     return isLayoutCompatible(C,
16601                               cast<RecordType>(T1)->getDecl(),
16602                               cast<RecordType>(T2)->getDecl());
16603   }
16604 
16605   return false;
16606 }
16607 
16608 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16609 
16610 /// Given a type tag expression find the type tag itself.
16611 ///
16612 /// \param TypeExpr Type tag expression, as it appears in user's code.
16613 ///
16614 /// \param VD Declaration of an identifier that appears in a type tag.
16615 ///
16616 /// \param MagicValue Type tag magic value.
16617 ///
16618 /// \param isConstantEvaluated whether the evalaution should be performed in
16619 
16620 /// constant context.
16621 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16622                             const ValueDecl **VD, uint64_t *MagicValue,
16623                             bool isConstantEvaluated) {
16624   while(true) {
16625     if (!TypeExpr)
16626       return false;
16627 
16628     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16629 
16630     switch (TypeExpr->getStmtClass()) {
16631     case Stmt::UnaryOperatorClass: {
16632       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16633       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16634         TypeExpr = UO->getSubExpr();
16635         continue;
16636       }
16637       return false;
16638     }
16639 
16640     case Stmt::DeclRefExprClass: {
16641       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16642       *VD = DRE->getDecl();
16643       return true;
16644     }
16645 
16646     case Stmt::IntegerLiteralClass: {
16647       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16648       llvm::APInt MagicValueAPInt = IL->getValue();
16649       if (MagicValueAPInt.getActiveBits() <= 64) {
16650         *MagicValue = MagicValueAPInt.getZExtValue();
16651         return true;
16652       } else
16653         return false;
16654     }
16655 
16656     case Stmt::BinaryConditionalOperatorClass:
16657     case Stmt::ConditionalOperatorClass: {
16658       const AbstractConditionalOperator *ACO =
16659           cast<AbstractConditionalOperator>(TypeExpr);
16660       bool Result;
16661       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16662                                                      isConstantEvaluated)) {
16663         if (Result)
16664           TypeExpr = ACO->getTrueExpr();
16665         else
16666           TypeExpr = ACO->getFalseExpr();
16667         continue;
16668       }
16669       return false;
16670     }
16671 
16672     case Stmt::BinaryOperatorClass: {
16673       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16674       if (BO->getOpcode() == BO_Comma) {
16675         TypeExpr = BO->getRHS();
16676         continue;
16677       }
16678       return false;
16679     }
16680 
16681     default:
16682       return false;
16683     }
16684   }
16685 }
16686 
16687 /// Retrieve the C type corresponding to type tag TypeExpr.
16688 ///
16689 /// \param TypeExpr Expression that specifies a type tag.
16690 ///
16691 /// \param MagicValues Registered magic values.
16692 ///
16693 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16694 ///        kind.
16695 ///
16696 /// \param TypeInfo Information about the corresponding C type.
16697 ///
16698 /// \param isConstantEvaluated whether the evalaution should be performed in
16699 /// constant context.
16700 ///
16701 /// \returns true if the corresponding C type was found.
16702 static bool GetMatchingCType(
16703     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16704     const ASTContext &Ctx,
16705     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16706         *MagicValues,
16707     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16708     bool isConstantEvaluated) {
16709   FoundWrongKind = false;
16710 
16711   // Variable declaration that has type_tag_for_datatype attribute.
16712   const ValueDecl *VD = nullptr;
16713 
16714   uint64_t MagicValue;
16715 
16716   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16717     return false;
16718 
16719   if (VD) {
16720     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16721       if (I->getArgumentKind() != ArgumentKind) {
16722         FoundWrongKind = true;
16723         return false;
16724       }
16725       TypeInfo.Type = I->getMatchingCType();
16726       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16727       TypeInfo.MustBeNull = I->getMustBeNull();
16728       return true;
16729     }
16730     return false;
16731   }
16732 
16733   if (!MagicValues)
16734     return false;
16735 
16736   llvm::DenseMap<Sema::TypeTagMagicValue,
16737                  Sema::TypeTagData>::const_iterator I =
16738       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16739   if (I == MagicValues->end())
16740     return false;
16741 
16742   TypeInfo = I->second;
16743   return true;
16744 }
16745 
16746 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16747                                       uint64_t MagicValue, QualType Type,
16748                                       bool LayoutCompatible,
16749                                       bool MustBeNull) {
16750   if (!TypeTagForDatatypeMagicValues)
16751     TypeTagForDatatypeMagicValues.reset(
16752         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16753 
16754   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16755   (*TypeTagForDatatypeMagicValues)[Magic] =
16756       TypeTagData(Type, LayoutCompatible, MustBeNull);
16757 }
16758 
16759 static bool IsSameCharType(QualType T1, QualType T2) {
16760   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16761   if (!BT1)
16762     return false;
16763 
16764   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16765   if (!BT2)
16766     return false;
16767 
16768   BuiltinType::Kind T1Kind = BT1->getKind();
16769   BuiltinType::Kind T2Kind = BT2->getKind();
16770 
16771   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16772          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16773          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16774          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16775 }
16776 
16777 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16778                                     const ArrayRef<const Expr *> ExprArgs,
16779                                     SourceLocation CallSiteLoc) {
16780   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16781   bool IsPointerAttr = Attr->getIsPointer();
16782 
16783   // Retrieve the argument representing the 'type_tag'.
16784   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16785   if (TypeTagIdxAST >= ExprArgs.size()) {
16786     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16787         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16788     return;
16789   }
16790   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16791   bool FoundWrongKind;
16792   TypeTagData TypeInfo;
16793   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16794                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16795                         TypeInfo, isConstantEvaluated())) {
16796     if (FoundWrongKind)
16797       Diag(TypeTagExpr->getExprLoc(),
16798            diag::warn_type_tag_for_datatype_wrong_kind)
16799         << TypeTagExpr->getSourceRange();
16800     return;
16801   }
16802 
16803   // Retrieve the argument representing the 'arg_idx'.
16804   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16805   if (ArgumentIdxAST >= ExprArgs.size()) {
16806     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16807         << 1 << Attr->getArgumentIdx().getSourceIndex();
16808     return;
16809   }
16810   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16811   if (IsPointerAttr) {
16812     // Skip implicit cast of pointer to `void *' (as a function argument).
16813     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16814       if (ICE->getType()->isVoidPointerType() &&
16815           ICE->getCastKind() == CK_BitCast)
16816         ArgumentExpr = ICE->getSubExpr();
16817   }
16818   QualType ArgumentType = ArgumentExpr->getType();
16819 
16820   // Passing a `void*' pointer shouldn't trigger a warning.
16821   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16822     return;
16823 
16824   if (TypeInfo.MustBeNull) {
16825     // Type tag with matching void type requires a null pointer.
16826     if (!ArgumentExpr->isNullPointerConstant(Context,
16827                                              Expr::NPC_ValueDependentIsNotNull)) {
16828       Diag(ArgumentExpr->getExprLoc(),
16829            diag::warn_type_safety_null_pointer_required)
16830           << ArgumentKind->getName()
16831           << ArgumentExpr->getSourceRange()
16832           << TypeTagExpr->getSourceRange();
16833     }
16834     return;
16835   }
16836 
16837   QualType RequiredType = TypeInfo.Type;
16838   if (IsPointerAttr)
16839     RequiredType = Context.getPointerType(RequiredType);
16840 
16841   bool mismatch = false;
16842   if (!TypeInfo.LayoutCompatible) {
16843     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16844 
16845     // C++11 [basic.fundamental] p1:
16846     // Plain char, signed char, and unsigned char are three distinct types.
16847     //
16848     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16849     // char' depending on the current char signedness mode.
16850     if (mismatch)
16851       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16852                                            RequiredType->getPointeeType())) ||
16853           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16854         mismatch = false;
16855   } else
16856     if (IsPointerAttr)
16857       mismatch = !isLayoutCompatible(Context,
16858                                      ArgumentType->getPointeeType(),
16859                                      RequiredType->getPointeeType());
16860     else
16861       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16862 
16863   if (mismatch)
16864     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16865         << ArgumentType << ArgumentKind
16866         << TypeInfo.LayoutCompatible << RequiredType
16867         << ArgumentExpr->getSourceRange()
16868         << TypeTagExpr->getSourceRange();
16869 }
16870 
16871 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16872                                          CharUnits Alignment) {
16873   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16874 }
16875 
16876 void Sema::DiagnoseMisalignedMembers() {
16877   for (MisalignedMember &m : MisalignedMembers) {
16878     const NamedDecl *ND = m.RD;
16879     if (ND->getName().empty()) {
16880       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16881         ND = TD;
16882     }
16883     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16884         << m.MD << ND << m.E->getSourceRange();
16885   }
16886   MisalignedMembers.clear();
16887 }
16888 
16889 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16890   E = E->IgnoreParens();
16891   if (!T->isPointerType() && !T->isIntegerType())
16892     return;
16893   if (isa<UnaryOperator>(E) &&
16894       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16895     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16896     if (isa<MemberExpr>(Op)) {
16897       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16898       if (MA != MisalignedMembers.end() &&
16899           (T->isIntegerType() ||
16900            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16901                                    Context.getTypeAlignInChars(
16902                                        T->getPointeeType()) <= MA->Alignment))))
16903         MisalignedMembers.erase(MA);
16904     }
16905   }
16906 }
16907 
16908 void Sema::RefersToMemberWithReducedAlignment(
16909     Expr *E,
16910     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16911         Action) {
16912   const auto *ME = dyn_cast<MemberExpr>(E);
16913   if (!ME)
16914     return;
16915 
16916   // No need to check expressions with an __unaligned-qualified type.
16917   if (E->getType().getQualifiers().hasUnaligned())
16918     return;
16919 
16920   // For a chain of MemberExpr like "a.b.c.d" this list
16921   // will keep FieldDecl's like [d, c, b].
16922   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16923   const MemberExpr *TopME = nullptr;
16924   bool AnyIsPacked = false;
16925   do {
16926     QualType BaseType = ME->getBase()->getType();
16927     if (BaseType->isDependentType())
16928       return;
16929     if (ME->isArrow())
16930       BaseType = BaseType->getPointeeType();
16931     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16932     if (RD->isInvalidDecl())
16933       return;
16934 
16935     ValueDecl *MD = ME->getMemberDecl();
16936     auto *FD = dyn_cast<FieldDecl>(MD);
16937     // We do not care about non-data members.
16938     if (!FD || FD->isInvalidDecl())
16939       return;
16940 
16941     AnyIsPacked =
16942         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16943     ReverseMemberChain.push_back(FD);
16944 
16945     TopME = ME;
16946     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16947   } while (ME);
16948   assert(TopME && "We did not compute a topmost MemberExpr!");
16949 
16950   // Not the scope of this diagnostic.
16951   if (!AnyIsPacked)
16952     return;
16953 
16954   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16955   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16956   // TODO: The innermost base of the member expression may be too complicated.
16957   // For now, just disregard these cases. This is left for future
16958   // improvement.
16959   if (!DRE && !isa<CXXThisExpr>(TopBase))
16960       return;
16961 
16962   // Alignment expected by the whole expression.
16963   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16964 
16965   // No need to do anything else with this case.
16966   if (ExpectedAlignment.isOne())
16967     return;
16968 
16969   // Synthesize offset of the whole access.
16970   CharUnits Offset;
16971   for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16972     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16973 
16974   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16975   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16976       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16977 
16978   // The base expression of the innermost MemberExpr may give
16979   // stronger guarantees than the class containing the member.
16980   if (DRE && !TopME->isArrow()) {
16981     const ValueDecl *VD = DRE->getDecl();
16982     if (!VD->getType()->isReferenceType())
16983       CompleteObjectAlignment =
16984           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16985   }
16986 
16987   // Check if the synthesized offset fulfills the alignment.
16988   if (Offset % ExpectedAlignment != 0 ||
16989       // It may fulfill the offset it but the effective alignment may still be
16990       // lower than the expected expression alignment.
16991       CompleteObjectAlignment < ExpectedAlignment) {
16992     // If this happens, we want to determine a sensible culprit of this.
16993     // Intuitively, watching the chain of member expressions from right to
16994     // left, we start with the required alignment (as required by the field
16995     // type) but some packed attribute in that chain has reduced the alignment.
16996     // It may happen that another packed structure increases it again. But if
16997     // we are here such increase has not been enough. So pointing the first
16998     // FieldDecl that either is packed or else its RecordDecl is,
16999     // seems reasonable.
17000     FieldDecl *FD = nullptr;
17001     CharUnits Alignment;
17002     for (FieldDecl *FDI : ReverseMemberChain) {
17003       if (FDI->hasAttr<PackedAttr>() ||
17004           FDI->getParent()->hasAttr<PackedAttr>()) {
17005         FD = FDI;
17006         Alignment = std::min(
17007             Context.getTypeAlignInChars(FD->getType()),
17008             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
17009         break;
17010       }
17011     }
17012     assert(FD && "We did not find a packed FieldDecl!");
17013     Action(E, FD->getParent(), FD, Alignment);
17014   }
17015 }
17016 
17017 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
17018   using namespace std::placeholders;
17019 
17020   RefersToMemberWithReducedAlignment(
17021       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
17022                      _2, _3, _4));
17023 }
17024 
17025 // Check if \p Ty is a valid type for the elementwise math builtins. If it is
17026 // not a valid type, emit an error message and return true. Otherwise return
17027 // false.
17028 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc,
17029                                         QualType Ty) {
17030   if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) {
17031     S.Diag(Loc, diag::err_builtin_invalid_arg_type)
17032         << 1 << /* vector, integer or float ty*/ 0 << Ty;
17033     return true;
17034   }
17035   return false;
17036 }
17037 
17038 bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) {
17039   if (checkArgCount(*this, TheCall, 1))
17040     return true;
17041 
17042   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17043   if (A.isInvalid())
17044     return true;
17045 
17046   TheCall->setArg(0, A.get());
17047   QualType TyA = A.get()->getType();
17048 
17049   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
17050     return true;
17051 
17052   TheCall->setType(TyA);
17053   return false;
17054 }
17055 
17056 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) {
17057   if (checkArgCount(*this, TheCall, 2))
17058     return true;
17059 
17060   ExprResult A = TheCall->getArg(0);
17061   ExprResult B = TheCall->getArg(1);
17062   // Do standard promotions between the two arguments, returning their common
17063   // type.
17064   QualType Res =
17065       UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
17066   if (A.isInvalid() || B.isInvalid())
17067     return true;
17068 
17069   QualType TyA = A.get()->getType();
17070   QualType TyB = B.get()->getType();
17071 
17072   if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
17073     return Diag(A.get()->getBeginLoc(),
17074                 diag::err_typecheck_call_different_arg_types)
17075            << TyA << TyB;
17076 
17077   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
17078     return true;
17079 
17080   TheCall->setArg(0, A.get());
17081   TheCall->setArg(1, B.get());
17082   TheCall->setType(Res);
17083   return false;
17084 }
17085 
17086 bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
17087   if (checkArgCount(*this, TheCall, 1))
17088     return true;
17089 
17090   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17091   if (A.isInvalid())
17092     return true;
17093 
17094   TheCall->setArg(0, A.get());
17095   return false;
17096 }
17097 
17098 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
17099                                             ExprResult CallResult) {
17100   if (checkArgCount(*this, TheCall, 1))
17101     return ExprError();
17102 
17103   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
17104   if (MatrixArg.isInvalid())
17105     return MatrixArg;
17106   Expr *Matrix = MatrixArg.get();
17107 
17108   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17109   if (!MType) {
17110     Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17111         << 1 << /* matrix ty*/ 1 << Matrix->getType();
17112     return ExprError();
17113   }
17114 
17115   // Create returned matrix type by swapping rows and columns of the argument
17116   // matrix type.
17117   QualType ResultType = Context.getConstantMatrixType(
17118       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
17119 
17120   // Change the return type to the type of the returned matrix.
17121   TheCall->setType(ResultType);
17122 
17123   // Update call argument to use the possibly converted matrix argument.
17124   TheCall->setArg(0, Matrix);
17125   return CallResult;
17126 }
17127 
17128 // Get and verify the matrix dimensions.
17129 static llvm::Optional<unsigned>
17130 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
17131   SourceLocation ErrorPos;
17132   Optional<llvm::APSInt> Value =
17133       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
17134   if (!Value) {
17135     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
17136         << Name;
17137     return {};
17138   }
17139   uint64_t Dim = Value->getZExtValue();
17140   if (!ConstantMatrixType::isDimensionValid(Dim)) {
17141     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
17142         << Name << ConstantMatrixType::getMaxElementsPerDimension();
17143     return {};
17144   }
17145   return Dim;
17146 }
17147 
17148 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17149                                                   ExprResult CallResult) {
17150   if (!getLangOpts().MatrixTypes) {
17151     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17152     return ExprError();
17153   }
17154 
17155   if (checkArgCount(*this, TheCall, 4))
17156     return ExprError();
17157 
17158   unsigned PtrArgIdx = 0;
17159   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17160   Expr *RowsExpr = TheCall->getArg(1);
17161   Expr *ColumnsExpr = TheCall->getArg(2);
17162   Expr *StrideExpr = TheCall->getArg(3);
17163 
17164   bool ArgError = false;
17165 
17166   // Check pointer argument.
17167   {
17168     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17169     if (PtrConv.isInvalid())
17170       return PtrConv;
17171     PtrExpr = PtrConv.get();
17172     TheCall->setArg(0, PtrExpr);
17173     if (PtrExpr->isTypeDependent()) {
17174       TheCall->setType(Context.DependentTy);
17175       return TheCall;
17176     }
17177   }
17178 
17179   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17180   QualType ElementTy;
17181   if (!PtrTy) {
17182     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17183         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17184     ArgError = true;
17185   } else {
17186     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17187 
17188     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
17189       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17190           << PtrArgIdx + 1 << /* pointer to element ty*/ 2
17191           << PtrExpr->getType();
17192       ArgError = true;
17193     }
17194   }
17195 
17196   // Apply default Lvalue conversions and convert the expression to size_t.
17197   auto ApplyArgumentConversions = [this](Expr *E) {
17198     ExprResult Conv = DefaultLvalueConversion(E);
17199     if (Conv.isInvalid())
17200       return Conv;
17201 
17202     return tryConvertExprToType(Conv.get(), Context.getSizeType());
17203   };
17204 
17205   // Apply conversion to row and column expressions.
17206   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17207   if (!RowsConv.isInvalid()) {
17208     RowsExpr = RowsConv.get();
17209     TheCall->setArg(1, RowsExpr);
17210   } else
17211     RowsExpr = nullptr;
17212 
17213   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17214   if (!ColumnsConv.isInvalid()) {
17215     ColumnsExpr = ColumnsConv.get();
17216     TheCall->setArg(2, ColumnsExpr);
17217   } else
17218     ColumnsExpr = nullptr;
17219 
17220   // If any any part of the result matrix type is still pending, just use
17221   // Context.DependentTy, until all parts are resolved.
17222   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17223       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17224     TheCall->setType(Context.DependentTy);
17225     return CallResult;
17226   }
17227 
17228   // Check row and column dimensions.
17229   llvm::Optional<unsigned> MaybeRows;
17230   if (RowsExpr)
17231     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17232 
17233   llvm::Optional<unsigned> MaybeColumns;
17234   if (ColumnsExpr)
17235     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17236 
17237   // Check stride argument.
17238   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17239   if (StrideConv.isInvalid())
17240     return ExprError();
17241   StrideExpr = StrideConv.get();
17242   TheCall->setArg(3, StrideExpr);
17243 
17244   if (MaybeRows) {
17245     if (Optional<llvm::APSInt> Value =
17246             StrideExpr->getIntegerConstantExpr(Context)) {
17247       uint64_t Stride = Value->getZExtValue();
17248       if (Stride < *MaybeRows) {
17249         Diag(StrideExpr->getBeginLoc(),
17250              diag::err_builtin_matrix_stride_too_small);
17251         ArgError = true;
17252       }
17253     }
17254   }
17255 
17256   if (ArgError || !MaybeRows || !MaybeColumns)
17257     return ExprError();
17258 
17259   TheCall->setType(
17260       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17261   return CallResult;
17262 }
17263 
17264 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17265                                                    ExprResult CallResult) {
17266   if (checkArgCount(*this, TheCall, 3))
17267     return ExprError();
17268 
17269   unsigned PtrArgIdx = 1;
17270   Expr *MatrixExpr = TheCall->getArg(0);
17271   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17272   Expr *StrideExpr = TheCall->getArg(2);
17273 
17274   bool ArgError = false;
17275 
17276   {
17277     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17278     if (MatrixConv.isInvalid())
17279       return MatrixConv;
17280     MatrixExpr = MatrixConv.get();
17281     TheCall->setArg(0, MatrixExpr);
17282   }
17283   if (MatrixExpr->isTypeDependent()) {
17284     TheCall->setType(Context.DependentTy);
17285     return TheCall;
17286   }
17287 
17288   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17289   if (!MatrixTy) {
17290     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17291         << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
17292     ArgError = true;
17293   }
17294 
17295   {
17296     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17297     if (PtrConv.isInvalid())
17298       return PtrConv;
17299     PtrExpr = PtrConv.get();
17300     TheCall->setArg(1, PtrExpr);
17301     if (PtrExpr->isTypeDependent()) {
17302       TheCall->setType(Context.DependentTy);
17303       return TheCall;
17304     }
17305   }
17306 
17307   // Check pointer argument.
17308   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17309   if (!PtrTy) {
17310     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17311         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17312     ArgError = true;
17313   } else {
17314     QualType ElementTy = PtrTy->getPointeeType();
17315     if (ElementTy.isConstQualified()) {
17316       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17317       ArgError = true;
17318     }
17319     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17320     if (MatrixTy &&
17321         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17322       Diag(PtrExpr->getBeginLoc(),
17323            diag::err_builtin_matrix_pointer_arg_mismatch)
17324           << ElementTy << MatrixTy->getElementType();
17325       ArgError = true;
17326     }
17327   }
17328 
17329   // Apply default Lvalue conversions and convert the stride expression to
17330   // size_t.
17331   {
17332     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17333     if (StrideConv.isInvalid())
17334       return StrideConv;
17335 
17336     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17337     if (StrideConv.isInvalid())
17338       return StrideConv;
17339     StrideExpr = StrideConv.get();
17340     TheCall->setArg(2, StrideExpr);
17341   }
17342 
17343   // Check stride argument.
17344   if (MatrixTy) {
17345     if (Optional<llvm::APSInt> Value =
17346             StrideExpr->getIntegerConstantExpr(Context)) {
17347       uint64_t Stride = Value->getZExtValue();
17348       if (Stride < MatrixTy->getNumRows()) {
17349         Diag(StrideExpr->getBeginLoc(),
17350              diag::err_builtin_matrix_stride_too_small);
17351         ArgError = true;
17352       }
17353     }
17354   }
17355 
17356   if (ArgError)
17357     return ExprError();
17358 
17359   return CallResult;
17360 }
17361 
17362 /// \brief Enforce the bounds of a TCB
17363 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
17364 /// directly calls other functions in the same TCB as marked by the enforce_tcb
17365 /// and enforce_tcb_leaf attributes.
17366 void Sema::CheckTCBEnforcement(const SourceLocation CallExprLoc,
17367                                const NamedDecl *Callee) {
17368   const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17369 
17370   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17371     return;
17372 
17373   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17374   // all TCBs the callee is a part of.
17375   llvm::StringSet<> CalleeTCBs;
17376   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
17377            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17378   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
17379            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17380 
17381   // Go through the TCBs the caller is a part of and emit warnings if Caller
17382   // is in a TCB that the Callee is not.
17383   for_each(
17384       Caller->specific_attrs<EnforceTCBAttr>(),
17385       [&](const auto *A) {
17386         StringRef CallerTCB = A->getTCBName();
17387         if (CalleeTCBs.count(CallerTCB) == 0) {
17388           this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
17389               << Callee << CallerTCB;
17390         }
17391       });
17392 }
17393