1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements extra semantic analysis beyond what is enforced
10 //  by the C type system.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/AttrIterator.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/FormatString.h"
30 #include "clang/AST/NSAPI.h"
31 #include "clang/AST/NonTrivialTypeVisitor.h"
32 #include "clang/AST/OperationKinds.h"
33 #include "clang/AST/RecordLayout.h"
34 #include "clang/AST/Stmt.h"
35 #include "clang/AST/TemplateBase.h"
36 #include "clang/AST/Type.h"
37 #include "clang/AST/TypeLoc.h"
38 #include "clang/AST/UnresolvedSet.h"
39 #include "clang/Basic/AddressSpaces.h"
40 #include "clang/Basic/CharInfo.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/IdentifierTable.h"
43 #include "clang/Basic/LLVM.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/OpenCLOptions.h"
46 #include "clang/Basic/OperatorKinds.h"
47 #include "clang/Basic/PartialDiagnostic.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/Specifiers.h"
51 #include "clang/Basic/SyncScope.h"
52 #include "clang/Basic/TargetBuiltins.h"
53 #include "clang/Basic/TargetCXXABI.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "clang/Basic/TypeTraits.h"
56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57 #include "clang/Sema/Initialization.h"
58 #include "clang/Sema/Lookup.h"
59 #include "clang/Sema/Ownership.h"
60 #include "clang/Sema/Scope.h"
61 #include "clang/Sema/ScopeInfo.h"
62 #include "clang/Sema/Sema.h"
63 #include "clang/Sema/SemaInternal.h"
64 #include "llvm/ADT/APFloat.h"
65 #include "llvm/ADT/APInt.h"
66 #include "llvm/ADT/APSInt.h"
67 #include "llvm/ADT/ArrayRef.h"
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/FoldingSet.h"
70 #include "llvm/ADT/None.h"
71 #include "llvm/ADT/Optional.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallBitVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallString.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/ADT/StringSet.h"
79 #include "llvm/ADT/StringSwitch.h"
80 #include "llvm/ADT/Triple.h"
81 #include "llvm/Support/AtomicOrdering.h"
82 #include "llvm/Support/Casting.h"
83 #include "llvm/Support/Compiler.h"
84 #include "llvm/Support/ConvertUTF.h"
85 #include "llvm/Support/ErrorHandling.h"
86 #include "llvm/Support/Format.h"
87 #include "llvm/Support/Locale.h"
88 #include "llvm/Support/MathExtras.h"
89 #include "llvm/Support/SaveAndRestore.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include <algorithm>
92 #include <bitset>
93 #include <cassert>
94 #include <cctype>
95 #include <cstddef>
96 #include <cstdint>
97 #include <functional>
98 #include <limits>
99 #include <string>
100 #include <tuple>
101 #include <utility>
102 
103 using namespace clang;
104 using namespace sema;
105 
106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
107                                                     unsigned ByteNo) const {
108   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
109                                Context.getTargetInfo());
110 }
111 
112 /// Checks that a call expression's argument count is the desired number.
113 /// This is useful when doing custom type-checking.  Returns true on error.
114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
115   unsigned argCount = call->getNumArgs();
116   if (argCount == desiredArgCount) return false;
117 
118   if (argCount < desiredArgCount)
119     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
120            << 0 /*function call*/ << desiredArgCount << argCount
121            << call->getSourceRange();
122 
123   // Highlight all the excess arguments.
124   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
125                     call->getArg(argCount - 1)->getEndLoc());
126 
127   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
128     << 0 /*function call*/ << desiredArgCount << argCount
129     << call->getArg(1)->getSourceRange();
130 }
131 
132 /// Check that the first argument to __builtin_annotation is an integer
133 /// and the second argument is a non-wide string literal.
134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
135   if (checkArgCount(S, TheCall, 2))
136     return true;
137 
138   // First argument should be an integer.
139   Expr *ValArg = TheCall->getArg(0);
140   QualType Ty = ValArg->getType();
141   if (!Ty->isIntegerType()) {
142     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
143         << ValArg->getSourceRange();
144     return true;
145   }
146 
147   // Second argument should be a constant string.
148   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
149   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
150   if (!Literal || !Literal->isAscii()) {
151     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
152         << StrArg->getSourceRange();
153     return true;
154   }
155 
156   TheCall->setType(Ty);
157   return false;
158 }
159 
160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
161   // We need at least one argument.
162   if (TheCall->getNumArgs() < 1) {
163     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
164         << 0 << 1 << TheCall->getNumArgs()
165         << TheCall->getCallee()->getSourceRange();
166     return true;
167   }
168 
169   // All arguments should be wide string literals.
170   for (Expr *Arg : TheCall->arguments()) {
171     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
172     if (!Literal || !Literal->isWide()) {
173       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
174           << Arg->getSourceRange();
175       return true;
176     }
177   }
178 
179   return false;
180 }
181 
182 /// Check that the argument to __builtin_addressof is a glvalue, and set the
183 /// result type to the corresponding pointer type.
184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
185   if (checkArgCount(S, TheCall, 1))
186     return true;
187 
188   ExprResult Arg(TheCall->getArg(0));
189   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
190   if (ResultType.isNull())
191     return true;
192 
193   TheCall->setArg(0, Arg.get());
194   TheCall->setType(ResultType);
195   return false;
196 }
197 
198 /// Check that the argument to __builtin_function_start is a function.
199 static bool SemaBuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
200   if (checkArgCount(S, TheCall, 1))
201     return true;
202 
203   ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
204   if (Arg.isInvalid())
205     return true;
206 
207   TheCall->setArg(0, Arg.get());
208   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
209       Arg.get()->getAsBuiltinConstantDeclRef(S.getASTContext()));
210 
211   if (!FD) {
212     S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
213         << TheCall->getSourceRange();
214     return true;
215   }
216 
217   return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
218                                               TheCall->getBeginLoc());
219 }
220 
221 /// Check the number of arguments and set the result type to
222 /// the argument type.
223 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
224   if (checkArgCount(S, TheCall, 1))
225     return true;
226 
227   TheCall->setType(TheCall->getArg(0)->getType());
228   return false;
229 }
230 
231 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
232 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
233 /// type (but not a function pointer) and that the alignment is a power-of-two.
234 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
235   if (checkArgCount(S, TheCall, 2))
236     return true;
237 
238   clang::Expr *Source = TheCall->getArg(0);
239   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
240 
241   auto IsValidIntegerType = [](QualType Ty) {
242     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
243   };
244   QualType SrcTy = Source->getType();
245   // We should also be able to use it with arrays (but not functions!).
246   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
247     SrcTy = S.Context.getDecayedType(SrcTy);
248   }
249   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
250       SrcTy->isFunctionPointerType()) {
251     // FIXME: this is not quite the right error message since we don't allow
252     // floating point types, or member pointers.
253     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
254         << SrcTy;
255     return true;
256   }
257 
258   clang::Expr *AlignOp = TheCall->getArg(1);
259   if (!IsValidIntegerType(AlignOp->getType())) {
260     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
261         << AlignOp->getType();
262     return true;
263   }
264   Expr::EvalResult AlignResult;
265   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
266   // We can't check validity of alignment if it is value dependent.
267   if (!AlignOp->isValueDependent() &&
268       AlignOp->EvaluateAsInt(AlignResult, S.Context,
269                              Expr::SE_AllowSideEffects)) {
270     llvm::APSInt AlignValue = AlignResult.Val.getInt();
271     llvm::APSInt MaxValue(
272         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
273     if (AlignValue < 1) {
274       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
275       return true;
276     }
277     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
278       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
279           << toString(MaxValue, 10);
280       return true;
281     }
282     if (!AlignValue.isPowerOf2()) {
283       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
284       return true;
285     }
286     if (AlignValue == 1) {
287       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
288           << IsBooleanAlignBuiltin;
289     }
290   }
291 
292   ExprResult SrcArg = S.PerformCopyInitialization(
293       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
294       SourceLocation(), Source);
295   if (SrcArg.isInvalid())
296     return true;
297   TheCall->setArg(0, SrcArg.get());
298   ExprResult AlignArg =
299       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
300                                       S.Context, AlignOp->getType(), false),
301                                   SourceLocation(), AlignOp);
302   if (AlignArg.isInvalid())
303     return true;
304   TheCall->setArg(1, AlignArg.get());
305   // For align_up/align_down, the return type is the same as the (potentially
306   // decayed) argument type including qualifiers. For is_aligned(), the result
307   // is always bool.
308   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
309   return false;
310 }
311 
312 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
313                                 unsigned BuiltinID) {
314   if (checkArgCount(S, TheCall, 3))
315     return true;
316 
317   // First two arguments should be integers.
318   for (unsigned I = 0; I < 2; ++I) {
319     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
320     if (Arg.isInvalid()) return true;
321     TheCall->setArg(I, Arg.get());
322 
323     QualType Ty = Arg.get()->getType();
324     if (!Ty->isIntegerType()) {
325       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
326           << Ty << Arg.get()->getSourceRange();
327       return true;
328     }
329   }
330 
331   // Third argument should be a pointer to a non-const integer.
332   // IRGen correctly handles volatile, restrict, and address spaces, and
333   // the other qualifiers aren't possible.
334   {
335     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
336     if (Arg.isInvalid()) return true;
337     TheCall->setArg(2, Arg.get());
338 
339     QualType Ty = Arg.get()->getType();
340     const auto *PtrTy = Ty->getAs<PointerType>();
341     if (!PtrTy ||
342         !PtrTy->getPointeeType()->isIntegerType() ||
343         PtrTy->getPointeeType().isConstQualified()) {
344       S.Diag(Arg.get()->getBeginLoc(),
345              diag::err_overflow_builtin_must_be_ptr_int)
346         << Ty << Arg.get()->getSourceRange();
347       return true;
348     }
349   }
350 
351   // Disallow signed bit-precise integer args larger than 128 bits to mul
352   // function until we improve backend support.
353   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
354     for (unsigned I = 0; I < 3; ++I) {
355       const auto Arg = TheCall->getArg(I);
356       // Third argument will be a pointer.
357       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
358       if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
359           S.getASTContext().getIntWidth(Ty) > 128)
360         return S.Diag(Arg->getBeginLoc(),
361                       diag::err_overflow_builtin_bit_int_max_size)
362                << 128;
363     }
364   }
365 
366   return false;
367 }
368 
369 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
370   if (checkArgCount(S, BuiltinCall, 2))
371     return true;
372 
373   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
374   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
375   Expr *Call = BuiltinCall->getArg(0);
376   Expr *Chain = BuiltinCall->getArg(1);
377 
378   if (Call->getStmtClass() != Stmt::CallExprClass) {
379     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
380         << Call->getSourceRange();
381     return true;
382   }
383 
384   auto CE = cast<CallExpr>(Call);
385   if (CE->getCallee()->getType()->isBlockPointerType()) {
386     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
387         << Call->getSourceRange();
388     return true;
389   }
390 
391   const Decl *TargetDecl = CE->getCalleeDecl();
392   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
393     if (FD->getBuiltinID()) {
394       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
395           << Call->getSourceRange();
396       return true;
397     }
398 
399   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
400     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
401         << Call->getSourceRange();
402     return true;
403   }
404 
405   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
406   if (ChainResult.isInvalid())
407     return true;
408   if (!ChainResult.get()->getType()->isPointerType()) {
409     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
410         << Chain->getSourceRange();
411     return true;
412   }
413 
414   QualType ReturnTy = CE->getCallReturnType(S.Context);
415   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
416   QualType BuiltinTy = S.Context.getFunctionType(
417       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
418   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
419 
420   Builtin =
421       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
422 
423   BuiltinCall->setType(CE->getType());
424   BuiltinCall->setValueKind(CE->getValueKind());
425   BuiltinCall->setObjectKind(CE->getObjectKind());
426   BuiltinCall->setCallee(Builtin);
427   BuiltinCall->setArg(1, ChainResult.get());
428 
429   return false;
430 }
431 
432 namespace {
433 
434 class ScanfDiagnosticFormatHandler
435     : public analyze_format_string::FormatStringHandler {
436   // Accepts the argument index (relative to the first destination index) of the
437   // argument whose size we want.
438   using ComputeSizeFunction =
439       llvm::function_ref<Optional<llvm::APSInt>(unsigned)>;
440 
441   // Accepts the argument index (relative to the first destination index), the
442   // destination size, and the source size).
443   using DiagnoseFunction =
444       llvm::function_ref<void(unsigned, unsigned, unsigned)>;
445 
446   ComputeSizeFunction ComputeSizeArgument;
447   DiagnoseFunction Diagnose;
448 
449 public:
450   ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
451                                DiagnoseFunction Diagnose)
452       : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
453 
454   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
455                             const char *StartSpecifier,
456                             unsigned specifierLen) override {
457     if (!FS.consumesDataArgument())
458       return true;
459 
460     unsigned NulByte = 0;
461     switch ((FS.getConversionSpecifier().getKind())) {
462     default:
463       return true;
464     case analyze_format_string::ConversionSpecifier::sArg:
465     case analyze_format_string::ConversionSpecifier::ScanListArg:
466       NulByte = 1;
467       break;
468     case analyze_format_string::ConversionSpecifier::cArg:
469       break;
470     }
471 
472     analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
473     if (FW.getHowSpecified() !=
474         analyze_format_string::OptionalAmount::HowSpecified::Constant)
475       return true;
476 
477     unsigned SourceSize = FW.getConstantAmount() + NulByte;
478 
479     Optional<llvm::APSInt> DestSizeAPS = ComputeSizeArgument(FS.getArgIndex());
480     if (!DestSizeAPS)
481       return true;
482 
483     unsigned DestSize = DestSizeAPS->getZExtValue();
484 
485     if (DestSize < SourceSize)
486       Diagnose(FS.getArgIndex(), DestSize, SourceSize);
487 
488     return true;
489   }
490 };
491 
492 class EstimateSizeFormatHandler
493     : public analyze_format_string::FormatStringHandler {
494   size_t Size;
495 
496 public:
497   EstimateSizeFormatHandler(StringRef Format)
498       : Size(std::min(Format.find(0), Format.size()) +
499              1 /* null byte always written by sprintf */) {}
500 
501   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
502                              const char *, unsigned SpecifierLen,
503                              const TargetInfo &) override {
504 
505     const size_t FieldWidth = computeFieldWidth(FS);
506     const size_t Precision = computePrecision(FS);
507 
508     // The actual format.
509     switch (FS.getConversionSpecifier().getKind()) {
510     // Just a char.
511     case analyze_format_string::ConversionSpecifier::cArg:
512     case analyze_format_string::ConversionSpecifier::CArg:
513       Size += std::max(FieldWidth, (size_t)1);
514       break;
515     // Just an integer.
516     case analyze_format_string::ConversionSpecifier::dArg:
517     case analyze_format_string::ConversionSpecifier::DArg:
518     case analyze_format_string::ConversionSpecifier::iArg:
519     case analyze_format_string::ConversionSpecifier::oArg:
520     case analyze_format_string::ConversionSpecifier::OArg:
521     case analyze_format_string::ConversionSpecifier::uArg:
522     case analyze_format_string::ConversionSpecifier::UArg:
523     case analyze_format_string::ConversionSpecifier::xArg:
524     case analyze_format_string::ConversionSpecifier::XArg:
525       Size += std::max(FieldWidth, Precision);
526       break;
527 
528     // %g style conversion switches between %f or %e style dynamically.
529     // %f always takes less space, so default to it.
530     case analyze_format_string::ConversionSpecifier::gArg:
531     case analyze_format_string::ConversionSpecifier::GArg:
532 
533     // Floating point number in the form '[+]ddd.ddd'.
534     case analyze_format_string::ConversionSpecifier::fArg:
535     case analyze_format_string::ConversionSpecifier::FArg:
536       Size += std::max(FieldWidth, 1 /* integer part */ +
537                                        (Precision ? 1 + Precision
538                                                   : 0) /* period + decimal */);
539       break;
540 
541     // Floating point number in the form '[-]d.ddde[+-]dd'.
542     case analyze_format_string::ConversionSpecifier::eArg:
543     case analyze_format_string::ConversionSpecifier::EArg:
544       Size +=
545           std::max(FieldWidth,
546                    1 /* integer part */ +
547                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
548                        1 /* e or E letter */ + 2 /* exponent */);
549       break;
550 
551     // Floating point number in the form '[-]0xh.hhhhp±dd'.
552     case analyze_format_string::ConversionSpecifier::aArg:
553     case analyze_format_string::ConversionSpecifier::AArg:
554       Size +=
555           std::max(FieldWidth,
556                    2 /* 0x */ + 1 /* integer part */ +
557                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
558                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
559       break;
560 
561     // Just a string.
562     case analyze_format_string::ConversionSpecifier::sArg:
563     case analyze_format_string::ConversionSpecifier::SArg:
564       Size += FieldWidth;
565       break;
566 
567     // Just a pointer in the form '0xddd'.
568     case analyze_format_string::ConversionSpecifier::pArg:
569       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
570       break;
571 
572     // A plain percent.
573     case analyze_format_string::ConversionSpecifier::PercentArg:
574       Size += 1;
575       break;
576 
577     default:
578       break;
579     }
580 
581     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
582 
583     if (FS.hasAlternativeForm()) {
584       switch (FS.getConversionSpecifier().getKind()) {
585       default:
586         break;
587       // Force a leading '0'.
588       case analyze_format_string::ConversionSpecifier::oArg:
589         Size += 1;
590         break;
591       // Force a leading '0x'.
592       case analyze_format_string::ConversionSpecifier::xArg:
593       case analyze_format_string::ConversionSpecifier::XArg:
594         Size += 2;
595         break;
596       // Force a period '.' before decimal, even if precision is 0.
597       case analyze_format_string::ConversionSpecifier::aArg:
598       case analyze_format_string::ConversionSpecifier::AArg:
599       case analyze_format_string::ConversionSpecifier::eArg:
600       case analyze_format_string::ConversionSpecifier::EArg:
601       case analyze_format_string::ConversionSpecifier::fArg:
602       case analyze_format_string::ConversionSpecifier::FArg:
603       case analyze_format_string::ConversionSpecifier::gArg:
604       case analyze_format_string::ConversionSpecifier::GArg:
605         Size += (Precision ? 0 : 1);
606         break;
607       }
608     }
609     assert(SpecifierLen <= Size && "no underflow");
610     Size -= SpecifierLen;
611     return true;
612   }
613 
614   size_t getSizeLowerBound() const { return Size; }
615 
616 private:
617   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
618     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
619     size_t FieldWidth = 0;
620     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
621       FieldWidth = FW.getConstantAmount();
622     return FieldWidth;
623   }
624 
625   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
626     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
627     size_t Precision = 0;
628 
629     // See man 3 printf for default precision value based on the specifier.
630     switch (FW.getHowSpecified()) {
631     case analyze_format_string::OptionalAmount::NotSpecified:
632       switch (FS.getConversionSpecifier().getKind()) {
633       default:
634         break;
635       case analyze_format_string::ConversionSpecifier::dArg: // %d
636       case analyze_format_string::ConversionSpecifier::DArg: // %D
637       case analyze_format_string::ConversionSpecifier::iArg: // %i
638         Precision = 1;
639         break;
640       case analyze_format_string::ConversionSpecifier::oArg: // %d
641       case analyze_format_string::ConversionSpecifier::OArg: // %D
642       case analyze_format_string::ConversionSpecifier::uArg: // %d
643       case analyze_format_string::ConversionSpecifier::UArg: // %D
644       case analyze_format_string::ConversionSpecifier::xArg: // %d
645       case analyze_format_string::ConversionSpecifier::XArg: // %D
646         Precision = 1;
647         break;
648       case analyze_format_string::ConversionSpecifier::fArg: // %f
649       case analyze_format_string::ConversionSpecifier::FArg: // %F
650       case analyze_format_string::ConversionSpecifier::eArg: // %e
651       case analyze_format_string::ConversionSpecifier::EArg: // %E
652       case analyze_format_string::ConversionSpecifier::gArg: // %g
653       case analyze_format_string::ConversionSpecifier::GArg: // %G
654         Precision = 6;
655         break;
656       case analyze_format_string::ConversionSpecifier::pArg: // %d
657         Precision = 1;
658         break;
659       }
660       break;
661     case analyze_format_string::OptionalAmount::Constant:
662       Precision = FW.getConstantAmount();
663       break;
664     default:
665       break;
666     }
667     return Precision;
668   }
669 };
670 
671 } // namespace
672 
673 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
674                                                CallExpr *TheCall) {
675   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
676       isConstantEvaluated())
677     return;
678 
679   bool UseDABAttr = false;
680   const FunctionDecl *UseDecl = FD;
681 
682   const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
683   if (DABAttr) {
684     UseDecl = DABAttr->getFunction();
685     assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
686     UseDABAttr = true;
687   }
688 
689   unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
690 
691   if (!BuiltinID)
692     return;
693 
694   const TargetInfo &TI = getASTContext().getTargetInfo();
695   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
696 
697   auto TranslateIndex = [&](unsigned Index) -> Optional<unsigned> {
698     // If we refer to a diagnose_as_builtin attribute, we need to change the
699     // argument index to refer to the arguments of the called function. Unless
700     // the index is out of bounds, which presumably means it's a variadic
701     // function.
702     if (!UseDABAttr)
703       return Index;
704     unsigned DABIndices = DABAttr->argIndices_size();
705     unsigned NewIndex = Index < DABIndices
706                             ? DABAttr->argIndices_begin()[Index]
707                             : Index - DABIndices + FD->getNumParams();
708     if (NewIndex >= TheCall->getNumArgs())
709       return llvm::None;
710     return NewIndex;
711   };
712 
713   auto ComputeExplicitObjectSizeArgument =
714       [&](unsigned Index) -> Optional<llvm::APSInt> {
715     Optional<unsigned> IndexOptional = TranslateIndex(Index);
716     if (!IndexOptional)
717       return llvm::None;
718     unsigned NewIndex = IndexOptional.getValue();
719     Expr::EvalResult Result;
720     Expr *SizeArg = TheCall->getArg(NewIndex);
721     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
722       return llvm::None;
723     llvm::APSInt Integer = Result.Val.getInt();
724     Integer.setIsUnsigned(true);
725     return Integer;
726   };
727 
728   auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
729     // If the parameter has a pass_object_size attribute, then we should use its
730     // (potentially) more strict checking mode. Otherwise, conservatively assume
731     // type 0.
732     int BOSType = 0;
733     // This check can fail for variadic functions.
734     if (Index < FD->getNumParams()) {
735       if (const auto *POS =
736               FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
737         BOSType = POS->getType();
738     }
739 
740     Optional<unsigned> IndexOptional = TranslateIndex(Index);
741     if (!IndexOptional)
742       return llvm::None;
743     unsigned NewIndex = IndexOptional.getValue();
744 
745     const Expr *ObjArg = TheCall->getArg(NewIndex);
746     uint64_t Result;
747     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
748       return llvm::None;
749 
750     // Get the object size in the target's size_t width.
751     return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
752   };
753 
754   auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
755     Optional<unsigned> IndexOptional = TranslateIndex(Index);
756     if (!IndexOptional)
757       return llvm::None;
758     unsigned NewIndex = IndexOptional.getValue();
759 
760     const Expr *ObjArg = TheCall->getArg(NewIndex);
761     uint64_t Result;
762     if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
763       return llvm::None;
764     // Add 1 for null byte.
765     return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
766   };
767 
768   Optional<llvm::APSInt> SourceSize;
769   Optional<llvm::APSInt> DestinationSize;
770   unsigned DiagID = 0;
771   bool IsChkVariant = false;
772 
773   auto GetFunctionName = [&]() {
774     StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
775     // Skim off the details of whichever builtin was called to produce a better
776     // diagnostic, as it's unlikely that the user wrote the __builtin
777     // explicitly.
778     if (IsChkVariant) {
779       FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
780       FunctionName = FunctionName.drop_back(std::strlen("_chk"));
781     } else if (FunctionName.startswith("__builtin_")) {
782       FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
783     }
784     return FunctionName;
785   };
786 
787   switch (BuiltinID) {
788   default:
789     return;
790   case Builtin::BI__builtin_strcpy:
791   case Builtin::BIstrcpy: {
792     DiagID = diag::warn_fortify_strlen_overflow;
793     SourceSize = ComputeStrLenArgument(1);
794     DestinationSize = ComputeSizeArgument(0);
795     break;
796   }
797 
798   case Builtin::BI__builtin___strcpy_chk: {
799     DiagID = diag::warn_fortify_strlen_overflow;
800     SourceSize = ComputeStrLenArgument(1);
801     DestinationSize = ComputeExplicitObjectSizeArgument(2);
802     IsChkVariant = true;
803     break;
804   }
805 
806   case Builtin::BIscanf:
807   case Builtin::BIfscanf:
808   case Builtin::BIsscanf: {
809     unsigned FormatIndex = 1;
810     unsigned DataIndex = 2;
811     if (BuiltinID == Builtin::BIscanf) {
812       FormatIndex = 0;
813       DataIndex = 1;
814     }
815 
816     const auto *FormatExpr =
817         TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
818 
819     const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
820     if (!Format)
821       return;
822 
823     if (!Format->isAscii() && !Format->isUTF8())
824       return;
825 
826     auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
827                         unsigned SourceSize) {
828       DiagID = diag::warn_fortify_scanf_overflow;
829       unsigned Index = ArgIndex + DataIndex;
830       StringRef FunctionName = GetFunctionName();
831       DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
832                           PDiag(DiagID) << FunctionName << (Index + 1)
833                                         << DestSize << SourceSize);
834     };
835 
836     StringRef FormatStrRef = Format->getString();
837     auto ShiftedComputeSizeArgument = [&](unsigned Index) {
838       return ComputeSizeArgument(Index + DataIndex);
839     };
840     ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
841     const char *FormatBytes = FormatStrRef.data();
842     const ConstantArrayType *T =
843         Context.getAsConstantArrayType(Format->getType());
844     assert(T && "String literal not of constant array type!");
845     size_t TypeSize = T->getSize().getZExtValue();
846 
847     // In case there's a null byte somewhere.
848     size_t StrLen =
849         std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
850 
851     analyze_format_string::ParseScanfString(H, FormatBytes,
852                                             FormatBytes + StrLen, getLangOpts(),
853                                             Context.getTargetInfo());
854 
855     // Unlike the other cases, in this one we have already issued the diagnostic
856     // here, so no need to continue (because unlike the other cases, here the
857     // diagnostic refers to the argument number).
858     return;
859   }
860 
861   case Builtin::BIsprintf:
862   case Builtin::BI__builtin___sprintf_chk: {
863     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
864     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
865 
866     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
867 
868       if (!Format->isAscii() && !Format->isUTF8())
869         return;
870 
871       StringRef FormatStrRef = Format->getString();
872       EstimateSizeFormatHandler H(FormatStrRef);
873       const char *FormatBytes = FormatStrRef.data();
874       const ConstantArrayType *T =
875           Context.getAsConstantArrayType(Format->getType());
876       assert(T && "String literal not of constant array type!");
877       size_t TypeSize = T->getSize().getZExtValue();
878 
879       // In case there's a null byte somewhere.
880       size_t StrLen =
881           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
882       if (!analyze_format_string::ParsePrintfString(
883               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
884               Context.getTargetInfo(), false)) {
885         DiagID = diag::warn_fortify_source_format_overflow;
886         SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
887                          .extOrTrunc(SizeTypeWidth);
888         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
889           DestinationSize = ComputeExplicitObjectSizeArgument(2);
890           IsChkVariant = true;
891         } else {
892           DestinationSize = ComputeSizeArgument(0);
893         }
894         break;
895       }
896     }
897     return;
898   }
899   case Builtin::BI__builtin___memcpy_chk:
900   case Builtin::BI__builtin___memmove_chk:
901   case Builtin::BI__builtin___memset_chk:
902   case Builtin::BI__builtin___strlcat_chk:
903   case Builtin::BI__builtin___strlcpy_chk:
904   case Builtin::BI__builtin___strncat_chk:
905   case Builtin::BI__builtin___strncpy_chk:
906   case Builtin::BI__builtin___stpncpy_chk:
907   case Builtin::BI__builtin___memccpy_chk:
908   case Builtin::BI__builtin___mempcpy_chk: {
909     DiagID = diag::warn_builtin_chk_overflow;
910     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
911     DestinationSize =
912         ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
913     IsChkVariant = true;
914     break;
915   }
916 
917   case Builtin::BI__builtin___snprintf_chk:
918   case Builtin::BI__builtin___vsnprintf_chk: {
919     DiagID = diag::warn_builtin_chk_overflow;
920     SourceSize = ComputeExplicitObjectSizeArgument(1);
921     DestinationSize = ComputeExplicitObjectSizeArgument(3);
922     IsChkVariant = true;
923     break;
924   }
925 
926   case Builtin::BIstrncat:
927   case Builtin::BI__builtin_strncat:
928   case Builtin::BIstrncpy:
929   case Builtin::BI__builtin_strncpy:
930   case Builtin::BIstpncpy:
931   case Builtin::BI__builtin_stpncpy: {
932     // Whether these functions overflow depends on the runtime strlen of the
933     // string, not just the buffer size, so emitting the "always overflow"
934     // diagnostic isn't quite right. We should still diagnose passing a buffer
935     // size larger than the destination buffer though; this is a runtime abort
936     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
937     DiagID = diag::warn_fortify_source_size_mismatch;
938     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
939     DestinationSize = ComputeSizeArgument(0);
940     break;
941   }
942 
943   case Builtin::BImemcpy:
944   case Builtin::BI__builtin_memcpy:
945   case Builtin::BImemmove:
946   case Builtin::BI__builtin_memmove:
947   case Builtin::BImemset:
948   case Builtin::BI__builtin_memset:
949   case Builtin::BImempcpy:
950   case Builtin::BI__builtin_mempcpy: {
951     DiagID = diag::warn_fortify_source_overflow;
952     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
953     DestinationSize = ComputeSizeArgument(0);
954     break;
955   }
956   case Builtin::BIsnprintf:
957   case Builtin::BI__builtin_snprintf:
958   case Builtin::BIvsnprintf:
959   case Builtin::BI__builtin_vsnprintf: {
960     DiagID = diag::warn_fortify_source_size_mismatch;
961     SourceSize = ComputeExplicitObjectSizeArgument(1);
962     DestinationSize = ComputeSizeArgument(0);
963     break;
964   }
965   }
966 
967   if (!SourceSize || !DestinationSize ||
968       llvm::APSInt::compareValues(SourceSize.getValue(),
969                                   DestinationSize.getValue()) <= 0)
970     return;
971 
972   StringRef FunctionName = GetFunctionName();
973 
974   SmallString<16> DestinationStr;
975   SmallString<16> SourceStr;
976   DestinationSize->toString(DestinationStr, /*Radix=*/10);
977   SourceSize->toString(SourceStr, /*Radix=*/10);
978   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
979                       PDiag(DiagID)
980                           << FunctionName << DestinationStr << SourceStr);
981 }
982 
983 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
984                                      Scope::ScopeFlags NeededScopeFlags,
985                                      unsigned DiagID) {
986   // Scopes aren't available during instantiation. Fortunately, builtin
987   // functions cannot be template args so they cannot be formed through template
988   // instantiation. Therefore checking once during the parse is sufficient.
989   if (SemaRef.inTemplateInstantiation())
990     return false;
991 
992   Scope *S = SemaRef.getCurScope();
993   while (S && !S->isSEHExceptScope())
994     S = S->getParent();
995   if (!S || !(S->getFlags() & NeededScopeFlags)) {
996     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
997     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
998         << DRE->getDecl()->getIdentifier();
999     return true;
1000   }
1001 
1002   return false;
1003 }
1004 
1005 static inline bool isBlockPointer(Expr *Arg) {
1006   return Arg->getType()->isBlockPointerType();
1007 }
1008 
1009 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
1010 /// void*, which is a requirement of device side enqueue.
1011 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
1012   const BlockPointerType *BPT =
1013       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1014   ArrayRef<QualType> Params =
1015       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
1016   unsigned ArgCounter = 0;
1017   bool IllegalParams = false;
1018   // Iterate through the block parameters until either one is found that is not
1019   // a local void*, or the block is valid.
1020   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
1021        I != E; ++I, ++ArgCounter) {
1022     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
1023         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
1024             LangAS::opencl_local) {
1025       // Get the location of the error. If a block literal has been passed
1026       // (BlockExpr) then we can point straight to the offending argument,
1027       // else we just point to the variable reference.
1028       SourceLocation ErrorLoc;
1029       if (isa<BlockExpr>(BlockArg)) {
1030         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
1031         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
1032       } else if (isa<DeclRefExpr>(BlockArg)) {
1033         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
1034       }
1035       S.Diag(ErrorLoc,
1036              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
1037       IllegalParams = true;
1038     }
1039   }
1040 
1041   return IllegalParams;
1042 }
1043 
1044 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
1045   // OpenCL device can support extension but not the feature as extension
1046   // requires subgroup independent forward progress, but subgroup independent
1047   // forward progress is optional in OpenCL C 3.0 __opencl_c_subgroups feature.
1048   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts()) &&
1049       !S.getOpenCLOptions().isSupported("__opencl_c_subgroups",
1050                                         S.getLangOpts())) {
1051     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
1052         << 1 << Call->getDirectCallee()
1053         << "cl_khr_subgroups or __opencl_c_subgroups";
1054     return true;
1055   }
1056   return false;
1057 }
1058 
1059 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
1060   if (checkArgCount(S, TheCall, 2))
1061     return true;
1062 
1063   if (checkOpenCLSubgroupExt(S, TheCall))
1064     return true;
1065 
1066   // First argument is an ndrange_t type.
1067   Expr *NDRangeArg = TheCall->getArg(0);
1068   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1069     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1070         << TheCall->getDirectCallee() << "'ndrange_t'";
1071     return true;
1072   }
1073 
1074   Expr *BlockArg = TheCall->getArg(1);
1075   if (!isBlockPointer(BlockArg)) {
1076     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1077         << TheCall->getDirectCallee() << "block";
1078     return true;
1079   }
1080   return checkOpenCLBlockArgs(S, BlockArg);
1081 }
1082 
1083 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
1084 /// get_kernel_work_group_size
1085 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
1086 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
1087   if (checkArgCount(S, TheCall, 1))
1088     return true;
1089 
1090   Expr *BlockArg = TheCall->getArg(0);
1091   if (!isBlockPointer(BlockArg)) {
1092     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1093         << TheCall->getDirectCallee() << "block";
1094     return true;
1095   }
1096   return checkOpenCLBlockArgs(S, BlockArg);
1097 }
1098 
1099 /// Diagnose integer type and any valid implicit conversion to it.
1100 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
1101                                       const QualType &IntType);
1102 
1103 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
1104                                             unsigned Start, unsigned End) {
1105   bool IllegalParams = false;
1106   for (unsigned I = Start; I <= End; ++I)
1107     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
1108                                               S.Context.getSizeType());
1109   return IllegalParams;
1110 }
1111 
1112 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
1113 /// 'local void*' parameter of passed block.
1114 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
1115                                            Expr *BlockArg,
1116                                            unsigned NumNonVarArgs) {
1117   const BlockPointerType *BPT =
1118       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1119   unsigned NumBlockParams =
1120       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
1121   unsigned TotalNumArgs = TheCall->getNumArgs();
1122 
1123   // For each argument passed to the block, a corresponding uint needs to
1124   // be passed to describe the size of the local memory.
1125   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
1126     S.Diag(TheCall->getBeginLoc(),
1127            diag::err_opencl_enqueue_kernel_local_size_args);
1128     return true;
1129   }
1130 
1131   // Check that the sizes of the local memory are specified by integers.
1132   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
1133                                          TotalNumArgs - 1);
1134 }
1135 
1136 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
1137 /// overload formats specified in Table 6.13.17.1.
1138 /// int enqueue_kernel(queue_t queue,
1139 ///                    kernel_enqueue_flags_t flags,
1140 ///                    const ndrange_t ndrange,
1141 ///                    void (^block)(void))
1142 /// int enqueue_kernel(queue_t queue,
1143 ///                    kernel_enqueue_flags_t flags,
1144 ///                    const ndrange_t ndrange,
1145 ///                    uint num_events_in_wait_list,
1146 ///                    clk_event_t *event_wait_list,
1147 ///                    clk_event_t *event_ret,
1148 ///                    void (^block)(void))
1149 /// int enqueue_kernel(queue_t queue,
1150 ///                    kernel_enqueue_flags_t flags,
1151 ///                    const ndrange_t ndrange,
1152 ///                    void (^block)(local void*, ...),
1153 ///                    uint size0, ...)
1154 /// int enqueue_kernel(queue_t queue,
1155 ///                    kernel_enqueue_flags_t flags,
1156 ///                    const ndrange_t ndrange,
1157 ///                    uint num_events_in_wait_list,
1158 ///                    clk_event_t *event_wait_list,
1159 ///                    clk_event_t *event_ret,
1160 ///                    void (^block)(local void*, ...),
1161 ///                    uint size0, ...)
1162 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
1163   unsigned NumArgs = TheCall->getNumArgs();
1164 
1165   if (NumArgs < 4) {
1166     S.Diag(TheCall->getBeginLoc(),
1167            diag::err_typecheck_call_too_few_args_at_least)
1168         << 0 << 4 << NumArgs;
1169     return true;
1170   }
1171 
1172   Expr *Arg0 = TheCall->getArg(0);
1173   Expr *Arg1 = TheCall->getArg(1);
1174   Expr *Arg2 = TheCall->getArg(2);
1175   Expr *Arg3 = TheCall->getArg(3);
1176 
1177   // First argument always needs to be a queue_t type.
1178   if (!Arg0->getType()->isQueueT()) {
1179     S.Diag(TheCall->getArg(0)->getBeginLoc(),
1180            diag::err_opencl_builtin_expected_type)
1181         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
1182     return true;
1183   }
1184 
1185   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
1186   if (!Arg1->getType()->isIntegerType()) {
1187     S.Diag(TheCall->getArg(1)->getBeginLoc(),
1188            diag::err_opencl_builtin_expected_type)
1189         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
1190     return true;
1191   }
1192 
1193   // Third argument is always an ndrange_t type.
1194   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1195     S.Diag(TheCall->getArg(2)->getBeginLoc(),
1196            diag::err_opencl_builtin_expected_type)
1197         << TheCall->getDirectCallee() << "'ndrange_t'";
1198     return true;
1199   }
1200 
1201   // With four arguments, there is only one form that the function could be
1202   // called in: no events and no variable arguments.
1203   if (NumArgs == 4) {
1204     // check that the last argument is the right block type.
1205     if (!isBlockPointer(Arg3)) {
1206       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1207           << TheCall->getDirectCallee() << "block";
1208       return true;
1209     }
1210     // we have a block type, check the prototype
1211     const BlockPointerType *BPT =
1212         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1213     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1214       S.Diag(Arg3->getBeginLoc(),
1215              diag::err_opencl_enqueue_kernel_blocks_no_args);
1216       return true;
1217     }
1218     return false;
1219   }
1220   // we can have block + varargs.
1221   if (isBlockPointer(Arg3))
1222     return (checkOpenCLBlockArgs(S, Arg3) ||
1223             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1224   // last two cases with either exactly 7 args or 7 args and varargs.
1225   if (NumArgs >= 7) {
1226     // check common block argument.
1227     Expr *Arg6 = TheCall->getArg(6);
1228     if (!isBlockPointer(Arg6)) {
1229       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1230           << TheCall->getDirectCallee() << "block";
1231       return true;
1232     }
1233     if (checkOpenCLBlockArgs(S, Arg6))
1234       return true;
1235 
1236     // Forth argument has to be any integer type.
1237     if (!Arg3->getType()->isIntegerType()) {
1238       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1239              diag::err_opencl_builtin_expected_type)
1240           << TheCall->getDirectCallee() << "integer";
1241       return true;
1242     }
1243     // check remaining common arguments.
1244     Expr *Arg4 = TheCall->getArg(4);
1245     Expr *Arg5 = TheCall->getArg(5);
1246 
1247     // Fifth argument is always passed as a pointer to clk_event_t.
1248     if (!Arg4->isNullPointerConstant(S.Context,
1249                                      Expr::NPC_ValueDependentIsNotNull) &&
1250         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1251       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1252              diag::err_opencl_builtin_expected_type)
1253           << TheCall->getDirectCallee()
1254           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1255       return true;
1256     }
1257 
1258     // Sixth argument is always passed as a pointer to clk_event_t.
1259     if (!Arg5->isNullPointerConstant(S.Context,
1260                                      Expr::NPC_ValueDependentIsNotNull) &&
1261         !(Arg5->getType()->isPointerType() &&
1262           Arg5->getType()->getPointeeType()->isClkEventT())) {
1263       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1264              diag::err_opencl_builtin_expected_type)
1265           << TheCall->getDirectCallee()
1266           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1267       return true;
1268     }
1269 
1270     if (NumArgs == 7)
1271       return false;
1272 
1273     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1274   }
1275 
1276   // None of the specific case has been detected, give generic error
1277   S.Diag(TheCall->getBeginLoc(),
1278          diag::err_opencl_enqueue_kernel_incorrect_args);
1279   return true;
1280 }
1281 
1282 /// Returns OpenCL access qual.
1283 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1284     return D->getAttr<OpenCLAccessAttr>();
1285 }
1286 
1287 /// Returns true if pipe element type is different from the pointer.
1288 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1289   const Expr *Arg0 = Call->getArg(0);
1290   // First argument type should always be pipe.
1291   if (!Arg0->getType()->isPipeType()) {
1292     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1293         << Call->getDirectCallee() << Arg0->getSourceRange();
1294     return true;
1295   }
1296   OpenCLAccessAttr *AccessQual =
1297       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1298   // Validates the access qualifier is compatible with the call.
1299   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1300   // read_only and write_only, and assumed to be read_only if no qualifier is
1301   // specified.
1302   switch (Call->getDirectCallee()->getBuiltinID()) {
1303   case Builtin::BIread_pipe:
1304   case Builtin::BIreserve_read_pipe:
1305   case Builtin::BIcommit_read_pipe:
1306   case Builtin::BIwork_group_reserve_read_pipe:
1307   case Builtin::BIsub_group_reserve_read_pipe:
1308   case Builtin::BIwork_group_commit_read_pipe:
1309   case Builtin::BIsub_group_commit_read_pipe:
1310     if (!(!AccessQual || AccessQual->isReadOnly())) {
1311       S.Diag(Arg0->getBeginLoc(),
1312              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1313           << "read_only" << Arg0->getSourceRange();
1314       return true;
1315     }
1316     break;
1317   case Builtin::BIwrite_pipe:
1318   case Builtin::BIreserve_write_pipe:
1319   case Builtin::BIcommit_write_pipe:
1320   case Builtin::BIwork_group_reserve_write_pipe:
1321   case Builtin::BIsub_group_reserve_write_pipe:
1322   case Builtin::BIwork_group_commit_write_pipe:
1323   case Builtin::BIsub_group_commit_write_pipe:
1324     if (!(AccessQual && AccessQual->isWriteOnly())) {
1325       S.Diag(Arg0->getBeginLoc(),
1326              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1327           << "write_only" << Arg0->getSourceRange();
1328       return true;
1329     }
1330     break;
1331   default:
1332     break;
1333   }
1334   return false;
1335 }
1336 
1337 /// Returns true if pipe element type is different from the pointer.
1338 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1339   const Expr *Arg0 = Call->getArg(0);
1340   const Expr *ArgIdx = Call->getArg(Idx);
1341   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1342   const QualType EltTy = PipeTy->getElementType();
1343   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1344   // The Idx argument should be a pointer and the type of the pointer and
1345   // the type of pipe element should also be the same.
1346   if (!ArgTy ||
1347       !S.Context.hasSameType(
1348           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1349     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1350         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1351         << ArgIdx->getType() << ArgIdx->getSourceRange();
1352     return true;
1353   }
1354   return false;
1355 }
1356 
1357 // Performs semantic analysis for the read/write_pipe call.
1358 // \param S Reference to the semantic analyzer.
1359 // \param Call A pointer to the builtin call.
1360 // \return True if a semantic error has been found, false otherwise.
1361 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1362   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1363   // functions have two forms.
1364   switch (Call->getNumArgs()) {
1365   case 2:
1366     if (checkOpenCLPipeArg(S, Call))
1367       return true;
1368     // The call with 2 arguments should be
1369     // read/write_pipe(pipe T, T*).
1370     // Check packet type T.
1371     if (checkOpenCLPipePacketType(S, Call, 1))
1372       return true;
1373     break;
1374 
1375   case 4: {
1376     if (checkOpenCLPipeArg(S, Call))
1377       return true;
1378     // The call with 4 arguments should be
1379     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1380     // Check reserve_id_t.
1381     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1382       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1383           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1384           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1385       return true;
1386     }
1387 
1388     // Check the index.
1389     const Expr *Arg2 = Call->getArg(2);
1390     if (!Arg2->getType()->isIntegerType() &&
1391         !Arg2->getType()->isUnsignedIntegerType()) {
1392       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1393           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1394           << Arg2->getType() << Arg2->getSourceRange();
1395       return true;
1396     }
1397 
1398     // Check packet type T.
1399     if (checkOpenCLPipePacketType(S, Call, 3))
1400       return true;
1401   } break;
1402   default:
1403     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1404         << Call->getDirectCallee() << Call->getSourceRange();
1405     return true;
1406   }
1407 
1408   return false;
1409 }
1410 
1411 // Performs a semantic analysis on the {work_group_/sub_group_
1412 //        /_}reserve_{read/write}_pipe
1413 // \param S Reference to the semantic analyzer.
1414 // \param Call The call to the builtin function to be analyzed.
1415 // \return True if a semantic error was found, false otherwise.
1416 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1417   if (checkArgCount(S, Call, 2))
1418     return true;
1419 
1420   if (checkOpenCLPipeArg(S, Call))
1421     return true;
1422 
1423   // Check the reserve size.
1424   if (!Call->getArg(1)->getType()->isIntegerType() &&
1425       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1426     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1427         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1428         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1429     return true;
1430   }
1431 
1432   // Since return type of reserve_read/write_pipe built-in function is
1433   // reserve_id_t, which is not defined in the builtin def file , we used int
1434   // as return type and need to override the return type of these functions.
1435   Call->setType(S.Context.OCLReserveIDTy);
1436 
1437   return false;
1438 }
1439 
1440 // Performs a semantic analysis on {work_group_/sub_group_
1441 //        /_}commit_{read/write}_pipe
1442 // \param S Reference to the semantic analyzer.
1443 // \param Call The call to the builtin function to be analyzed.
1444 // \return True if a semantic error was found, false otherwise.
1445 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1446   if (checkArgCount(S, Call, 2))
1447     return true;
1448 
1449   if (checkOpenCLPipeArg(S, Call))
1450     return true;
1451 
1452   // Check reserve_id_t.
1453   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1454     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1455         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1456         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1457     return true;
1458   }
1459 
1460   return false;
1461 }
1462 
1463 // Performs a semantic analysis on the call to built-in Pipe
1464 //        Query Functions.
1465 // \param S Reference to the semantic analyzer.
1466 // \param Call The call to the builtin function to be analyzed.
1467 // \return True if a semantic error was found, false otherwise.
1468 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1469   if (checkArgCount(S, Call, 1))
1470     return true;
1471 
1472   if (!Call->getArg(0)->getType()->isPipeType()) {
1473     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1474         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1475     return true;
1476   }
1477 
1478   return false;
1479 }
1480 
1481 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1482 // Performs semantic analysis for the to_global/local/private call.
1483 // \param S Reference to the semantic analyzer.
1484 // \param BuiltinID ID of the builtin function.
1485 // \param Call A pointer to the builtin call.
1486 // \return True if a semantic error has been found, false otherwise.
1487 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1488                                     CallExpr *Call) {
1489   if (checkArgCount(S, Call, 1))
1490     return true;
1491 
1492   auto RT = Call->getArg(0)->getType();
1493   if (!RT->isPointerType() || RT->getPointeeType()
1494       .getAddressSpace() == LangAS::opencl_constant) {
1495     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1496         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1497     return true;
1498   }
1499 
1500   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1501     S.Diag(Call->getArg(0)->getBeginLoc(),
1502            diag::warn_opencl_generic_address_space_arg)
1503         << Call->getDirectCallee()->getNameInfo().getAsString()
1504         << Call->getArg(0)->getSourceRange();
1505   }
1506 
1507   RT = RT->getPointeeType();
1508   auto Qual = RT.getQualifiers();
1509   switch (BuiltinID) {
1510   case Builtin::BIto_global:
1511     Qual.setAddressSpace(LangAS::opencl_global);
1512     break;
1513   case Builtin::BIto_local:
1514     Qual.setAddressSpace(LangAS::opencl_local);
1515     break;
1516   case Builtin::BIto_private:
1517     Qual.setAddressSpace(LangAS::opencl_private);
1518     break;
1519   default:
1520     llvm_unreachable("Invalid builtin function");
1521   }
1522   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1523       RT.getUnqualifiedType(), Qual)));
1524 
1525   return false;
1526 }
1527 
1528 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1529   if (checkArgCount(S, TheCall, 1))
1530     return ExprError();
1531 
1532   // Compute __builtin_launder's parameter type from the argument.
1533   // The parameter type is:
1534   //  * The type of the argument if it's not an array or function type,
1535   //  Otherwise,
1536   //  * The decayed argument type.
1537   QualType ParamTy = [&]() {
1538     QualType ArgTy = TheCall->getArg(0)->getType();
1539     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1540       return S.Context.getPointerType(Ty->getElementType());
1541     if (ArgTy->isFunctionType()) {
1542       return S.Context.getPointerType(ArgTy);
1543     }
1544     return ArgTy;
1545   }();
1546 
1547   TheCall->setType(ParamTy);
1548 
1549   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1550     if (!ParamTy->isPointerType())
1551       return 0;
1552     if (ParamTy->isFunctionPointerType())
1553       return 1;
1554     if (ParamTy->isVoidPointerType())
1555       return 2;
1556     return llvm::Optional<unsigned>{};
1557   }();
1558   if (DiagSelect.hasValue()) {
1559     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1560         << DiagSelect.getValue() << TheCall->getSourceRange();
1561     return ExprError();
1562   }
1563 
1564   // We either have an incomplete class type, or we have a class template
1565   // whose instantiation has not been forced. Example:
1566   //
1567   //   template <class T> struct Foo { T value; };
1568   //   Foo<int> *p = nullptr;
1569   //   auto *d = __builtin_launder(p);
1570   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1571                             diag::err_incomplete_type))
1572     return ExprError();
1573 
1574   assert(ParamTy->getPointeeType()->isObjectType() &&
1575          "Unhandled non-object pointer case");
1576 
1577   InitializedEntity Entity =
1578       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1579   ExprResult Arg =
1580       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1581   if (Arg.isInvalid())
1582     return ExprError();
1583   TheCall->setArg(0, Arg.get());
1584 
1585   return TheCall;
1586 }
1587 
1588 // Emit an error and return true if the current object format type is in the
1589 // list of unsupported types.
1590 static bool CheckBuiltinTargetNotInUnsupported(
1591     Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1592     ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
1593   llvm::Triple::ObjectFormatType CurObjFormat =
1594       S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
1595   if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
1596     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1597         << TheCall->getSourceRange();
1598     return true;
1599   }
1600   return false;
1601 }
1602 
1603 // Emit an error and return true if the current architecture is not in the list
1604 // of supported architectures.
1605 static bool
1606 CheckBuiltinTargetInSupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1607                               ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1608   llvm::Triple::ArchType CurArch =
1609       S.getASTContext().getTargetInfo().getTriple().getArch();
1610   if (llvm::is_contained(SupportedArchs, CurArch))
1611     return false;
1612   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1613       << TheCall->getSourceRange();
1614   return true;
1615 }
1616 
1617 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1618                                  SourceLocation CallSiteLoc);
1619 
1620 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1621                                       CallExpr *TheCall) {
1622   switch (TI.getTriple().getArch()) {
1623   default:
1624     // Some builtins don't require additional checking, so just consider these
1625     // acceptable.
1626     return false;
1627   case llvm::Triple::arm:
1628   case llvm::Triple::armeb:
1629   case llvm::Triple::thumb:
1630   case llvm::Triple::thumbeb:
1631     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1632   case llvm::Triple::aarch64:
1633   case llvm::Triple::aarch64_32:
1634   case llvm::Triple::aarch64_be:
1635     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1636   case llvm::Triple::bpfeb:
1637   case llvm::Triple::bpfel:
1638     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1639   case llvm::Triple::hexagon:
1640     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1641   case llvm::Triple::mips:
1642   case llvm::Triple::mipsel:
1643   case llvm::Triple::mips64:
1644   case llvm::Triple::mips64el:
1645     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1646   case llvm::Triple::systemz:
1647     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1648   case llvm::Triple::x86:
1649   case llvm::Triple::x86_64:
1650     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1651   case llvm::Triple::ppc:
1652   case llvm::Triple::ppcle:
1653   case llvm::Triple::ppc64:
1654   case llvm::Triple::ppc64le:
1655     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1656   case llvm::Triple::amdgcn:
1657     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1658   case llvm::Triple::riscv32:
1659   case llvm::Triple::riscv64:
1660     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1661   }
1662 }
1663 
1664 ExprResult
1665 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1666                                CallExpr *TheCall) {
1667   ExprResult TheCallResult(TheCall);
1668 
1669   // Find out if any arguments are required to be integer constant expressions.
1670   unsigned ICEArguments = 0;
1671   ASTContext::GetBuiltinTypeError Error;
1672   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1673   if (Error != ASTContext::GE_None)
1674     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1675 
1676   // If any arguments are required to be ICE's, check and diagnose.
1677   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1678     // Skip arguments not required to be ICE's.
1679     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1680 
1681     llvm::APSInt Result;
1682     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1683       return true;
1684     ICEArguments &= ~(1 << ArgNo);
1685   }
1686 
1687   switch (BuiltinID) {
1688   case Builtin::BI__builtin___CFStringMakeConstantString:
1689     // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
1690     // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
1691     if (CheckBuiltinTargetNotInUnsupported(
1692             *this, BuiltinID, TheCall,
1693             {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
1694       return ExprError();
1695     assert(TheCall->getNumArgs() == 1 &&
1696            "Wrong # arguments to builtin CFStringMakeConstantString");
1697     if (CheckObjCString(TheCall->getArg(0)))
1698       return ExprError();
1699     break;
1700   case Builtin::BI__builtin_ms_va_start:
1701   case Builtin::BI__builtin_stdarg_start:
1702   case Builtin::BI__builtin_va_start:
1703     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1704       return ExprError();
1705     break;
1706   case Builtin::BI__va_start: {
1707     switch (Context.getTargetInfo().getTriple().getArch()) {
1708     case llvm::Triple::aarch64:
1709     case llvm::Triple::arm:
1710     case llvm::Triple::thumb:
1711       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1712         return ExprError();
1713       break;
1714     default:
1715       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1716         return ExprError();
1717       break;
1718     }
1719     break;
1720   }
1721 
1722   // The acquire, release, and no fence variants are ARM and AArch64 only.
1723   case Builtin::BI_interlockedbittestandset_acq:
1724   case Builtin::BI_interlockedbittestandset_rel:
1725   case Builtin::BI_interlockedbittestandset_nf:
1726   case Builtin::BI_interlockedbittestandreset_acq:
1727   case Builtin::BI_interlockedbittestandreset_rel:
1728   case Builtin::BI_interlockedbittestandreset_nf:
1729     if (CheckBuiltinTargetInSupported(
1730             *this, BuiltinID, TheCall,
1731             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1732       return ExprError();
1733     break;
1734 
1735   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1736   case Builtin::BI_bittest64:
1737   case Builtin::BI_bittestandcomplement64:
1738   case Builtin::BI_bittestandreset64:
1739   case Builtin::BI_bittestandset64:
1740   case Builtin::BI_interlockedbittestandreset64:
1741   case Builtin::BI_interlockedbittestandset64:
1742     if (CheckBuiltinTargetInSupported(*this, BuiltinID, TheCall,
1743                                       {llvm::Triple::x86_64, llvm::Triple::arm,
1744                                        llvm::Triple::thumb,
1745                                        llvm::Triple::aarch64}))
1746       return ExprError();
1747     break;
1748 
1749   case Builtin::BI__builtin_isgreater:
1750   case Builtin::BI__builtin_isgreaterequal:
1751   case Builtin::BI__builtin_isless:
1752   case Builtin::BI__builtin_islessequal:
1753   case Builtin::BI__builtin_islessgreater:
1754   case Builtin::BI__builtin_isunordered:
1755     if (SemaBuiltinUnorderedCompare(TheCall))
1756       return ExprError();
1757     break;
1758   case Builtin::BI__builtin_fpclassify:
1759     if (SemaBuiltinFPClassification(TheCall, 6))
1760       return ExprError();
1761     break;
1762   case Builtin::BI__builtin_isfinite:
1763   case Builtin::BI__builtin_isinf:
1764   case Builtin::BI__builtin_isinf_sign:
1765   case Builtin::BI__builtin_isnan:
1766   case Builtin::BI__builtin_isnormal:
1767   case Builtin::BI__builtin_signbit:
1768   case Builtin::BI__builtin_signbitf:
1769   case Builtin::BI__builtin_signbitl:
1770     if (SemaBuiltinFPClassification(TheCall, 1))
1771       return ExprError();
1772     break;
1773   case Builtin::BI__builtin_shufflevector:
1774     return SemaBuiltinShuffleVector(TheCall);
1775     // TheCall will be freed by the smart pointer here, but that's fine, since
1776     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1777   case Builtin::BI__builtin_prefetch:
1778     if (SemaBuiltinPrefetch(TheCall))
1779       return ExprError();
1780     break;
1781   case Builtin::BI__builtin_alloca_with_align:
1782   case Builtin::BI__builtin_alloca_with_align_uninitialized:
1783     if (SemaBuiltinAllocaWithAlign(TheCall))
1784       return ExprError();
1785     LLVM_FALLTHROUGH;
1786   case Builtin::BI__builtin_alloca:
1787   case Builtin::BI__builtin_alloca_uninitialized:
1788     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1789         << TheCall->getDirectCallee();
1790     break;
1791   case Builtin::BI__arithmetic_fence:
1792     if (SemaBuiltinArithmeticFence(TheCall))
1793       return ExprError();
1794     break;
1795   case Builtin::BI__assume:
1796   case Builtin::BI__builtin_assume:
1797     if (SemaBuiltinAssume(TheCall))
1798       return ExprError();
1799     break;
1800   case Builtin::BI__builtin_assume_aligned:
1801     if (SemaBuiltinAssumeAligned(TheCall))
1802       return ExprError();
1803     break;
1804   case Builtin::BI__builtin_dynamic_object_size:
1805   case Builtin::BI__builtin_object_size:
1806     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1807       return ExprError();
1808     break;
1809   case Builtin::BI__builtin_longjmp:
1810     if (SemaBuiltinLongjmp(TheCall))
1811       return ExprError();
1812     break;
1813   case Builtin::BI__builtin_setjmp:
1814     if (SemaBuiltinSetjmp(TheCall))
1815       return ExprError();
1816     break;
1817   case Builtin::BI__builtin_classify_type:
1818     if (checkArgCount(*this, TheCall, 1)) return true;
1819     TheCall->setType(Context.IntTy);
1820     break;
1821   case Builtin::BI__builtin_complex:
1822     if (SemaBuiltinComplex(TheCall))
1823       return ExprError();
1824     break;
1825   case Builtin::BI__builtin_constant_p: {
1826     if (checkArgCount(*this, TheCall, 1)) return true;
1827     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1828     if (Arg.isInvalid()) return true;
1829     TheCall->setArg(0, Arg.get());
1830     TheCall->setType(Context.IntTy);
1831     break;
1832   }
1833   case Builtin::BI__builtin_launder:
1834     return SemaBuiltinLaunder(*this, TheCall);
1835   case Builtin::BI__sync_fetch_and_add:
1836   case Builtin::BI__sync_fetch_and_add_1:
1837   case Builtin::BI__sync_fetch_and_add_2:
1838   case Builtin::BI__sync_fetch_and_add_4:
1839   case Builtin::BI__sync_fetch_and_add_8:
1840   case Builtin::BI__sync_fetch_and_add_16:
1841   case Builtin::BI__sync_fetch_and_sub:
1842   case Builtin::BI__sync_fetch_and_sub_1:
1843   case Builtin::BI__sync_fetch_and_sub_2:
1844   case Builtin::BI__sync_fetch_and_sub_4:
1845   case Builtin::BI__sync_fetch_and_sub_8:
1846   case Builtin::BI__sync_fetch_and_sub_16:
1847   case Builtin::BI__sync_fetch_and_or:
1848   case Builtin::BI__sync_fetch_and_or_1:
1849   case Builtin::BI__sync_fetch_and_or_2:
1850   case Builtin::BI__sync_fetch_and_or_4:
1851   case Builtin::BI__sync_fetch_and_or_8:
1852   case Builtin::BI__sync_fetch_and_or_16:
1853   case Builtin::BI__sync_fetch_and_and:
1854   case Builtin::BI__sync_fetch_and_and_1:
1855   case Builtin::BI__sync_fetch_and_and_2:
1856   case Builtin::BI__sync_fetch_and_and_4:
1857   case Builtin::BI__sync_fetch_and_and_8:
1858   case Builtin::BI__sync_fetch_and_and_16:
1859   case Builtin::BI__sync_fetch_and_xor:
1860   case Builtin::BI__sync_fetch_and_xor_1:
1861   case Builtin::BI__sync_fetch_and_xor_2:
1862   case Builtin::BI__sync_fetch_and_xor_4:
1863   case Builtin::BI__sync_fetch_and_xor_8:
1864   case Builtin::BI__sync_fetch_and_xor_16:
1865   case Builtin::BI__sync_fetch_and_nand:
1866   case Builtin::BI__sync_fetch_and_nand_1:
1867   case Builtin::BI__sync_fetch_and_nand_2:
1868   case Builtin::BI__sync_fetch_and_nand_4:
1869   case Builtin::BI__sync_fetch_and_nand_8:
1870   case Builtin::BI__sync_fetch_and_nand_16:
1871   case Builtin::BI__sync_add_and_fetch:
1872   case Builtin::BI__sync_add_and_fetch_1:
1873   case Builtin::BI__sync_add_and_fetch_2:
1874   case Builtin::BI__sync_add_and_fetch_4:
1875   case Builtin::BI__sync_add_and_fetch_8:
1876   case Builtin::BI__sync_add_and_fetch_16:
1877   case Builtin::BI__sync_sub_and_fetch:
1878   case Builtin::BI__sync_sub_and_fetch_1:
1879   case Builtin::BI__sync_sub_and_fetch_2:
1880   case Builtin::BI__sync_sub_and_fetch_4:
1881   case Builtin::BI__sync_sub_and_fetch_8:
1882   case Builtin::BI__sync_sub_and_fetch_16:
1883   case Builtin::BI__sync_and_and_fetch:
1884   case Builtin::BI__sync_and_and_fetch_1:
1885   case Builtin::BI__sync_and_and_fetch_2:
1886   case Builtin::BI__sync_and_and_fetch_4:
1887   case Builtin::BI__sync_and_and_fetch_8:
1888   case Builtin::BI__sync_and_and_fetch_16:
1889   case Builtin::BI__sync_or_and_fetch:
1890   case Builtin::BI__sync_or_and_fetch_1:
1891   case Builtin::BI__sync_or_and_fetch_2:
1892   case Builtin::BI__sync_or_and_fetch_4:
1893   case Builtin::BI__sync_or_and_fetch_8:
1894   case Builtin::BI__sync_or_and_fetch_16:
1895   case Builtin::BI__sync_xor_and_fetch:
1896   case Builtin::BI__sync_xor_and_fetch_1:
1897   case Builtin::BI__sync_xor_and_fetch_2:
1898   case Builtin::BI__sync_xor_and_fetch_4:
1899   case Builtin::BI__sync_xor_and_fetch_8:
1900   case Builtin::BI__sync_xor_and_fetch_16:
1901   case Builtin::BI__sync_nand_and_fetch:
1902   case Builtin::BI__sync_nand_and_fetch_1:
1903   case Builtin::BI__sync_nand_and_fetch_2:
1904   case Builtin::BI__sync_nand_and_fetch_4:
1905   case Builtin::BI__sync_nand_and_fetch_8:
1906   case Builtin::BI__sync_nand_and_fetch_16:
1907   case Builtin::BI__sync_val_compare_and_swap:
1908   case Builtin::BI__sync_val_compare_and_swap_1:
1909   case Builtin::BI__sync_val_compare_and_swap_2:
1910   case Builtin::BI__sync_val_compare_and_swap_4:
1911   case Builtin::BI__sync_val_compare_and_swap_8:
1912   case Builtin::BI__sync_val_compare_and_swap_16:
1913   case Builtin::BI__sync_bool_compare_and_swap:
1914   case Builtin::BI__sync_bool_compare_and_swap_1:
1915   case Builtin::BI__sync_bool_compare_and_swap_2:
1916   case Builtin::BI__sync_bool_compare_and_swap_4:
1917   case Builtin::BI__sync_bool_compare_and_swap_8:
1918   case Builtin::BI__sync_bool_compare_and_swap_16:
1919   case Builtin::BI__sync_lock_test_and_set:
1920   case Builtin::BI__sync_lock_test_and_set_1:
1921   case Builtin::BI__sync_lock_test_and_set_2:
1922   case Builtin::BI__sync_lock_test_and_set_4:
1923   case Builtin::BI__sync_lock_test_and_set_8:
1924   case Builtin::BI__sync_lock_test_and_set_16:
1925   case Builtin::BI__sync_lock_release:
1926   case Builtin::BI__sync_lock_release_1:
1927   case Builtin::BI__sync_lock_release_2:
1928   case Builtin::BI__sync_lock_release_4:
1929   case Builtin::BI__sync_lock_release_8:
1930   case Builtin::BI__sync_lock_release_16:
1931   case Builtin::BI__sync_swap:
1932   case Builtin::BI__sync_swap_1:
1933   case Builtin::BI__sync_swap_2:
1934   case Builtin::BI__sync_swap_4:
1935   case Builtin::BI__sync_swap_8:
1936   case Builtin::BI__sync_swap_16:
1937     return SemaBuiltinAtomicOverloaded(TheCallResult);
1938   case Builtin::BI__sync_synchronize:
1939     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1940         << TheCall->getCallee()->getSourceRange();
1941     break;
1942   case Builtin::BI__builtin_nontemporal_load:
1943   case Builtin::BI__builtin_nontemporal_store:
1944     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1945   case Builtin::BI__builtin_memcpy_inline: {
1946     auto ArgArrayConversionFailed = [&](unsigned Arg) {
1947       ExprResult ArgExpr =
1948           DefaultFunctionArrayLvalueConversion(TheCall->getArg(Arg));
1949       if (ArgExpr.isInvalid())
1950         return true;
1951       TheCall->setArg(Arg, ArgExpr.get());
1952       return false;
1953     };
1954 
1955     if (ArgArrayConversionFailed(0) || ArgArrayConversionFailed(1))
1956       return true;
1957     clang::Expr *SizeOp = TheCall->getArg(2);
1958     // We warn about copying to or from `nullptr` pointers when `size` is
1959     // greater than 0. When `size` is value dependent we cannot evaluate its
1960     // value so we bail out.
1961     if (SizeOp->isValueDependent())
1962       break;
1963     if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
1964       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1965       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1966     }
1967     break;
1968   }
1969 #define BUILTIN(ID, TYPE, ATTRS)
1970 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1971   case Builtin::BI##ID: \
1972     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1973 #include "clang/Basic/Builtins.def"
1974   case Builtin::BI__annotation:
1975     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1976       return ExprError();
1977     break;
1978   case Builtin::BI__builtin_annotation:
1979     if (SemaBuiltinAnnotation(*this, TheCall))
1980       return ExprError();
1981     break;
1982   case Builtin::BI__builtin_addressof:
1983     if (SemaBuiltinAddressof(*this, TheCall))
1984       return ExprError();
1985     break;
1986   case Builtin::BI__builtin_function_start:
1987     if (SemaBuiltinFunctionStart(*this, TheCall))
1988       return ExprError();
1989     break;
1990   case Builtin::BI__builtin_is_aligned:
1991   case Builtin::BI__builtin_align_up:
1992   case Builtin::BI__builtin_align_down:
1993     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1994       return ExprError();
1995     break;
1996   case Builtin::BI__builtin_add_overflow:
1997   case Builtin::BI__builtin_sub_overflow:
1998   case Builtin::BI__builtin_mul_overflow:
1999     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
2000       return ExprError();
2001     break;
2002   case Builtin::BI__builtin_operator_new:
2003   case Builtin::BI__builtin_operator_delete: {
2004     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
2005     ExprResult Res =
2006         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
2007     if (Res.isInvalid())
2008       CorrectDelayedTyposInExpr(TheCallResult.get());
2009     return Res;
2010   }
2011   case Builtin::BI__builtin_dump_struct: {
2012     // We first want to ensure we are called with 2 arguments
2013     if (checkArgCount(*this, TheCall, 2))
2014       return ExprError();
2015     // Ensure that the first argument is of type 'struct XX *'
2016     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
2017     const QualType PtrArgType = PtrArg->getType();
2018     if (!PtrArgType->isPointerType() ||
2019         !PtrArgType->getPointeeType()->isRecordType()) {
2020       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2021           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
2022           << "structure pointer";
2023       return ExprError();
2024     }
2025 
2026     // Ensure that the second argument is of type 'FunctionType'
2027     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
2028     const QualType FnPtrArgType = FnPtrArg->getType();
2029     if (!FnPtrArgType->isPointerType()) {
2030       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2031           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
2032           << FnPtrArgType << "'int (*)(const char *, ...)'";
2033       return ExprError();
2034     }
2035 
2036     const auto *FuncType =
2037         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
2038 
2039     if (!FuncType) {
2040       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2041           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
2042           << FnPtrArgType << "'int (*)(const char *, ...)'";
2043       return ExprError();
2044     }
2045 
2046     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
2047       if (!FT->getNumParams()) {
2048         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2049             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
2050             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
2051         return ExprError();
2052       }
2053       QualType PT = FT->getParamType(0);
2054       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
2055           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
2056           !PT->getPointeeType().isConstQualified()) {
2057         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2058             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
2059             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
2060         return ExprError();
2061       }
2062     }
2063 
2064     TheCall->setType(Context.IntTy);
2065     break;
2066   }
2067   case Builtin::BI__builtin_expect_with_probability: {
2068     // We first want to ensure we are called with 3 arguments
2069     if (checkArgCount(*this, TheCall, 3))
2070       return ExprError();
2071     // then check probability is constant float in range [0.0, 1.0]
2072     const Expr *ProbArg = TheCall->getArg(2);
2073     SmallVector<PartialDiagnosticAt, 8> Notes;
2074     Expr::EvalResult Eval;
2075     Eval.Diag = &Notes;
2076     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
2077         !Eval.Val.isFloat()) {
2078       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
2079           << ProbArg->getSourceRange();
2080       for (const PartialDiagnosticAt &PDiag : Notes)
2081         Diag(PDiag.first, PDiag.second);
2082       return ExprError();
2083     }
2084     llvm::APFloat Probability = Eval.Val.getFloat();
2085     bool LoseInfo = false;
2086     Probability.convert(llvm::APFloat::IEEEdouble(),
2087                         llvm::RoundingMode::Dynamic, &LoseInfo);
2088     if (!(Probability >= llvm::APFloat(0.0) &&
2089           Probability <= llvm::APFloat(1.0))) {
2090       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
2091           << ProbArg->getSourceRange();
2092       return ExprError();
2093     }
2094     break;
2095   }
2096   case Builtin::BI__builtin_preserve_access_index:
2097     if (SemaBuiltinPreserveAI(*this, TheCall))
2098       return ExprError();
2099     break;
2100   case Builtin::BI__builtin_call_with_static_chain:
2101     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
2102       return ExprError();
2103     break;
2104   case Builtin::BI__exception_code:
2105   case Builtin::BI_exception_code:
2106     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
2107                                  diag::err_seh___except_block))
2108       return ExprError();
2109     break;
2110   case Builtin::BI__exception_info:
2111   case Builtin::BI_exception_info:
2112     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
2113                                  diag::err_seh___except_filter))
2114       return ExprError();
2115     break;
2116   case Builtin::BI__GetExceptionInfo:
2117     if (checkArgCount(*this, TheCall, 1))
2118       return ExprError();
2119 
2120     if (CheckCXXThrowOperand(
2121             TheCall->getBeginLoc(),
2122             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
2123             TheCall))
2124       return ExprError();
2125 
2126     TheCall->setType(Context.VoidPtrTy);
2127     break;
2128   // OpenCL v2.0, s6.13.16 - Pipe functions
2129   case Builtin::BIread_pipe:
2130   case Builtin::BIwrite_pipe:
2131     // Since those two functions are declared with var args, we need a semantic
2132     // check for the argument.
2133     if (SemaBuiltinRWPipe(*this, TheCall))
2134       return ExprError();
2135     break;
2136   case Builtin::BIreserve_read_pipe:
2137   case Builtin::BIreserve_write_pipe:
2138   case Builtin::BIwork_group_reserve_read_pipe:
2139   case Builtin::BIwork_group_reserve_write_pipe:
2140     if (SemaBuiltinReserveRWPipe(*this, TheCall))
2141       return ExprError();
2142     break;
2143   case Builtin::BIsub_group_reserve_read_pipe:
2144   case Builtin::BIsub_group_reserve_write_pipe:
2145     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2146         SemaBuiltinReserveRWPipe(*this, TheCall))
2147       return ExprError();
2148     break;
2149   case Builtin::BIcommit_read_pipe:
2150   case Builtin::BIcommit_write_pipe:
2151   case Builtin::BIwork_group_commit_read_pipe:
2152   case Builtin::BIwork_group_commit_write_pipe:
2153     if (SemaBuiltinCommitRWPipe(*this, TheCall))
2154       return ExprError();
2155     break;
2156   case Builtin::BIsub_group_commit_read_pipe:
2157   case Builtin::BIsub_group_commit_write_pipe:
2158     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2159         SemaBuiltinCommitRWPipe(*this, TheCall))
2160       return ExprError();
2161     break;
2162   case Builtin::BIget_pipe_num_packets:
2163   case Builtin::BIget_pipe_max_packets:
2164     if (SemaBuiltinPipePackets(*this, TheCall))
2165       return ExprError();
2166     break;
2167   case Builtin::BIto_global:
2168   case Builtin::BIto_local:
2169   case Builtin::BIto_private:
2170     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
2171       return ExprError();
2172     break;
2173   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
2174   case Builtin::BIenqueue_kernel:
2175     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
2176       return ExprError();
2177     break;
2178   case Builtin::BIget_kernel_work_group_size:
2179   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
2180     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
2181       return ExprError();
2182     break;
2183   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
2184   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
2185     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
2186       return ExprError();
2187     break;
2188   case Builtin::BI__builtin_os_log_format:
2189     Cleanup.setExprNeedsCleanups(true);
2190     LLVM_FALLTHROUGH;
2191   case Builtin::BI__builtin_os_log_format_buffer_size:
2192     if (SemaBuiltinOSLogFormat(TheCall))
2193       return ExprError();
2194     break;
2195   case Builtin::BI__builtin_frame_address:
2196   case Builtin::BI__builtin_return_address: {
2197     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
2198       return ExprError();
2199 
2200     // -Wframe-address warning if non-zero passed to builtin
2201     // return/frame address.
2202     Expr::EvalResult Result;
2203     if (!TheCall->getArg(0)->isValueDependent() &&
2204         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
2205         Result.Val.getInt() != 0)
2206       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
2207           << ((BuiltinID == Builtin::BI__builtin_return_address)
2208                   ? "__builtin_return_address"
2209                   : "__builtin_frame_address")
2210           << TheCall->getSourceRange();
2211     break;
2212   }
2213 
2214   // __builtin_elementwise_abs restricts the element type to signed integers or
2215   // floating point types only.
2216   case Builtin::BI__builtin_elementwise_abs: {
2217     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2218       return ExprError();
2219 
2220     QualType ArgTy = TheCall->getArg(0)->getType();
2221     QualType EltTy = ArgTy;
2222 
2223     if (auto *VecTy = EltTy->getAs<VectorType>())
2224       EltTy = VecTy->getElementType();
2225     if (EltTy->isUnsignedIntegerType()) {
2226       Diag(TheCall->getArg(0)->getBeginLoc(),
2227            diag::err_builtin_invalid_arg_type)
2228           << 1 << /* signed integer or float ty*/ 3 << ArgTy;
2229       return ExprError();
2230     }
2231     break;
2232   }
2233 
2234   // These builtins restrict the element type to floating point
2235   // types only.
2236   case Builtin::BI__builtin_elementwise_ceil:
2237   case Builtin::BI__builtin_elementwise_floor:
2238   case Builtin::BI__builtin_elementwise_roundeven:
2239   case Builtin::BI__builtin_elementwise_trunc: {
2240     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2241       return ExprError();
2242 
2243     QualType ArgTy = TheCall->getArg(0)->getType();
2244     QualType EltTy = ArgTy;
2245 
2246     if (auto *VecTy = EltTy->getAs<VectorType>())
2247       EltTy = VecTy->getElementType();
2248     if (!EltTy->isFloatingType()) {
2249       Diag(TheCall->getArg(0)->getBeginLoc(),
2250            diag::err_builtin_invalid_arg_type)
2251           << 1 << /* float ty*/ 5 << ArgTy;
2252 
2253       return ExprError();
2254     }
2255     break;
2256   }
2257 
2258   // These builtins restrict the element type to integer
2259   // types only.
2260   case Builtin::BI__builtin_elementwise_add_sat:
2261   case Builtin::BI__builtin_elementwise_sub_sat: {
2262     if (SemaBuiltinElementwiseMath(TheCall))
2263       return ExprError();
2264 
2265     const Expr *Arg = TheCall->getArg(0);
2266     QualType ArgTy = Arg->getType();
2267     QualType EltTy = ArgTy;
2268 
2269     if (auto *VecTy = EltTy->getAs<VectorType>())
2270       EltTy = VecTy->getElementType();
2271 
2272     if (!EltTy->isIntegerType()) {
2273       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2274           << 1 << /* integer ty */ 6 << ArgTy;
2275       return ExprError();
2276     }
2277     break;
2278   }
2279 
2280   case Builtin::BI__builtin_elementwise_min:
2281   case Builtin::BI__builtin_elementwise_max:
2282     if (SemaBuiltinElementwiseMath(TheCall))
2283       return ExprError();
2284     break;
2285   case Builtin::BI__builtin_reduce_max:
2286   case Builtin::BI__builtin_reduce_min: {
2287     if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2288       return ExprError();
2289 
2290     const Expr *Arg = TheCall->getArg(0);
2291     const auto *TyA = Arg->getType()->getAs<VectorType>();
2292     if (!TyA) {
2293       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2294           << 1 << /* vector ty*/ 4 << Arg->getType();
2295       return ExprError();
2296     }
2297 
2298     TheCall->setType(TyA->getElementType());
2299     break;
2300   }
2301 
2302   // These builtins support vectors of integers only.
2303   case Builtin::BI__builtin_reduce_xor:
2304   case Builtin::BI__builtin_reduce_or:
2305   case Builtin::BI__builtin_reduce_and: {
2306     if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2307       return ExprError();
2308 
2309     const Expr *Arg = TheCall->getArg(0);
2310     const auto *TyA = Arg->getType()->getAs<VectorType>();
2311     if (!TyA || !TyA->getElementType()->isIntegerType()) {
2312       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2313           << 1  << /* vector of integers */ 6 << Arg->getType();
2314       return ExprError();
2315     }
2316     TheCall->setType(TyA->getElementType());
2317     break;
2318   }
2319 
2320   case Builtin::BI__builtin_matrix_transpose:
2321     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
2322 
2323   case Builtin::BI__builtin_matrix_column_major_load:
2324     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
2325 
2326   case Builtin::BI__builtin_matrix_column_major_store:
2327     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
2328 
2329   case Builtin::BI__builtin_get_device_side_mangled_name: {
2330     auto Check = [](CallExpr *TheCall) {
2331       if (TheCall->getNumArgs() != 1)
2332         return false;
2333       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
2334       if (!DRE)
2335         return false;
2336       auto *D = DRE->getDecl();
2337       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
2338         return false;
2339       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
2340              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2341     };
2342     if (!Check(TheCall)) {
2343       Diag(TheCall->getBeginLoc(),
2344            diag::err_hip_invalid_args_builtin_mangled_name);
2345       return ExprError();
2346     }
2347   }
2348   }
2349 
2350   // Since the target specific builtins for each arch overlap, only check those
2351   // of the arch we are compiling for.
2352   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2353     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2354       assert(Context.getAuxTargetInfo() &&
2355              "Aux Target Builtin, but not an aux target?");
2356 
2357       if (CheckTSBuiltinFunctionCall(
2358               *Context.getAuxTargetInfo(),
2359               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2360         return ExprError();
2361     } else {
2362       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2363                                      TheCall))
2364         return ExprError();
2365     }
2366   }
2367 
2368   return TheCallResult;
2369 }
2370 
2371 // Get the valid immediate range for the specified NEON type code.
2372 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2373   NeonTypeFlags Type(t);
2374   int IsQuad = ForceQuad ? true : Type.isQuad();
2375   switch (Type.getEltType()) {
2376   case NeonTypeFlags::Int8:
2377   case NeonTypeFlags::Poly8:
2378     return shift ? 7 : (8 << IsQuad) - 1;
2379   case NeonTypeFlags::Int16:
2380   case NeonTypeFlags::Poly16:
2381     return shift ? 15 : (4 << IsQuad) - 1;
2382   case NeonTypeFlags::Int32:
2383     return shift ? 31 : (2 << IsQuad) - 1;
2384   case NeonTypeFlags::Int64:
2385   case NeonTypeFlags::Poly64:
2386     return shift ? 63 : (1 << IsQuad) - 1;
2387   case NeonTypeFlags::Poly128:
2388     return shift ? 127 : (1 << IsQuad) - 1;
2389   case NeonTypeFlags::Float16:
2390     assert(!shift && "cannot shift float types!");
2391     return (4 << IsQuad) - 1;
2392   case NeonTypeFlags::Float32:
2393     assert(!shift && "cannot shift float types!");
2394     return (2 << IsQuad) - 1;
2395   case NeonTypeFlags::Float64:
2396     assert(!shift && "cannot shift float types!");
2397     return (1 << IsQuad) - 1;
2398   case NeonTypeFlags::BFloat16:
2399     assert(!shift && "cannot shift float types!");
2400     return (4 << IsQuad) - 1;
2401   }
2402   llvm_unreachable("Invalid NeonTypeFlag!");
2403 }
2404 
2405 /// getNeonEltType - Return the QualType corresponding to the elements of
2406 /// the vector type specified by the NeonTypeFlags.  This is used to check
2407 /// the pointer arguments for Neon load/store intrinsics.
2408 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2409                                bool IsPolyUnsigned, bool IsInt64Long) {
2410   switch (Flags.getEltType()) {
2411   case NeonTypeFlags::Int8:
2412     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2413   case NeonTypeFlags::Int16:
2414     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2415   case NeonTypeFlags::Int32:
2416     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2417   case NeonTypeFlags::Int64:
2418     if (IsInt64Long)
2419       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2420     else
2421       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2422                                 : Context.LongLongTy;
2423   case NeonTypeFlags::Poly8:
2424     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2425   case NeonTypeFlags::Poly16:
2426     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2427   case NeonTypeFlags::Poly64:
2428     if (IsInt64Long)
2429       return Context.UnsignedLongTy;
2430     else
2431       return Context.UnsignedLongLongTy;
2432   case NeonTypeFlags::Poly128:
2433     break;
2434   case NeonTypeFlags::Float16:
2435     return Context.HalfTy;
2436   case NeonTypeFlags::Float32:
2437     return Context.FloatTy;
2438   case NeonTypeFlags::Float64:
2439     return Context.DoubleTy;
2440   case NeonTypeFlags::BFloat16:
2441     return Context.BFloat16Ty;
2442   }
2443   llvm_unreachable("Invalid NeonTypeFlag!");
2444 }
2445 
2446 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2447   // Range check SVE intrinsics that take immediate values.
2448   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2449 
2450   switch (BuiltinID) {
2451   default:
2452     return false;
2453 #define GET_SVE_IMMEDIATE_CHECK
2454 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2455 #undef GET_SVE_IMMEDIATE_CHECK
2456   }
2457 
2458   // Perform all the immediate checks for this builtin call.
2459   bool HasError = false;
2460   for (auto &I : ImmChecks) {
2461     int ArgNum, CheckTy, ElementSizeInBits;
2462     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2463 
2464     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2465 
2466     // Function that checks whether the operand (ArgNum) is an immediate
2467     // that is one of the predefined values.
2468     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2469                                    int ErrDiag) -> bool {
2470       // We can't check the value of a dependent argument.
2471       Expr *Arg = TheCall->getArg(ArgNum);
2472       if (Arg->isTypeDependent() || Arg->isValueDependent())
2473         return false;
2474 
2475       // Check constant-ness first.
2476       llvm::APSInt Imm;
2477       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2478         return true;
2479 
2480       if (!CheckImm(Imm.getSExtValue()))
2481         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2482       return false;
2483     };
2484 
2485     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2486     case SVETypeFlags::ImmCheck0_31:
2487       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2488         HasError = true;
2489       break;
2490     case SVETypeFlags::ImmCheck0_13:
2491       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2492         HasError = true;
2493       break;
2494     case SVETypeFlags::ImmCheck1_16:
2495       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2496         HasError = true;
2497       break;
2498     case SVETypeFlags::ImmCheck0_7:
2499       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2500         HasError = true;
2501       break;
2502     case SVETypeFlags::ImmCheckExtract:
2503       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2504                                       (2048 / ElementSizeInBits) - 1))
2505         HasError = true;
2506       break;
2507     case SVETypeFlags::ImmCheckShiftRight:
2508       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2509         HasError = true;
2510       break;
2511     case SVETypeFlags::ImmCheckShiftRightNarrow:
2512       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2513                                       ElementSizeInBits / 2))
2514         HasError = true;
2515       break;
2516     case SVETypeFlags::ImmCheckShiftLeft:
2517       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2518                                       ElementSizeInBits - 1))
2519         HasError = true;
2520       break;
2521     case SVETypeFlags::ImmCheckLaneIndex:
2522       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2523                                       (128 / (1 * ElementSizeInBits)) - 1))
2524         HasError = true;
2525       break;
2526     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2527       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2528                                       (128 / (2 * ElementSizeInBits)) - 1))
2529         HasError = true;
2530       break;
2531     case SVETypeFlags::ImmCheckLaneIndexDot:
2532       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2533                                       (128 / (4 * ElementSizeInBits)) - 1))
2534         HasError = true;
2535       break;
2536     case SVETypeFlags::ImmCheckComplexRot90_270:
2537       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2538                               diag::err_rotation_argument_to_cadd))
2539         HasError = true;
2540       break;
2541     case SVETypeFlags::ImmCheckComplexRotAll90:
2542       if (CheckImmediateInSet(
2543               [](int64_t V) {
2544                 return V == 0 || V == 90 || V == 180 || V == 270;
2545               },
2546               diag::err_rotation_argument_to_cmla))
2547         HasError = true;
2548       break;
2549     case SVETypeFlags::ImmCheck0_1:
2550       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2551         HasError = true;
2552       break;
2553     case SVETypeFlags::ImmCheck0_2:
2554       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2555         HasError = true;
2556       break;
2557     case SVETypeFlags::ImmCheck0_3:
2558       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2559         HasError = true;
2560       break;
2561     }
2562   }
2563 
2564   return HasError;
2565 }
2566 
2567 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2568                                         unsigned BuiltinID, CallExpr *TheCall) {
2569   llvm::APSInt Result;
2570   uint64_t mask = 0;
2571   unsigned TV = 0;
2572   int PtrArgNum = -1;
2573   bool HasConstPtr = false;
2574   switch (BuiltinID) {
2575 #define GET_NEON_OVERLOAD_CHECK
2576 #include "clang/Basic/arm_neon.inc"
2577 #include "clang/Basic/arm_fp16.inc"
2578 #undef GET_NEON_OVERLOAD_CHECK
2579   }
2580 
2581   // For NEON intrinsics which are overloaded on vector element type, validate
2582   // the immediate which specifies which variant to emit.
2583   unsigned ImmArg = TheCall->getNumArgs()-1;
2584   if (mask) {
2585     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2586       return true;
2587 
2588     TV = Result.getLimitedValue(64);
2589     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2590       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2591              << TheCall->getArg(ImmArg)->getSourceRange();
2592   }
2593 
2594   if (PtrArgNum >= 0) {
2595     // Check that pointer arguments have the specified type.
2596     Expr *Arg = TheCall->getArg(PtrArgNum);
2597     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2598       Arg = ICE->getSubExpr();
2599     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2600     QualType RHSTy = RHS.get()->getType();
2601 
2602     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2603     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2604                           Arch == llvm::Triple::aarch64_32 ||
2605                           Arch == llvm::Triple::aarch64_be;
2606     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2607     QualType EltTy =
2608         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2609     if (HasConstPtr)
2610       EltTy = EltTy.withConst();
2611     QualType LHSTy = Context.getPointerType(EltTy);
2612     AssignConvertType ConvTy;
2613     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2614     if (RHS.isInvalid())
2615       return true;
2616     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2617                                  RHS.get(), AA_Assigning))
2618       return true;
2619   }
2620 
2621   // For NEON intrinsics which take an immediate value as part of the
2622   // instruction, range check them here.
2623   unsigned i = 0, l = 0, u = 0;
2624   switch (BuiltinID) {
2625   default:
2626     return false;
2627   #define GET_NEON_IMMEDIATE_CHECK
2628   #include "clang/Basic/arm_neon.inc"
2629   #include "clang/Basic/arm_fp16.inc"
2630   #undef GET_NEON_IMMEDIATE_CHECK
2631   }
2632 
2633   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2634 }
2635 
2636 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2637   switch (BuiltinID) {
2638   default:
2639     return false;
2640   #include "clang/Basic/arm_mve_builtin_sema.inc"
2641   }
2642 }
2643 
2644 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2645                                        CallExpr *TheCall) {
2646   bool Err = false;
2647   switch (BuiltinID) {
2648   default:
2649     return false;
2650 #include "clang/Basic/arm_cde_builtin_sema.inc"
2651   }
2652 
2653   if (Err)
2654     return true;
2655 
2656   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2657 }
2658 
2659 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2660                                         const Expr *CoprocArg, bool WantCDE) {
2661   if (isConstantEvaluated())
2662     return false;
2663 
2664   // We can't check the value of a dependent argument.
2665   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2666     return false;
2667 
2668   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2669   int64_t CoprocNo = CoprocNoAP.getExtValue();
2670   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2671 
2672   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2673   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2674 
2675   if (IsCDECoproc != WantCDE)
2676     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2677            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2678 
2679   return false;
2680 }
2681 
2682 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2683                                         unsigned MaxWidth) {
2684   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2685           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2686           BuiltinID == ARM::BI__builtin_arm_strex ||
2687           BuiltinID == ARM::BI__builtin_arm_stlex ||
2688           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2689           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2690           BuiltinID == AArch64::BI__builtin_arm_strex ||
2691           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2692          "unexpected ARM builtin");
2693   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2694                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2695                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2696                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2697 
2698   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2699 
2700   // Ensure that we have the proper number of arguments.
2701   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2702     return true;
2703 
2704   // Inspect the pointer argument of the atomic builtin.  This should always be
2705   // a pointer type, whose element is an integral scalar or pointer type.
2706   // Because it is a pointer type, we don't have to worry about any implicit
2707   // casts here.
2708   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2709   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2710   if (PointerArgRes.isInvalid())
2711     return true;
2712   PointerArg = PointerArgRes.get();
2713 
2714   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2715   if (!pointerType) {
2716     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2717         << PointerArg->getType() << PointerArg->getSourceRange();
2718     return true;
2719   }
2720 
2721   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2722   // task is to insert the appropriate casts into the AST. First work out just
2723   // what the appropriate type is.
2724   QualType ValType = pointerType->getPointeeType();
2725   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2726   if (IsLdrex)
2727     AddrType.addConst();
2728 
2729   // Issue a warning if the cast is dodgy.
2730   CastKind CastNeeded = CK_NoOp;
2731   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2732     CastNeeded = CK_BitCast;
2733     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2734         << PointerArg->getType() << Context.getPointerType(AddrType)
2735         << AA_Passing << PointerArg->getSourceRange();
2736   }
2737 
2738   // Finally, do the cast and replace the argument with the corrected version.
2739   AddrType = Context.getPointerType(AddrType);
2740   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2741   if (PointerArgRes.isInvalid())
2742     return true;
2743   PointerArg = PointerArgRes.get();
2744 
2745   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2746 
2747   // In general, we allow ints, floats and pointers to be loaded and stored.
2748   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2749       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2750     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2751         << PointerArg->getType() << PointerArg->getSourceRange();
2752     return true;
2753   }
2754 
2755   // But ARM doesn't have instructions to deal with 128-bit versions.
2756   if (Context.getTypeSize(ValType) > MaxWidth) {
2757     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2758     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2759         << PointerArg->getType() << PointerArg->getSourceRange();
2760     return true;
2761   }
2762 
2763   switch (ValType.getObjCLifetime()) {
2764   case Qualifiers::OCL_None:
2765   case Qualifiers::OCL_ExplicitNone:
2766     // okay
2767     break;
2768 
2769   case Qualifiers::OCL_Weak:
2770   case Qualifiers::OCL_Strong:
2771   case Qualifiers::OCL_Autoreleasing:
2772     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2773         << ValType << PointerArg->getSourceRange();
2774     return true;
2775   }
2776 
2777   if (IsLdrex) {
2778     TheCall->setType(ValType);
2779     return false;
2780   }
2781 
2782   // Initialize the argument to be stored.
2783   ExprResult ValArg = TheCall->getArg(0);
2784   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2785       Context, ValType, /*consume*/ false);
2786   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2787   if (ValArg.isInvalid())
2788     return true;
2789   TheCall->setArg(0, ValArg.get());
2790 
2791   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2792   // but the custom checker bypasses all default analysis.
2793   TheCall->setType(Context.IntTy);
2794   return false;
2795 }
2796 
2797 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2798                                        CallExpr *TheCall) {
2799   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2800       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2801       BuiltinID == ARM::BI__builtin_arm_strex ||
2802       BuiltinID == ARM::BI__builtin_arm_stlex) {
2803     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2804   }
2805 
2806   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2807     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2808       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2809   }
2810 
2811   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2812       BuiltinID == ARM::BI__builtin_arm_wsr64)
2813     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2814 
2815   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2816       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2817       BuiltinID == ARM::BI__builtin_arm_wsr ||
2818       BuiltinID == ARM::BI__builtin_arm_wsrp)
2819     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2820 
2821   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2822     return true;
2823   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2824     return true;
2825   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2826     return true;
2827 
2828   // For intrinsics which take an immediate value as part of the instruction,
2829   // range check them here.
2830   // FIXME: VFP Intrinsics should error if VFP not present.
2831   switch (BuiltinID) {
2832   default: return false;
2833   case ARM::BI__builtin_arm_ssat:
2834     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2835   case ARM::BI__builtin_arm_usat:
2836     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2837   case ARM::BI__builtin_arm_ssat16:
2838     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2839   case ARM::BI__builtin_arm_usat16:
2840     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2841   case ARM::BI__builtin_arm_vcvtr_f:
2842   case ARM::BI__builtin_arm_vcvtr_d:
2843     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2844   case ARM::BI__builtin_arm_dmb:
2845   case ARM::BI__builtin_arm_dsb:
2846   case ARM::BI__builtin_arm_isb:
2847   case ARM::BI__builtin_arm_dbg:
2848     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2849   case ARM::BI__builtin_arm_cdp:
2850   case ARM::BI__builtin_arm_cdp2:
2851   case ARM::BI__builtin_arm_mcr:
2852   case ARM::BI__builtin_arm_mcr2:
2853   case ARM::BI__builtin_arm_mrc:
2854   case ARM::BI__builtin_arm_mrc2:
2855   case ARM::BI__builtin_arm_mcrr:
2856   case ARM::BI__builtin_arm_mcrr2:
2857   case ARM::BI__builtin_arm_mrrc:
2858   case ARM::BI__builtin_arm_mrrc2:
2859   case ARM::BI__builtin_arm_ldc:
2860   case ARM::BI__builtin_arm_ldcl:
2861   case ARM::BI__builtin_arm_ldc2:
2862   case ARM::BI__builtin_arm_ldc2l:
2863   case ARM::BI__builtin_arm_stc:
2864   case ARM::BI__builtin_arm_stcl:
2865   case ARM::BI__builtin_arm_stc2:
2866   case ARM::BI__builtin_arm_stc2l:
2867     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2868            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2869                                         /*WantCDE*/ false);
2870   }
2871 }
2872 
2873 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2874                                            unsigned BuiltinID,
2875                                            CallExpr *TheCall) {
2876   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2877       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2878       BuiltinID == AArch64::BI__builtin_arm_strex ||
2879       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2880     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2881   }
2882 
2883   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2884     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2885       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2886       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2887       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2888   }
2889 
2890   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2891       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2892     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2893 
2894   // Memory Tagging Extensions (MTE) Intrinsics
2895   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2896       BuiltinID == AArch64::BI__builtin_arm_addg ||
2897       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2898       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2899       BuiltinID == AArch64::BI__builtin_arm_stg ||
2900       BuiltinID == AArch64::BI__builtin_arm_subp) {
2901     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2902   }
2903 
2904   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2905       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2906       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2907       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2908     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2909 
2910   // Only check the valid encoding range. Any constant in this range would be
2911   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2912   // an exception for incorrect registers. This matches MSVC behavior.
2913   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2914       BuiltinID == AArch64::BI_WriteStatusReg)
2915     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2916 
2917   if (BuiltinID == AArch64::BI__getReg)
2918     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2919 
2920   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2921     return true;
2922 
2923   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2924     return true;
2925 
2926   // For intrinsics which take an immediate value as part of the instruction,
2927   // range check them here.
2928   unsigned i = 0, l = 0, u = 0;
2929   switch (BuiltinID) {
2930   default: return false;
2931   case AArch64::BI__builtin_arm_dmb:
2932   case AArch64::BI__builtin_arm_dsb:
2933   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2934   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2935   }
2936 
2937   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2938 }
2939 
2940 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2941   if (Arg->getType()->getAsPlaceholderType())
2942     return false;
2943 
2944   // The first argument needs to be a record field access.
2945   // If it is an array element access, we delay decision
2946   // to BPF backend to check whether the access is a
2947   // field access or not.
2948   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2949           isa<MemberExpr>(Arg->IgnoreParens()) ||
2950           isa<ArraySubscriptExpr>(Arg->IgnoreParens()));
2951 }
2952 
2953 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2954                             QualType VectorTy, QualType EltTy) {
2955   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2956   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2957     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2958         << Call->getSourceRange() << VectorEltTy << EltTy;
2959     return false;
2960   }
2961   return true;
2962 }
2963 
2964 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2965   QualType ArgType = Arg->getType();
2966   if (ArgType->getAsPlaceholderType())
2967     return false;
2968 
2969   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2970   // format:
2971   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2972   //   2. <type> var;
2973   //      __builtin_preserve_type_info(var, flag);
2974   if (!isa<DeclRefExpr>(Arg->IgnoreParens()) &&
2975       !isa<UnaryOperator>(Arg->IgnoreParens()))
2976     return false;
2977 
2978   // Typedef type.
2979   if (ArgType->getAs<TypedefType>())
2980     return true;
2981 
2982   // Record type or Enum type.
2983   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2984   if (const auto *RT = Ty->getAs<RecordType>()) {
2985     if (!RT->getDecl()->getDeclName().isEmpty())
2986       return true;
2987   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2988     if (!ET->getDecl()->getDeclName().isEmpty())
2989       return true;
2990   }
2991 
2992   return false;
2993 }
2994 
2995 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2996   QualType ArgType = Arg->getType();
2997   if (ArgType->getAsPlaceholderType())
2998     return false;
2999 
3000   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
3001   // format:
3002   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
3003   //                                 flag);
3004   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
3005   if (!UO)
3006     return false;
3007 
3008   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
3009   if (!CE)
3010     return false;
3011   if (CE->getCastKind() != CK_IntegralToPointer &&
3012       CE->getCastKind() != CK_NullToPointer)
3013     return false;
3014 
3015   // The integer must be from an EnumConstantDecl.
3016   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
3017   if (!DR)
3018     return false;
3019 
3020   const EnumConstantDecl *Enumerator =
3021       dyn_cast<EnumConstantDecl>(DR->getDecl());
3022   if (!Enumerator)
3023     return false;
3024 
3025   // The type must be EnumType.
3026   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
3027   const auto *ET = Ty->getAs<EnumType>();
3028   if (!ET)
3029     return false;
3030 
3031   // The enum value must be supported.
3032   return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
3033 }
3034 
3035 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
3036                                        CallExpr *TheCall) {
3037   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
3038           BuiltinID == BPF::BI__builtin_btf_type_id ||
3039           BuiltinID == BPF::BI__builtin_preserve_type_info ||
3040           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
3041          "unexpected BPF builtin");
3042 
3043   if (checkArgCount(*this, TheCall, 2))
3044     return true;
3045 
3046   // The second argument needs to be a constant int
3047   Expr *Arg = TheCall->getArg(1);
3048   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
3049   diag::kind kind;
3050   if (!Value) {
3051     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
3052       kind = diag::err_preserve_field_info_not_const;
3053     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
3054       kind = diag::err_btf_type_id_not_const;
3055     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
3056       kind = diag::err_preserve_type_info_not_const;
3057     else
3058       kind = diag::err_preserve_enum_value_not_const;
3059     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
3060     return true;
3061   }
3062 
3063   // The first argument
3064   Arg = TheCall->getArg(0);
3065   bool InvalidArg = false;
3066   bool ReturnUnsignedInt = true;
3067   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
3068     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
3069       InvalidArg = true;
3070       kind = diag::err_preserve_field_info_not_field;
3071     }
3072   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
3073     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
3074       InvalidArg = true;
3075       kind = diag::err_preserve_type_info_invalid;
3076     }
3077   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
3078     if (!isValidBPFPreserveEnumValueArg(Arg)) {
3079       InvalidArg = true;
3080       kind = diag::err_preserve_enum_value_invalid;
3081     }
3082     ReturnUnsignedInt = false;
3083   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
3084     ReturnUnsignedInt = false;
3085   }
3086 
3087   if (InvalidArg) {
3088     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
3089     return true;
3090   }
3091 
3092   if (ReturnUnsignedInt)
3093     TheCall->setType(Context.UnsignedIntTy);
3094   else
3095     TheCall->setType(Context.UnsignedLongTy);
3096   return false;
3097 }
3098 
3099 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3100   struct ArgInfo {
3101     uint8_t OpNum;
3102     bool IsSigned;
3103     uint8_t BitWidth;
3104     uint8_t Align;
3105   };
3106   struct BuiltinInfo {
3107     unsigned BuiltinID;
3108     ArgInfo Infos[2];
3109   };
3110 
3111   static BuiltinInfo Infos[] = {
3112     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
3113     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
3114     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
3115     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
3116     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
3117     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
3118     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
3119     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
3120     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
3121     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
3122     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
3123 
3124     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
3125     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
3126     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
3127     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
3128     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
3129     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
3130     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
3131     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
3132     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
3133     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
3134     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
3135 
3136     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
3137     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
3138     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
3139     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
3140     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
3141     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
3142     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
3143     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
3144     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
3145     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
3146     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
3147     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
3148     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
3149     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
3150     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
3151     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
3152     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
3153     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
3154     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
3155     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
3156     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
3157     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
3158     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
3159     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
3160     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
3161     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
3162     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
3163     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
3164     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
3165     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
3166     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
3167     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
3168     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
3169     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
3170     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
3171     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
3172     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
3173     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
3174     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
3175     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
3176     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
3177     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
3178     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
3179     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
3180     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
3181     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
3182     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
3183     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
3184     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
3185     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
3186     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
3187     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
3188                                                       {{ 1, false, 6,  0 }} },
3189     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
3190     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
3191     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
3192     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
3193     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
3194     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
3195     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
3196                                                       {{ 1, false, 5,  0 }} },
3197     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
3198     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
3199     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
3200     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
3201     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
3202     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
3203                                                        { 2, false, 5,  0 }} },
3204     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
3205                                                        { 2, false, 6,  0 }} },
3206     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
3207                                                        { 3, false, 5,  0 }} },
3208     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
3209                                                        { 3, false, 6,  0 }} },
3210     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
3211     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
3212     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
3213     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
3214     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
3215     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
3216     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
3217     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
3218     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
3219     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
3220     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
3221     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
3222     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
3223     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
3224     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
3225     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
3226                                                       {{ 2, false, 4,  0 },
3227                                                        { 3, false, 5,  0 }} },
3228     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
3229                                                       {{ 2, false, 4,  0 },
3230                                                        { 3, false, 5,  0 }} },
3231     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
3232                                                       {{ 2, false, 4,  0 },
3233                                                        { 3, false, 5,  0 }} },
3234     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
3235                                                       {{ 2, false, 4,  0 },
3236                                                        { 3, false, 5,  0 }} },
3237     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
3238     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
3239     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
3240     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
3241     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
3242     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
3243     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
3244     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
3245     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
3246     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
3247     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
3248                                                        { 2, false, 5,  0 }} },
3249     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
3250                                                        { 2, false, 6,  0 }} },
3251     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
3252     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
3253     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
3254     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
3255     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
3256     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
3257     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
3258     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
3259     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
3260                                                       {{ 1, false, 4,  0 }} },
3261     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
3262     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
3263                                                       {{ 1, false, 4,  0 }} },
3264     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
3265     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
3266     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
3267     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
3268     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
3269     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
3270     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
3271     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
3272     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
3273     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
3274     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
3275     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
3276     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
3277     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
3278     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
3279     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
3280     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
3281     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
3282     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
3283     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
3284                                                       {{ 3, false, 1,  0 }} },
3285     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
3286     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
3287     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
3288     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
3289                                                       {{ 3, false, 1,  0 }} },
3290     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
3291     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
3292     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
3293     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
3294                                                       {{ 3, false, 1,  0 }} },
3295   };
3296 
3297   // Use a dynamically initialized static to sort the table exactly once on
3298   // first run.
3299   static const bool SortOnce =
3300       (llvm::sort(Infos,
3301                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
3302                    return LHS.BuiltinID < RHS.BuiltinID;
3303                  }),
3304        true);
3305   (void)SortOnce;
3306 
3307   const BuiltinInfo *F = llvm::partition_point(
3308       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
3309   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
3310     return false;
3311 
3312   bool Error = false;
3313 
3314   for (const ArgInfo &A : F->Infos) {
3315     // Ignore empty ArgInfo elements.
3316     if (A.BitWidth == 0)
3317       continue;
3318 
3319     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
3320     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
3321     if (!A.Align) {
3322       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3323     } else {
3324       unsigned M = 1 << A.Align;
3325       Min *= M;
3326       Max *= M;
3327       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3328       Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
3329     }
3330   }
3331   return Error;
3332 }
3333 
3334 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
3335                                            CallExpr *TheCall) {
3336   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3337 }
3338 
3339 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
3340                                         unsigned BuiltinID, CallExpr *TheCall) {
3341   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
3342          CheckMipsBuiltinArgument(BuiltinID, TheCall);
3343 }
3344 
3345 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
3346                                CallExpr *TheCall) {
3347 
3348   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3349       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3350     if (!TI.hasFeature("dsp"))
3351       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3352   }
3353 
3354   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3355       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3356     if (!TI.hasFeature("dspr2"))
3357       return Diag(TheCall->getBeginLoc(),
3358                   diag::err_mips_builtin_requires_dspr2);
3359   }
3360 
3361   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3362       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3363     if (!TI.hasFeature("msa"))
3364       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3365   }
3366 
3367   return false;
3368 }
3369 
3370 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3371 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3372 // ordering for DSP is unspecified. MSA is ordered by the data format used
3373 // by the underlying instruction i.e., df/m, df/n and then by size.
3374 //
3375 // FIXME: The size tests here should instead be tablegen'd along with the
3376 //        definitions from include/clang/Basic/BuiltinsMips.def.
3377 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3378 //        be too.
3379 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3380   unsigned i = 0, l = 0, u = 0, m = 0;
3381   switch (BuiltinID) {
3382   default: return false;
3383   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3384   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3385   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3386   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3387   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3388   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3389   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3390   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3391   // df/m field.
3392   // These intrinsics take an unsigned 3 bit immediate.
3393   case Mips::BI__builtin_msa_bclri_b:
3394   case Mips::BI__builtin_msa_bnegi_b:
3395   case Mips::BI__builtin_msa_bseti_b:
3396   case Mips::BI__builtin_msa_sat_s_b:
3397   case Mips::BI__builtin_msa_sat_u_b:
3398   case Mips::BI__builtin_msa_slli_b:
3399   case Mips::BI__builtin_msa_srai_b:
3400   case Mips::BI__builtin_msa_srari_b:
3401   case Mips::BI__builtin_msa_srli_b:
3402   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3403   case Mips::BI__builtin_msa_binsli_b:
3404   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3405   // These intrinsics take an unsigned 4 bit immediate.
3406   case Mips::BI__builtin_msa_bclri_h:
3407   case Mips::BI__builtin_msa_bnegi_h:
3408   case Mips::BI__builtin_msa_bseti_h:
3409   case Mips::BI__builtin_msa_sat_s_h:
3410   case Mips::BI__builtin_msa_sat_u_h:
3411   case Mips::BI__builtin_msa_slli_h:
3412   case Mips::BI__builtin_msa_srai_h:
3413   case Mips::BI__builtin_msa_srari_h:
3414   case Mips::BI__builtin_msa_srli_h:
3415   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3416   case Mips::BI__builtin_msa_binsli_h:
3417   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3418   // These intrinsics take an unsigned 5 bit immediate.
3419   // The first block of intrinsics actually have an unsigned 5 bit field,
3420   // not a df/n field.
3421   case Mips::BI__builtin_msa_cfcmsa:
3422   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3423   case Mips::BI__builtin_msa_clei_u_b:
3424   case Mips::BI__builtin_msa_clei_u_h:
3425   case Mips::BI__builtin_msa_clei_u_w:
3426   case Mips::BI__builtin_msa_clei_u_d:
3427   case Mips::BI__builtin_msa_clti_u_b:
3428   case Mips::BI__builtin_msa_clti_u_h:
3429   case Mips::BI__builtin_msa_clti_u_w:
3430   case Mips::BI__builtin_msa_clti_u_d:
3431   case Mips::BI__builtin_msa_maxi_u_b:
3432   case Mips::BI__builtin_msa_maxi_u_h:
3433   case Mips::BI__builtin_msa_maxi_u_w:
3434   case Mips::BI__builtin_msa_maxi_u_d:
3435   case Mips::BI__builtin_msa_mini_u_b:
3436   case Mips::BI__builtin_msa_mini_u_h:
3437   case Mips::BI__builtin_msa_mini_u_w:
3438   case Mips::BI__builtin_msa_mini_u_d:
3439   case Mips::BI__builtin_msa_addvi_b:
3440   case Mips::BI__builtin_msa_addvi_h:
3441   case Mips::BI__builtin_msa_addvi_w:
3442   case Mips::BI__builtin_msa_addvi_d:
3443   case Mips::BI__builtin_msa_bclri_w:
3444   case Mips::BI__builtin_msa_bnegi_w:
3445   case Mips::BI__builtin_msa_bseti_w:
3446   case Mips::BI__builtin_msa_sat_s_w:
3447   case Mips::BI__builtin_msa_sat_u_w:
3448   case Mips::BI__builtin_msa_slli_w:
3449   case Mips::BI__builtin_msa_srai_w:
3450   case Mips::BI__builtin_msa_srari_w:
3451   case Mips::BI__builtin_msa_srli_w:
3452   case Mips::BI__builtin_msa_srlri_w:
3453   case Mips::BI__builtin_msa_subvi_b:
3454   case Mips::BI__builtin_msa_subvi_h:
3455   case Mips::BI__builtin_msa_subvi_w:
3456   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3457   case Mips::BI__builtin_msa_binsli_w:
3458   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3459   // These intrinsics take an unsigned 6 bit immediate.
3460   case Mips::BI__builtin_msa_bclri_d:
3461   case Mips::BI__builtin_msa_bnegi_d:
3462   case Mips::BI__builtin_msa_bseti_d:
3463   case Mips::BI__builtin_msa_sat_s_d:
3464   case Mips::BI__builtin_msa_sat_u_d:
3465   case Mips::BI__builtin_msa_slli_d:
3466   case Mips::BI__builtin_msa_srai_d:
3467   case Mips::BI__builtin_msa_srari_d:
3468   case Mips::BI__builtin_msa_srli_d:
3469   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3470   case Mips::BI__builtin_msa_binsli_d:
3471   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3472   // These intrinsics take a signed 5 bit immediate.
3473   case Mips::BI__builtin_msa_ceqi_b:
3474   case Mips::BI__builtin_msa_ceqi_h:
3475   case Mips::BI__builtin_msa_ceqi_w:
3476   case Mips::BI__builtin_msa_ceqi_d:
3477   case Mips::BI__builtin_msa_clti_s_b:
3478   case Mips::BI__builtin_msa_clti_s_h:
3479   case Mips::BI__builtin_msa_clti_s_w:
3480   case Mips::BI__builtin_msa_clti_s_d:
3481   case Mips::BI__builtin_msa_clei_s_b:
3482   case Mips::BI__builtin_msa_clei_s_h:
3483   case Mips::BI__builtin_msa_clei_s_w:
3484   case Mips::BI__builtin_msa_clei_s_d:
3485   case Mips::BI__builtin_msa_maxi_s_b:
3486   case Mips::BI__builtin_msa_maxi_s_h:
3487   case Mips::BI__builtin_msa_maxi_s_w:
3488   case Mips::BI__builtin_msa_maxi_s_d:
3489   case Mips::BI__builtin_msa_mini_s_b:
3490   case Mips::BI__builtin_msa_mini_s_h:
3491   case Mips::BI__builtin_msa_mini_s_w:
3492   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3493   // These intrinsics take an unsigned 8 bit immediate.
3494   case Mips::BI__builtin_msa_andi_b:
3495   case Mips::BI__builtin_msa_nori_b:
3496   case Mips::BI__builtin_msa_ori_b:
3497   case Mips::BI__builtin_msa_shf_b:
3498   case Mips::BI__builtin_msa_shf_h:
3499   case Mips::BI__builtin_msa_shf_w:
3500   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3501   case Mips::BI__builtin_msa_bseli_b:
3502   case Mips::BI__builtin_msa_bmnzi_b:
3503   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3504   // df/n format
3505   // These intrinsics take an unsigned 4 bit immediate.
3506   case Mips::BI__builtin_msa_copy_s_b:
3507   case Mips::BI__builtin_msa_copy_u_b:
3508   case Mips::BI__builtin_msa_insve_b:
3509   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3510   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3511   // These intrinsics take an unsigned 3 bit immediate.
3512   case Mips::BI__builtin_msa_copy_s_h:
3513   case Mips::BI__builtin_msa_copy_u_h:
3514   case Mips::BI__builtin_msa_insve_h:
3515   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3516   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3517   // These intrinsics take an unsigned 2 bit immediate.
3518   case Mips::BI__builtin_msa_copy_s_w:
3519   case Mips::BI__builtin_msa_copy_u_w:
3520   case Mips::BI__builtin_msa_insve_w:
3521   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3522   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3523   // These intrinsics take an unsigned 1 bit immediate.
3524   case Mips::BI__builtin_msa_copy_s_d:
3525   case Mips::BI__builtin_msa_copy_u_d:
3526   case Mips::BI__builtin_msa_insve_d:
3527   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3528   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3529   // Memory offsets and immediate loads.
3530   // These intrinsics take a signed 10 bit immediate.
3531   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3532   case Mips::BI__builtin_msa_ldi_h:
3533   case Mips::BI__builtin_msa_ldi_w:
3534   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3535   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3536   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3537   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3538   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3539   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3540   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3541   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3542   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3543   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3544   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3545   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3546   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3547   }
3548 
3549   if (!m)
3550     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3551 
3552   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3553          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3554 }
3555 
3556 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3557 /// advancing the pointer over the consumed characters. The decoded type is
3558 /// returned. If the decoded type represents a constant integer with a
3559 /// constraint on its value then Mask is set to that value. The type descriptors
3560 /// used in Str are specific to PPC MMA builtins and are documented in the file
3561 /// defining the PPC builtins.
3562 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3563                                         unsigned &Mask) {
3564   bool RequireICE = false;
3565   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3566   switch (*Str++) {
3567   case 'V':
3568     return Context.getVectorType(Context.UnsignedCharTy, 16,
3569                                  VectorType::VectorKind::AltiVecVector);
3570   case 'i': {
3571     char *End;
3572     unsigned size = strtoul(Str, &End, 10);
3573     assert(End != Str && "Missing constant parameter constraint");
3574     Str = End;
3575     Mask = size;
3576     return Context.IntTy;
3577   }
3578   case 'W': {
3579     char *End;
3580     unsigned size = strtoul(Str, &End, 10);
3581     assert(End != Str && "Missing PowerPC MMA type size");
3582     Str = End;
3583     QualType Type;
3584     switch (size) {
3585   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3586     case size: Type = Context.Id##Ty; break;
3587   #include "clang/Basic/PPCTypes.def"
3588     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3589     }
3590     bool CheckVectorArgs = false;
3591     while (!CheckVectorArgs) {
3592       switch (*Str++) {
3593       case '*':
3594         Type = Context.getPointerType(Type);
3595         break;
3596       case 'C':
3597         Type = Type.withConst();
3598         break;
3599       default:
3600         CheckVectorArgs = true;
3601         --Str;
3602         break;
3603       }
3604     }
3605     return Type;
3606   }
3607   default:
3608     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3609   }
3610 }
3611 
3612 static bool isPPC_64Builtin(unsigned BuiltinID) {
3613   // These builtins only work on PPC 64bit targets.
3614   switch (BuiltinID) {
3615   case PPC::BI__builtin_divde:
3616   case PPC::BI__builtin_divdeu:
3617   case PPC::BI__builtin_bpermd:
3618   case PPC::BI__builtin_pdepd:
3619   case PPC::BI__builtin_pextd:
3620   case PPC::BI__builtin_ppc_ldarx:
3621   case PPC::BI__builtin_ppc_stdcx:
3622   case PPC::BI__builtin_ppc_tdw:
3623   case PPC::BI__builtin_ppc_trapd:
3624   case PPC::BI__builtin_ppc_cmpeqb:
3625   case PPC::BI__builtin_ppc_setb:
3626   case PPC::BI__builtin_ppc_mulhd:
3627   case PPC::BI__builtin_ppc_mulhdu:
3628   case PPC::BI__builtin_ppc_maddhd:
3629   case PPC::BI__builtin_ppc_maddhdu:
3630   case PPC::BI__builtin_ppc_maddld:
3631   case PPC::BI__builtin_ppc_load8r:
3632   case PPC::BI__builtin_ppc_store8r:
3633   case PPC::BI__builtin_ppc_insert_exp:
3634   case PPC::BI__builtin_ppc_extract_sig:
3635   case PPC::BI__builtin_ppc_addex:
3636   case PPC::BI__builtin_darn:
3637   case PPC::BI__builtin_darn_raw:
3638   case PPC::BI__builtin_ppc_compare_and_swaplp:
3639   case PPC::BI__builtin_ppc_fetch_and_addlp:
3640   case PPC::BI__builtin_ppc_fetch_and_andlp:
3641   case PPC::BI__builtin_ppc_fetch_and_orlp:
3642   case PPC::BI__builtin_ppc_fetch_and_swaplp:
3643     return true;
3644   }
3645   return false;
3646 }
3647 
3648 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3649                              StringRef FeatureToCheck, unsigned DiagID,
3650                              StringRef DiagArg = "") {
3651   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3652     return false;
3653 
3654   if (DiagArg.empty())
3655     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3656   else
3657     S.Diag(TheCall->getBeginLoc(), DiagID)
3658         << DiagArg << TheCall->getSourceRange();
3659 
3660   return true;
3661 }
3662 
3663 /// Returns true if the argument consists of one contiguous run of 1s with any
3664 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3665 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3666 /// since all 1s are not contiguous.
3667 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3668   llvm::APSInt Result;
3669   // We can't check the value of a dependent argument.
3670   Expr *Arg = TheCall->getArg(ArgNum);
3671   if (Arg->isTypeDependent() || Arg->isValueDependent())
3672     return false;
3673 
3674   // Check constant-ness first.
3675   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3676     return true;
3677 
3678   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3679   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3680     return false;
3681 
3682   return Diag(TheCall->getBeginLoc(),
3683               diag::err_argument_not_contiguous_bit_field)
3684          << ArgNum << Arg->getSourceRange();
3685 }
3686 
3687 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3688                                        CallExpr *TheCall) {
3689   unsigned i = 0, l = 0, u = 0;
3690   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3691   llvm::APSInt Result;
3692 
3693   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3694     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3695            << TheCall->getSourceRange();
3696 
3697   switch (BuiltinID) {
3698   default: return false;
3699   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3700   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3701     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3702            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3703   case PPC::BI__builtin_altivec_dss:
3704     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3705   case PPC::BI__builtin_tbegin:
3706   case PPC::BI__builtin_tend:
3707     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 1) ||
3708            SemaFeatureCheck(*this, TheCall, "htm",
3709                             diag::err_ppc_builtin_requires_htm);
3710   case PPC::BI__builtin_tsr:
3711     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3712            SemaFeatureCheck(*this, TheCall, "htm",
3713                             diag::err_ppc_builtin_requires_htm);
3714   case PPC::BI__builtin_tabortwc:
3715   case PPC::BI__builtin_tabortdc:
3716     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3717            SemaFeatureCheck(*this, TheCall, "htm",
3718                             diag::err_ppc_builtin_requires_htm);
3719   case PPC::BI__builtin_tabortwci:
3720   case PPC::BI__builtin_tabortdci:
3721     return SemaFeatureCheck(*this, TheCall, "htm",
3722                             diag::err_ppc_builtin_requires_htm) ||
3723            (SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3724             SemaBuiltinConstantArgRange(TheCall, 2, 0, 31));
3725   case PPC::BI__builtin_tabort:
3726   case PPC::BI__builtin_tcheck:
3727   case PPC::BI__builtin_treclaim:
3728   case PPC::BI__builtin_trechkpt:
3729   case PPC::BI__builtin_tendall:
3730   case PPC::BI__builtin_tresume:
3731   case PPC::BI__builtin_tsuspend:
3732   case PPC::BI__builtin_get_texasr:
3733   case PPC::BI__builtin_get_texasru:
3734   case PPC::BI__builtin_get_tfhar:
3735   case PPC::BI__builtin_get_tfiar:
3736   case PPC::BI__builtin_set_texasr:
3737   case PPC::BI__builtin_set_texasru:
3738   case PPC::BI__builtin_set_tfhar:
3739   case PPC::BI__builtin_set_tfiar:
3740   case PPC::BI__builtin_ttest:
3741     return SemaFeatureCheck(*this, TheCall, "htm",
3742                             diag::err_ppc_builtin_requires_htm);
3743   // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05',
3744   // __builtin_(un)pack_longdouble are available only if long double uses IBM
3745   // extended double representation.
3746   case PPC::BI__builtin_unpack_longdouble:
3747     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1))
3748       return true;
3749     LLVM_FALLTHROUGH;
3750   case PPC::BI__builtin_pack_longdouble:
3751     if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble())
3752       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi)
3753              << "ibmlongdouble";
3754     return false;
3755   case PPC::BI__builtin_altivec_dst:
3756   case PPC::BI__builtin_altivec_dstt:
3757   case PPC::BI__builtin_altivec_dstst:
3758   case PPC::BI__builtin_altivec_dststt:
3759     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3760   case PPC::BI__builtin_vsx_xxpermdi:
3761   case PPC::BI__builtin_vsx_xxsldwi:
3762     return SemaBuiltinVSX(TheCall);
3763   case PPC::BI__builtin_divwe:
3764   case PPC::BI__builtin_divweu:
3765   case PPC::BI__builtin_divde:
3766   case PPC::BI__builtin_divdeu:
3767     return SemaFeatureCheck(*this, TheCall, "extdiv",
3768                             diag::err_ppc_builtin_only_on_arch, "7");
3769   case PPC::BI__builtin_bpermd:
3770     return SemaFeatureCheck(*this, TheCall, "bpermd",
3771                             diag::err_ppc_builtin_only_on_arch, "7");
3772   case PPC::BI__builtin_unpack_vector_int128:
3773     return SemaFeatureCheck(*this, TheCall, "vsx",
3774                             diag::err_ppc_builtin_only_on_arch, "7") ||
3775            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3776   case PPC::BI__builtin_pack_vector_int128:
3777     return SemaFeatureCheck(*this, TheCall, "vsx",
3778                             diag::err_ppc_builtin_only_on_arch, "7");
3779   case PPC::BI__builtin_pdepd:
3780   case PPC::BI__builtin_pextd:
3781     return SemaFeatureCheck(*this, TheCall, "isa-v31-instructions",
3782                             diag::err_ppc_builtin_only_on_arch, "10");
3783   case PPC::BI__builtin_altivec_vgnb:
3784      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3785   case PPC::BI__builtin_altivec_vec_replace_elt:
3786   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3787     QualType VecTy = TheCall->getArg(0)->getType();
3788     QualType EltTy = TheCall->getArg(1)->getType();
3789     unsigned Width = Context.getIntWidth(EltTy);
3790     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3791            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3792   }
3793   case PPC::BI__builtin_vsx_xxeval:
3794      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3795   case PPC::BI__builtin_altivec_vsldbi:
3796      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3797   case PPC::BI__builtin_altivec_vsrdbi:
3798      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3799   case PPC::BI__builtin_vsx_xxpermx:
3800      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3801   case PPC::BI__builtin_ppc_tw:
3802   case PPC::BI__builtin_ppc_tdw:
3803     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3804   case PPC::BI__builtin_ppc_cmpeqb:
3805   case PPC::BI__builtin_ppc_setb:
3806   case PPC::BI__builtin_ppc_maddhd:
3807   case PPC::BI__builtin_ppc_maddhdu:
3808   case PPC::BI__builtin_ppc_maddld:
3809     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3810                             diag::err_ppc_builtin_only_on_arch, "9");
3811   case PPC::BI__builtin_ppc_cmprb:
3812     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3813                             diag::err_ppc_builtin_only_on_arch, "9") ||
3814            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3815   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3816   // be a constant that represents a contiguous bit field.
3817   case PPC::BI__builtin_ppc_rlwnm:
3818     return SemaValueIsRunOfOnes(TheCall, 2);
3819   case PPC::BI__builtin_ppc_rlwimi:
3820   case PPC::BI__builtin_ppc_rldimi:
3821     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3822            SemaValueIsRunOfOnes(TheCall, 3);
3823   case PPC::BI__builtin_ppc_extract_exp:
3824   case PPC::BI__builtin_ppc_extract_sig:
3825   case PPC::BI__builtin_ppc_insert_exp:
3826     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3827                             diag::err_ppc_builtin_only_on_arch, "9");
3828   case PPC::BI__builtin_ppc_addex: {
3829     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3830                          diag::err_ppc_builtin_only_on_arch, "9") ||
3831         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
3832       return true;
3833     // Output warning for reserved values 1 to 3.
3834     int ArgValue =
3835         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
3836     if (ArgValue != 0)
3837       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
3838           << ArgValue;
3839     return false;
3840   }
3841   case PPC::BI__builtin_ppc_mtfsb0:
3842   case PPC::BI__builtin_ppc_mtfsb1:
3843     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3844   case PPC::BI__builtin_ppc_mtfsf:
3845     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3846   case PPC::BI__builtin_ppc_mtfsfi:
3847     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3848            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3849   case PPC::BI__builtin_ppc_alignx:
3850     return SemaBuiltinConstantArgPower2(TheCall, 0);
3851   case PPC::BI__builtin_ppc_rdlam:
3852     return SemaValueIsRunOfOnes(TheCall, 2);
3853   case PPC::BI__builtin_ppc_icbt:
3854   case PPC::BI__builtin_ppc_sthcx:
3855   case PPC::BI__builtin_ppc_stbcx:
3856   case PPC::BI__builtin_ppc_lharx:
3857   case PPC::BI__builtin_ppc_lbarx:
3858     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3859                             diag::err_ppc_builtin_only_on_arch, "8");
3860   case PPC::BI__builtin_vsx_ldrmb:
3861   case PPC::BI__builtin_vsx_strmb:
3862     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3863                             diag::err_ppc_builtin_only_on_arch, "8") ||
3864            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3865   case PPC::BI__builtin_altivec_vcntmbb:
3866   case PPC::BI__builtin_altivec_vcntmbh:
3867   case PPC::BI__builtin_altivec_vcntmbw:
3868   case PPC::BI__builtin_altivec_vcntmbd:
3869     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3870   case PPC::BI__builtin_darn:
3871   case PPC::BI__builtin_darn_raw:
3872   case PPC::BI__builtin_darn_32:
3873     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3874                             diag::err_ppc_builtin_only_on_arch, "9");
3875   case PPC::BI__builtin_vsx_xxgenpcvbm:
3876   case PPC::BI__builtin_vsx_xxgenpcvhm:
3877   case PPC::BI__builtin_vsx_xxgenpcvwm:
3878   case PPC::BI__builtin_vsx_xxgenpcvdm:
3879     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3880   case PPC::BI__builtin_ppc_compare_exp_uo:
3881   case PPC::BI__builtin_ppc_compare_exp_lt:
3882   case PPC::BI__builtin_ppc_compare_exp_gt:
3883   case PPC::BI__builtin_ppc_compare_exp_eq:
3884     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3885                             diag::err_ppc_builtin_only_on_arch, "9") ||
3886            SemaFeatureCheck(*this, TheCall, "vsx",
3887                             diag::err_ppc_builtin_requires_vsx);
3888   case PPC::BI__builtin_ppc_test_data_class: {
3889     // Check if the first argument of the __builtin_ppc_test_data_class call is
3890     // valid. The argument must be either a 'float' or a 'double'.
3891     QualType ArgType = TheCall->getArg(0)->getType();
3892     if (ArgType != QualType(Context.FloatTy) &&
3893         ArgType != QualType(Context.DoubleTy))
3894       return Diag(TheCall->getBeginLoc(),
3895                   diag::err_ppc_invalid_test_data_class_type);
3896     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3897                             diag::err_ppc_builtin_only_on_arch, "9") ||
3898            SemaFeatureCheck(*this, TheCall, "vsx",
3899                             diag::err_ppc_builtin_requires_vsx) ||
3900            SemaBuiltinConstantArgRange(TheCall, 1, 0, 127);
3901   }
3902   case PPC::BI__builtin_ppc_load8r:
3903   case PPC::BI__builtin_ppc_store8r:
3904     return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions",
3905                             diag::err_ppc_builtin_only_on_arch, "7");
3906 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc)                                 \
3907   case PPC::BI__builtin_##Name:                                                \
3908     return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types);
3909 #include "clang/Basic/BuiltinsPPC.def"
3910   }
3911   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3912 }
3913 
3914 // Check if the given type is a non-pointer PPC MMA type. This function is used
3915 // in Sema to prevent invalid uses of restricted PPC MMA types.
3916 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3917   if (Type->isPointerType() || Type->isArrayType())
3918     return false;
3919 
3920   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3921 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3922   if (false
3923 #include "clang/Basic/PPCTypes.def"
3924      ) {
3925     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3926     return true;
3927   }
3928   return false;
3929 }
3930 
3931 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3932                                           CallExpr *TheCall) {
3933   // position of memory order and scope arguments in the builtin
3934   unsigned OrderIndex, ScopeIndex;
3935   switch (BuiltinID) {
3936   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3937   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3938   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3939   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3940     OrderIndex = 2;
3941     ScopeIndex = 3;
3942     break;
3943   case AMDGPU::BI__builtin_amdgcn_fence:
3944     OrderIndex = 0;
3945     ScopeIndex = 1;
3946     break;
3947   default:
3948     return false;
3949   }
3950 
3951   ExprResult Arg = TheCall->getArg(OrderIndex);
3952   auto ArgExpr = Arg.get();
3953   Expr::EvalResult ArgResult;
3954 
3955   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3956     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3957            << ArgExpr->getType();
3958   auto Ord = ArgResult.Val.getInt().getZExtValue();
3959 
3960   // Check validity of memory ordering as per C11 / C++11's memody model.
3961   // Only fence needs check. Atomic dec/inc allow all memory orders.
3962   if (!llvm::isValidAtomicOrderingCABI(Ord))
3963     return Diag(ArgExpr->getBeginLoc(),
3964                 diag::warn_atomic_op_has_invalid_memory_order)
3965            << ArgExpr->getSourceRange();
3966   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3967   case llvm::AtomicOrderingCABI::relaxed:
3968   case llvm::AtomicOrderingCABI::consume:
3969     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3970       return Diag(ArgExpr->getBeginLoc(),
3971                   diag::warn_atomic_op_has_invalid_memory_order)
3972              << ArgExpr->getSourceRange();
3973     break;
3974   case llvm::AtomicOrderingCABI::acquire:
3975   case llvm::AtomicOrderingCABI::release:
3976   case llvm::AtomicOrderingCABI::acq_rel:
3977   case llvm::AtomicOrderingCABI::seq_cst:
3978     break;
3979   }
3980 
3981   Arg = TheCall->getArg(ScopeIndex);
3982   ArgExpr = Arg.get();
3983   Expr::EvalResult ArgResult1;
3984   // Check that sync scope is a constant literal
3985   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3986     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3987            << ArgExpr->getType();
3988 
3989   return false;
3990 }
3991 
3992 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3993   llvm::APSInt Result;
3994 
3995   // We can't check the value of a dependent argument.
3996   Expr *Arg = TheCall->getArg(ArgNum);
3997   if (Arg->isTypeDependent() || Arg->isValueDependent())
3998     return false;
3999 
4000   // Check constant-ness first.
4001   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4002     return true;
4003 
4004   int64_t Val = Result.getSExtValue();
4005   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
4006     return false;
4007 
4008   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
4009          << Arg->getSourceRange();
4010 }
4011 
4012 static bool isRISCV32Builtin(unsigned BuiltinID) {
4013   // These builtins only work on riscv32 targets.
4014   switch (BuiltinID) {
4015   case RISCV::BI__builtin_riscv_zip_32:
4016   case RISCV::BI__builtin_riscv_unzip_32:
4017   case RISCV::BI__builtin_riscv_aes32dsi_32:
4018   case RISCV::BI__builtin_riscv_aes32dsmi_32:
4019   case RISCV::BI__builtin_riscv_aes32esi_32:
4020   case RISCV::BI__builtin_riscv_aes32esmi_32:
4021   case RISCV::BI__builtin_riscv_sha512sig0h_32:
4022   case RISCV::BI__builtin_riscv_sha512sig0l_32:
4023   case RISCV::BI__builtin_riscv_sha512sig1h_32:
4024   case RISCV::BI__builtin_riscv_sha512sig1l_32:
4025   case RISCV::BI__builtin_riscv_sha512sum0r_32:
4026   case RISCV::BI__builtin_riscv_sha512sum1r_32:
4027     return true;
4028   }
4029 
4030   return false;
4031 }
4032 
4033 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
4034                                          unsigned BuiltinID,
4035                                          CallExpr *TheCall) {
4036   // CodeGenFunction can also detect this, but this gives a better error
4037   // message.
4038   bool FeatureMissing = false;
4039   SmallVector<StringRef> ReqFeatures;
4040   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
4041   Features.split(ReqFeatures, ',');
4042 
4043   // Check for 32-bit only builtins on a 64-bit target.
4044   const llvm::Triple &TT = TI.getTriple();
4045   if (TT.getArch() != llvm::Triple::riscv32 && isRISCV32Builtin(BuiltinID))
4046     return Diag(TheCall->getCallee()->getBeginLoc(),
4047                 diag::err_32_bit_builtin_64_bit_tgt);
4048 
4049   // Check if each required feature is included
4050   for (StringRef F : ReqFeatures) {
4051     SmallVector<StringRef> ReqOpFeatures;
4052     F.split(ReqOpFeatures, '|');
4053     bool HasFeature = false;
4054     for (StringRef OF : ReqOpFeatures) {
4055       if (TI.hasFeature(OF)) {
4056         HasFeature = true;
4057         continue;
4058       }
4059     }
4060 
4061     if (!HasFeature) {
4062       std::string FeatureStrs;
4063       for (StringRef OF : ReqOpFeatures) {
4064         // If the feature is 64bit, alter the string so it will print better in
4065         // the diagnostic.
4066         if (OF == "64bit")
4067           OF = "RV64";
4068 
4069         // Convert features like "zbr" and "experimental-zbr" to "Zbr".
4070         OF.consume_front("experimental-");
4071         std::string FeatureStr = OF.str();
4072         FeatureStr[0] = std::toupper(FeatureStr[0]);
4073         // Combine strings.
4074         FeatureStrs += FeatureStrs == "" ? "" : ", ";
4075         FeatureStrs += "'";
4076         FeatureStrs += FeatureStr;
4077         FeatureStrs += "'";
4078       }
4079       // Error message
4080       FeatureMissing = true;
4081       Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
4082           << TheCall->getSourceRange() << StringRef(FeatureStrs);
4083     }
4084   }
4085 
4086   if (FeatureMissing)
4087     return true;
4088 
4089   switch (BuiltinID) {
4090   case RISCVVector::BI__builtin_rvv_vsetvli:
4091     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
4092            CheckRISCVLMUL(TheCall, 2);
4093   case RISCVVector::BI__builtin_rvv_vsetvlimax:
4094     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
4095            CheckRISCVLMUL(TheCall, 1);
4096   // Check if byteselect is in [0, 3]
4097   case RISCV::BI__builtin_riscv_aes32dsi_32:
4098   case RISCV::BI__builtin_riscv_aes32dsmi_32:
4099   case RISCV::BI__builtin_riscv_aes32esi_32:
4100   case RISCV::BI__builtin_riscv_aes32esmi_32:
4101   case RISCV::BI__builtin_riscv_sm4ks:
4102   case RISCV::BI__builtin_riscv_sm4ed:
4103     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
4104   // Check if rnum is in [0, 10]
4105   case RISCV::BI__builtin_riscv_aes64ks1i_64:
4106     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 10);
4107   }
4108 
4109   return false;
4110 }
4111 
4112 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
4113                                            CallExpr *TheCall) {
4114   if (BuiltinID == SystemZ::BI__builtin_tabort) {
4115     Expr *Arg = TheCall->getArg(0);
4116     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
4117       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
4118         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
4119                << Arg->getSourceRange();
4120   }
4121 
4122   // For intrinsics which take an immediate value as part of the instruction,
4123   // range check them here.
4124   unsigned i = 0, l = 0, u = 0;
4125   switch (BuiltinID) {
4126   default: return false;
4127   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
4128   case SystemZ::BI__builtin_s390_verimb:
4129   case SystemZ::BI__builtin_s390_verimh:
4130   case SystemZ::BI__builtin_s390_verimf:
4131   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
4132   case SystemZ::BI__builtin_s390_vfaeb:
4133   case SystemZ::BI__builtin_s390_vfaeh:
4134   case SystemZ::BI__builtin_s390_vfaef:
4135   case SystemZ::BI__builtin_s390_vfaebs:
4136   case SystemZ::BI__builtin_s390_vfaehs:
4137   case SystemZ::BI__builtin_s390_vfaefs:
4138   case SystemZ::BI__builtin_s390_vfaezb:
4139   case SystemZ::BI__builtin_s390_vfaezh:
4140   case SystemZ::BI__builtin_s390_vfaezf:
4141   case SystemZ::BI__builtin_s390_vfaezbs:
4142   case SystemZ::BI__builtin_s390_vfaezhs:
4143   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
4144   case SystemZ::BI__builtin_s390_vfisb:
4145   case SystemZ::BI__builtin_s390_vfidb:
4146     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
4147            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
4148   case SystemZ::BI__builtin_s390_vftcisb:
4149   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
4150   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
4151   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
4152   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
4153   case SystemZ::BI__builtin_s390_vstrcb:
4154   case SystemZ::BI__builtin_s390_vstrch:
4155   case SystemZ::BI__builtin_s390_vstrcf:
4156   case SystemZ::BI__builtin_s390_vstrczb:
4157   case SystemZ::BI__builtin_s390_vstrczh:
4158   case SystemZ::BI__builtin_s390_vstrczf:
4159   case SystemZ::BI__builtin_s390_vstrcbs:
4160   case SystemZ::BI__builtin_s390_vstrchs:
4161   case SystemZ::BI__builtin_s390_vstrcfs:
4162   case SystemZ::BI__builtin_s390_vstrczbs:
4163   case SystemZ::BI__builtin_s390_vstrczhs:
4164   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
4165   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
4166   case SystemZ::BI__builtin_s390_vfminsb:
4167   case SystemZ::BI__builtin_s390_vfmaxsb:
4168   case SystemZ::BI__builtin_s390_vfmindb:
4169   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
4170   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
4171   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
4172   case SystemZ::BI__builtin_s390_vclfnhs:
4173   case SystemZ::BI__builtin_s390_vclfnls:
4174   case SystemZ::BI__builtin_s390_vcfn:
4175   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
4176   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
4177   }
4178   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
4179 }
4180 
4181 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
4182 /// This checks that the target supports __builtin_cpu_supports and
4183 /// that the string argument is constant and valid.
4184 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
4185                                    CallExpr *TheCall) {
4186   Expr *Arg = TheCall->getArg(0);
4187 
4188   // Check if the argument is a string literal.
4189   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4190     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4191            << Arg->getSourceRange();
4192 
4193   // Check the contents of the string.
4194   StringRef Feature =
4195       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4196   if (!TI.validateCpuSupports(Feature))
4197     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
4198            << Arg->getSourceRange();
4199   return false;
4200 }
4201 
4202 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
4203 /// This checks that the target supports __builtin_cpu_is and
4204 /// that the string argument is constant and valid.
4205 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
4206   Expr *Arg = TheCall->getArg(0);
4207 
4208   // Check if the argument is a string literal.
4209   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4210     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4211            << Arg->getSourceRange();
4212 
4213   // Check the contents of the string.
4214   StringRef Feature =
4215       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4216   if (!TI.validateCpuIs(Feature))
4217     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
4218            << Arg->getSourceRange();
4219   return false;
4220 }
4221 
4222 // Check if the rounding mode is legal.
4223 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
4224   // Indicates if this instruction has rounding control or just SAE.
4225   bool HasRC = false;
4226 
4227   unsigned ArgNum = 0;
4228   switch (BuiltinID) {
4229   default:
4230     return false;
4231   case X86::BI__builtin_ia32_vcvttsd2si32:
4232   case X86::BI__builtin_ia32_vcvttsd2si64:
4233   case X86::BI__builtin_ia32_vcvttsd2usi32:
4234   case X86::BI__builtin_ia32_vcvttsd2usi64:
4235   case X86::BI__builtin_ia32_vcvttss2si32:
4236   case X86::BI__builtin_ia32_vcvttss2si64:
4237   case X86::BI__builtin_ia32_vcvttss2usi32:
4238   case X86::BI__builtin_ia32_vcvttss2usi64:
4239   case X86::BI__builtin_ia32_vcvttsh2si32:
4240   case X86::BI__builtin_ia32_vcvttsh2si64:
4241   case X86::BI__builtin_ia32_vcvttsh2usi32:
4242   case X86::BI__builtin_ia32_vcvttsh2usi64:
4243     ArgNum = 1;
4244     break;
4245   case X86::BI__builtin_ia32_maxpd512:
4246   case X86::BI__builtin_ia32_maxps512:
4247   case X86::BI__builtin_ia32_minpd512:
4248   case X86::BI__builtin_ia32_minps512:
4249   case X86::BI__builtin_ia32_maxph512:
4250   case X86::BI__builtin_ia32_minph512:
4251     ArgNum = 2;
4252     break;
4253   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
4254   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
4255   case X86::BI__builtin_ia32_cvtps2pd512_mask:
4256   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
4257   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
4258   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
4259   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
4260   case X86::BI__builtin_ia32_cvttps2dq512_mask:
4261   case X86::BI__builtin_ia32_cvttps2qq512_mask:
4262   case X86::BI__builtin_ia32_cvttps2udq512_mask:
4263   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
4264   case X86::BI__builtin_ia32_vcvttph2w512_mask:
4265   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
4266   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
4267   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
4268   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
4269   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
4270   case X86::BI__builtin_ia32_exp2pd_mask:
4271   case X86::BI__builtin_ia32_exp2ps_mask:
4272   case X86::BI__builtin_ia32_getexppd512_mask:
4273   case X86::BI__builtin_ia32_getexpps512_mask:
4274   case X86::BI__builtin_ia32_getexpph512_mask:
4275   case X86::BI__builtin_ia32_rcp28pd_mask:
4276   case X86::BI__builtin_ia32_rcp28ps_mask:
4277   case X86::BI__builtin_ia32_rsqrt28pd_mask:
4278   case X86::BI__builtin_ia32_rsqrt28ps_mask:
4279   case X86::BI__builtin_ia32_vcomisd:
4280   case X86::BI__builtin_ia32_vcomiss:
4281   case X86::BI__builtin_ia32_vcomish:
4282   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
4283     ArgNum = 3;
4284     break;
4285   case X86::BI__builtin_ia32_cmppd512_mask:
4286   case X86::BI__builtin_ia32_cmpps512_mask:
4287   case X86::BI__builtin_ia32_cmpsd_mask:
4288   case X86::BI__builtin_ia32_cmpss_mask:
4289   case X86::BI__builtin_ia32_cmpsh_mask:
4290   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
4291   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
4292   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
4293   case X86::BI__builtin_ia32_getexpsd128_round_mask:
4294   case X86::BI__builtin_ia32_getexpss128_round_mask:
4295   case X86::BI__builtin_ia32_getexpsh128_round_mask:
4296   case X86::BI__builtin_ia32_getmantpd512_mask:
4297   case X86::BI__builtin_ia32_getmantps512_mask:
4298   case X86::BI__builtin_ia32_getmantph512_mask:
4299   case X86::BI__builtin_ia32_maxsd_round_mask:
4300   case X86::BI__builtin_ia32_maxss_round_mask:
4301   case X86::BI__builtin_ia32_maxsh_round_mask:
4302   case X86::BI__builtin_ia32_minsd_round_mask:
4303   case X86::BI__builtin_ia32_minss_round_mask:
4304   case X86::BI__builtin_ia32_minsh_round_mask:
4305   case X86::BI__builtin_ia32_rcp28sd_round_mask:
4306   case X86::BI__builtin_ia32_rcp28ss_round_mask:
4307   case X86::BI__builtin_ia32_reducepd512_mask:
4308   case X86::BI__builtin_ia32_reduceps512_mask:
4309   case X86::BI__builtin_ia32_reduceph512_mask:
4310   case X86::BI__builtin_ia32_rndscalepd_mask:
4311   case X86::BI__builtin_ia32_rndscaleps_mask:
4312   case X86::BI__builtin_ia32_rndscaleph_mask:
4313   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
4314   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
4315     ArgNum = 4;
4316     break;
4317   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4318   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4319   case X86::BI__builtin_ia32_fixupimmps512_mask:
4320   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4321   case X86::BI__builtin_ia32_fixupimmsd_mask:
4322   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4323   case X86::BI__builtin_ia32_fixupimmss_mask:
4324   case X86::BI__builtin_ia32_fixupimmss_maskz:
4325   case X86::BI__builtin_ia32_getmantsd_round_mask:
4326   case X86::BI__builtin_ia32_getmantss_round_mask:
4327   case X86::BI__builtin_ia32_getmantsh_round_mask:
4328   case X86::BI__builtin_ia32_rangepd512_mask:
4329   case X86::BI__builtin_ia32_rangeps512_mask:
4330   case X86::BI__builtin_ia32_rangesd128_round_mask:
4331   case X86::BI__builtin_ia32_rangess128_round_mask:
4332   case X86::BI__builtin_ia32_reducesd_mask:
4333   case X86::BI__builtin_ia32_reducess_mask:
4334   case X86::BI__builtin_ia32_reducesh_mask:
4335   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4336   case X86::BI__builtin_ia32_rndscaless_round_mask:
4337   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4338     ArgNum = 5;
4339     break;
4340   case X86::BI__builtin_ia32_vcvtsd2si64:
4341   case X86::BI__builtin_ia32_vcvtsd2si32:
4342   case X86::BI__builtin_ia32_vcvtsd2usi32:
4343   case X86::BI__builtin_ia32_vcvtsd2usi64:
4344   case X86::BI__builtin_ia32_vcvtss2si32:
4345   case X86::BI__builtin_ia32_vcvtss2si64:
4346   case X86::BI__builtin_ia32_vcvtss2usi32:
4347   case X86::BI__builtin_ia32_vcvtss2usi64:
4348   case X86::BI__builtin_ia32_vcvtsh2si32:
4349   case X86::BI__builtin_ia32_vcvtsh2si64:
4350   case X86::BI__builtin_ia32_vcvtsh2usi32:
4351   case X86::BI__builtin_ia32_vcvtsh2usi64:
4352   case X86::BI__builtin_ia32_sqrtpd512:
4353   case X86::BI__builtin_ia32_sqrtps512:
4354   case X86::BI__builtin_ia32_sqrtph512:
4355     ArgNum = 1;
4356     HasRC = true;
4357     break;
4358   case X86::BI__builtin_ia32_addph512:
4359   case X86::BI__builtin_ia32_divph512:
4360   case X86::BI__builtin_ia32_mulph512:
4361   case X86::BI__builtin_ia32_subph512:
4362   case X86::BI__builtin_ia32_addpd512:
4363   case X86::BI__builtin_ia32_addps512:
4364   case X86::BI__builtin_ia32_divpd512:
4365   case X86::BI__builtin_ia32_divps512:
4366   case X86::BI__builtin_ia32_mulpd512:
4367   case X86::BI__builtin_ia32_mulps512:
4368   case X86::BI__builtin_ia32_subpd512:
4369   case X86::BI__builtin_ia32_subps512:
4370   case X86::BI__builtin_ia32_cvtsi2sd64:
4371   case X86::BI__builtin_ia32_cvtsi2ss32:
4372   case X86::BI__builtin_ia32_cvtsi2ss64:
4373   case X86::BI__builtin_ia32_cvtusi2sd64:
4374   case X86::BI__builtin_ia32_cvtusi2ss32:
4375   case X86::BI__builtin_ia32_cvtusi2ss64:
4376   case X86::BI__builtin_ia32_vcvtusi2sh:
4377   case X86::BI__builtin_ia32_vcvtusi642sh:
4378   case X86::BI__builtin_ia32_vcvtsi2sh:
4379   case X86::BI__builtin_ia32_vcvtsi642sh:
4380     ArgNum = 2;
4381     HasRC = true;
4382     break;
4383   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
4384   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
4385   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
4386   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
4387   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
4388   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
4389   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
4390   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
4391   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
4392   case X86::BI__builtin_ia32_cvtps2dq512_mask:
4393   case X86::BI__builtin_ia32_cvtps2qq512_mask:
4394   case X86::BI__builtin_ia32_cvtps2udq512_mask:
4395   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
4396   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
4397   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
4398   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
4399   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
4400   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
4401   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
4402   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
4403   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
4404   case X86::BI__builtin_ia32_vcvtph2w512_mask:
4405   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
4406   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
4407   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
4408   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
4409   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
4410   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
4411   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
4412     ArgNum = 3;
4413     HasRC = true;
4414     break;
4415   case X86::BI__builtin_ia32_addsh_round_mask:
4416   case X86::BI__builtin_ia32_addss_round_mask:
4417   case X86::BI__builtin_ia32_addsd_round_mask:
4418   case X86::BI__builtin_ia32_divsh_round_mask:
4419   case X86::BI__builtin_ia32_divss_round_mask:
4420   case X86::BI__builtin_ia32_divsd_round_mask:
4421   case X86::BI__builtin_ia32_mulsh_round_mask:
4422   case X86::BI__builtin_ia32_mulss_round_mask:
4423   case X86::BI__builtin_ia32_mulsd_round_mask:
4424   case X86::BI__builtin_ia32_subsh_round_mask:
4425   case X86::BI__builtin_ia32_subss_round_mask:
4426   case X86::BI__builtin_ia32_subsd_round_mask:
4427   case X86::BI__builtin_ia32_scalefph512_mask:
4428   case X86::BI__builtin_ia32_scalefpd512_mask:
4429   case X86::BI__builtin_ia32_scalefps512_mask:
4430   case X86::BI__builtin_ia32_scalefsd_round_mask:
4431   case X86::BI__builtin_ia32_scalefss_round_mask:
4432   case X86::BI__builtin_ia32_scalefsh_round_mask:
4433   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4434   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4435   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4436   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4437   case X86::BI__builtin_ia32_sqrtss_round_mask:
4438   case X86::BI__builtin_ia32_sqrtsh_round_mask:
4439   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4440   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4441   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4442   case X86::BI__builtin_ia32_vfmaddss3_mask:
4443   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4444   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4445   case X86::BI__builtin_ia32_vfmaddsh3_mask:
4446   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4447   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4448   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4449   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4450   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4451   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4452   case X86::BI__builtin_ia32_vfmaddps512_mask:
4453   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4454   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4455   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4456   case X86::BI__builtin_ia32_vfmaddph512_mask:
4457   case X86::BI__builtin_ia32_vfmaddph512_maskz:
4458   case X86::BI__builtin_ia32_vfmaddph512_mask3:
4459   case X86::BI__builtin_ia32_vfmsubph512_mask3:
4460   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4461   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4462   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4463   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4464   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4465   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4466   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4467   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4468   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4469   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4470   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4471   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4472   case X86::BI__builtin_ia32_vfmaddcsh_mask:
4473   case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
4474   case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
4475   case X86::BI__builtin_ia32_vfmaddcph512_mask:
4476   case X86::BI__builtin_ia32_vfmaddcph512_maskz:
4477   case X86::BI__builtin_ia32_vfmaddcph512_mask3:
4478   case X86::BI__builtin_ia32_vfcmaddcsh_mask:
4479   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
4480   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
4481   case X86::BI__builtin_ia32_vfcmaddcph512_mask:
4482   case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
4483   case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
4484   case X86::BI__builtin_ia32_vfmulcsh_mask:
4485   case X86::BI__builtin_ia32_vfmulcph512_mask:
4486   case X86::BI__builtin_ia32_vfcmulcsh_mask:
4487   case X86::BI__builtin_ia32_vfcmulcph512_mask:
4488     ArgNum = 4;
4489     HasRC = true;
4490     break;
4491   }
4492 
4493   llvm::APSInt Result;
4494 
4495   // We can't check the value of a dependent argument.
4496   Expr *Arg = TheCall->getArg(ArgNum);
4497   if (Arg->isTypeDependent() || Arg->isValueDependent())
4498     return false;
4499 
4500   // Check constant-ness first.
4501   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4502     return true;
4503 
4504   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4505   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4506   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4507   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4508   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4509       Result == 8/*ROUND_NO_EXC*/ ||
4510       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4511       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4512     return false;
4513 
4514   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4515          << Arg->getSourceRange();
4516 }
4517 
4518 // Check if the gather/scatter scale is legal.
4519 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4520                                              CallExpr *TheCall) {
4521   unsigned ArgNum = 0;
4522   switch (BuiltinID) {
4523   default:
4524     return false;
4525   case X86::BI__builtin_ia32_gatherpfdpd:
4526   case X86::BI__builtin_ia32_gatherpfdps:
4527   case X86::BI__builtin_ia32_gatherpfqpd:
4528   case X86::BI__builtin_ia32_gatherpfqps:
4529   case X86::BI__builtin_ia32_scatterpfdpd:
4530   case X86::BI__builtin_ia32_scatterpfdps:
4531   case X86::BI__builtin_ia32_scatterpfqpd:
4532   case X86::BI__builtin_ia32_scatterpfqps:
4533     ArgNum = 3;
4534     break;
4535   case X86::BI__builtin_ia32_gatherd_pd:
4536   case X86::BI__builtin_ia32_gatherd_pd256:
4537   case X86::BI__builtin_ia32_gatherq_pd:
4538   case X86::BI__builtin_ia32_gatherq_pd256:
4539   case X86::BI__builtin_ia32_gatherd_ps:
4540   case X86::BI__builtin_ia32_gatherd_ps256:
4541   case X86::BI__builtin_ia32_gatherq_ps:
4542   case X86::BI__builtin_ia32_gatherq_ps256:
4543   case X86::BI__builtin_ia32_gatherd_q:
4544   case X86::BI__builtin_ia32_gatherd_q256:
4545   case X86::BI__builtin_ia32_gatherq_q:
4546   case X86::BI__builtin_ia32_gatherq_q256:
4547   case X86::BI__builtin_ia32_gatherd_d:
4548   case X86::BI__builtin_ia32_gatherd_d256:
4549   case X86::BI__builtin_ia32_gatherq_d:
4550   case X86::BI__builtin_ia32_gatherq_d256:
4551   case X86::BI__builtin_ia32_gather3div2df:
4552   case X86::BI__builtin_ia32_gather3div2di:
4553   case X86::BI__builtin_ia32_gather3div4df:
4554   case X86::BI__builtin_ia32_gather3div4di:
4555   case X86::BI__builtin_ia32_gather3div4sf:
4556   case X86::BI__builtin_ia32_gather3div4si:
4557   case X86::BI__builtin_ia32_gather3div8sf:
4558   case X86::BI__builtin_ia32_gather3div8si:
4559   case X86::BI__builtin_ia32_gather3siv2df:
4560   case X86::BI__builtin_ia32_gather3siv2di:
4561   case X86::BI__builtin_ia32_gather3siv4df:
4562   case X86::BI__builtin_ia32_gather3siv4di:
4563   case X86::BI__builtin_ia32_gather3siv4sf:
4564   case X86::BI__builtin_ia32_gather3siv4si:
4565   case X86::BI__builtin_ia32_gather3siv8sf:
4566   case X86::BI__builtin_ia32_gather3siv8si:
4567   case X86::BI__builtin_ia32_gathersiv8df:
4568   case X86::BI__builtin_ia32_gathersiv16sf:
4569   case X86::BI__builtin_ia32_gatherdiv8df:
4570   case X86::BI__builtin_ia32_gatherdiv16sf:
4571   case X86::BI__builtin_ia32_gathersiv8di:
4572   case X86::BI__builtin_ia32_gathersiv16si:
4573   case X86::BI__builtin_ia32_gatherdiv8di:
4574   case X86::BI__builtin_ia32_gatherdiv16si:
4575   case X86::BI__builtin_ia32_scatterdiv2df:
4576   case X86::BI__builtin_ia32_scatterdiv2di:
4577   case X86::BI__builtin_ia32_scatterdiv4df:
4578   case X86::BI__builtin_ia32_scatterdiv4di:
4579   case X86::BI__builtin_ia32_scatterdiv4sf:
4580   case X86::BI__builtin_ia32_scatterdiv4si:
4581   case X86::BI__builtin_ia32_scatterdiv8sf:
4582   case X86::BI__builtin_ia32_scatterdiv8si:
4583   case X86::BI__builtin_ia32_scattersiv2df:
4584   case X86::BI__builtin_ia32_scattersiv2di:
4585   case X86::BI__builtin_ia32_scattersiv4df:
4586   case X86::BI__builtin_ia32_scattersiv4di:
4587   case X86::BI__builtin_ia32_scattersiv4sf:
4588   case X86::BI__builtin_ia32_scattersiv4si:
4589   case X86::BI__builtin_ia32_scattersiv8sf:
4590   case X86::BI__builtin_ia32_scattersiv8si:
4591   case X86::BI__builtin_ia32_scattersiv8df:
4592   case X86::BI__builtin_ia32_scattersiv16sf:
4593   case X86::BI__builtin_ia32_scatterdiv8df:
4594   case X86::BI__builtin_ia32_scatterdiv16sf:
4595   case X86::BI__builtin_ia32_scattersiv8di:
4596   case X86::BI__builtin_ia32_scattersiv16si:
4597   case X86::BI__builtin_ia32_scatterdiv8di:
4598   case X86::BI__builtin_ia32_scatterdiv16si:
4599     ArgNum = 4;
4600     break;
4601   }
4602 
4603   llvm::APSInt Result;
4604 
4605   // We can't check the value of a dependent argument.
4606   Expr *Arg = TheCall->getArg(ArgNum);
4607   if (Arg->isTypeDependent() || Arg->isValueDependent())
4608     return false;
4609 
4610   // Check constant-ness first.
4611   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4612     return true;
4613 
4614   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4615     return false;
4616 
4617   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4618          << Arg->getSourceRange();
4619 }
4620 
4621 enum { TileRegLow = 0, TileRegHigh = 7 };
4622 
4623 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4624                                              ArrayRef<int> ArgNums) {
4625   for (int ArgNum : ArgNums) {
4626     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4627       return true;
4628   }
4629   return false;
4630 }
4631 
4632 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4633                                         ArrayRef<int> ArgNums) {
4634   // Because the max number of tile register is TileRegHigh + 1, so here we use
4635   // each bit to represent the usage of them in bitset.
4636   std::bitset<TileRegHigh + 1> ArgValues;
4637   for (int ArgNum : ArgNums) {
4638     Expr *Arg = TheCall->getArg(ArgNum);
4639     if (Arg->isTypeDependent() || Arg->isValueDependent())
4640       continue;
4641 
4642     llvm::APSInt Result;
4643     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4644       return true;
4645     int ArgExtValue = Result.getExtValue();
4646     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4647            "Incorrect tile register num.");
4648     if (ArgValues.test(ArgExtValue))
4649       return Diag(TheCall->getBeginLoc(),
4650                   diag::err_x86_builtin_tile_arg_duplicate)
4651              << TheCall->getArg(ArgNum)->getSourceRange();
4652     ArgValues.set(ArgExtValue);
4653   }
4654   return false;
4655 }
4656 
4657 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4658                                                 ArrayRef<int> ArgNums) {
4659   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4660          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4661 }
4662 
4663 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4664   switch (BuiltinID) {
4665   default:
4666     return false;
4667   case X86::BI__builtin_ia32_tileloadd64:
4668   case X86::BI__builtin_ia32_tileloaddt164:
4669   case X86::BI__builtin_ia32_tilestored64:
4670   case X86::BI__builtin_ia32_tilezero:
4671     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4672   case X86::BI__builtin_ia32_tdpbssd:
4673   case X86::BI__builtin_ia32_tdpbsud:
4674   case X86::BI__builtin_ia32_tdpbusd:
4675   case X86::BI__builtin_ia32_tdpbuud:
4676   case X86::BI__builtin_ia32_tdpbf16ps:
4677     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4678   }
4679 }
4680 static bool isX86_32Builtin(unsigned BuiltinID) {
4681   // These builtins only work on x86-32 targets.
4682   switch (BuiltinID) {
4683   case X86::BI__builtin_ia32_readeflags_u32:
4684   case X86::BI__builtin_ia32_writeeflags_u32:
4685     return true;
4686   }
4687 
4688   return false;
4689 }
4690 
4691 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4692                                        CallExpr *TheCall) {
4693   if (BuiltinID == X86::BI__builtin_cpu_supports)
4694     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4695 
4696   if (BuiltinID == X86::BI__builtin_cpu_is)
4697     return SemaBuiltinCpuIs(*this, TI, TheCall);
4698 
4699   // Check for 32-bit only builtins on a 64-bit target.
4700   const llvm::Triple &TT = TI.getTriple();
4701   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4702     return Diag(TheCall->getCallee()->getBeginLoc(),
4703                 diag::err_32_bit_builtin_64_bit_tgt);
4704 
4705   // If the intrinsic has rounding or SAE make sure its valid.
4706   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4707     return true;
4708 
4709   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4710   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4711     return true;
4712 
4713   // If the intrinsic has a tile arguments, make sure they are valid.
4714   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4715     return true;
4716 
4717   // For intrinsics which take an immediate value as part of the instruction,
4718   // range check them here.
4719   int i = 0, l = 0, u = 0;
4720   switch (BuiltinID) {
4721   default:
4722     return false;
4723   case X86::BI__builtin_ia32_vec_ext_v2si:
4724   case X86::BI__builtin_ia32_vec_ext_v2di:
4725   case X86::BI__builtin_ia32_vextractf128_pd256:
4726   case X86::BI__builtin_ia32_vextractf128_ps256:
4727   case X86::BI__builtin_ia32_vextractf128_si256:
4728   case X86::BI__builtin_ia32_extract128i256:
4729   case X86::BI__builtin_ia32_extractf64x4_mask:
4730   case X86::BI__builtin_ia32_extracti64x4_mask:
4731   case X86::BI__builtin_ia32_extractf32x8_mask:
4732   case X86::BI__builtin_ia32_extracti32x8_mask:
4733   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4734   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4735   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4736   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4737     i = 1; l = 0; u = 1;
4738     break;
4739   case X86::BI__builtin_ia32_vec_set_v2di:
4740   case X86::BI__builtin_ia32_vinsertf128_pd256:
4741   case X86::BI__builtin_ia32_vinsertf128_ps256:
4742   case X86::BI__builtin_ia32_vinsertf128_si256:
4743   case X86::BI__builtin_ia32_insert128i256:
4744   case X86::BI__builtin_ia32_insertf32x8:
4745   case X86::BI__builtin_ia32_inserti32x8:
4746   case X86::BI__builtin_ia32_insertf64x4:
4747   case X86::BI__builtin_ia32_inserti64x4:
4748   case X86::BI__builtin_ia32_insertf64x2_256:
4749   case X86::BI__builtin_ia32_inserti64x2_256:
4750   case X86::BI__builtin_ia32_insertf32x4_256:
4751   case X86::BI__builtin_ia32_inserti32x4_256:
4752     i = 2; l = 0; u = 1;
4753     break;
4754   case X86::BI__builtin_ia32_vpermilpd:
4755   case X86::BI__builtin_ia32_vec_ext_v4hi:
4756   case X86::BI__builtin_ia32_vec_ext_v4si:
4757   case X86::BI__builtin_ia32_vec_ext_v4sf:
4758   case X86::BI__builtin_ia32_vec_ext_v4di:
4759   case X86::BI__builtin_ia32_extractf32x4_mask:
4760   case X86::BI__builtin_ia32_extracti32x4_mask:
4761   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4762   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4763     i = 1; l = 0; u = 3;
4764     break;
4765   case X86::BI_mm_prefetch:
4766   case X86::BI__builtin_ia32_vec_ext_v8hi:
4767   case X86::BI__builtin_ia32_vec_ext_v8si:
4768     i = 1; l = 0; u = 7;
4769     break;
4770   case X86::BI__builtin_ia32_sha1rnds4:
4771   case X86::BI__builtin_ia32_blendpd:
4772   case X86::BI__builtin_ia32_shufpd:
4773   case X86::BI__builtin_ia32_vec_set_v4hi:
4774   case X86::BI__builtin_ia32_vec_set_v4si:
4775   case X86::BI__builtin_ia32_vec_set_v4di:
4776   case X86::BI__builtin_ia32_shuf_f32x4_256:
4777   case X86::BI__builtin_ia32_shuf_f64x2_256:
4778   case X86::BI__builtin_ia32_shuf_i32x4_256:
4779   case X86::BI__builtin_ia32_shuf_i64x2_256:
4780   case X86::BI__builtin_ia32_insertf64x2_512:
4781   case X86::BI__builtin_ia32_inserti64x2_512:
4782   case X86::BI__builtin_ia32_insertf32x4:
4783   case X86::BI__builtin_ia32_inserti32x4:
4784     i = 2; l = 0; u = 3;
4785     break;
4786   case X86::BI__builtin_ia32_vpermil2pd:
4787   case X86::BI__builtin_ia32_vpermil2pd256:
4788   case X86::BI__builtin_ia32_vpermil2ps:
4789   case X86::BI__builtin_ia32_vpermil2ps256:
4790     i = 3; l = 0; u = 3;
4791     break;
4792   case X86::BI__builtin_ia32_cmpb128_mask:
4793   case X86::BI__builtin_ia32_cmpw128_mask:
4794   case X86::BI__builtin_ia32_cmpd128_mask:
4795   case X86::BI__builtin_ia32_cmpq128_mask:
4796   case X86::BI__builtin_ia32_cmpb256_mask:
4797   case X86::BI__builtin_ia32_cmpw256_mask:
4798   case X86::BI__builtin_ia32_cmpd256_mask:
4799   case X86::BI__builtin_ia32_cmpq256_mask:
4800   case X86::BI__builtin_ia32_cmpb512_mask:
4801   case X86::BI__builtin_ia32_cmpw512_mask:
4802   case X86::BI__builtin_ia32_cmpd512_mask:
4803   case X86::BI__builtin_ia32_cmpq512_mask:
4804   case X86::BI__builtin_ia32_ucmpb128_mask:
4805   case X86::BI__builtin_ia32_ucmpw128_mask:
4806   case X86::BI__builtin_ia32_ucmpd128_mask:
4807   case X86::BI__builtin_ia32_ucmpq128_mask:
4808   case X86::BI__builtin_ia32_ucmpb256_mask:
4809   case X86::BI__builtin_ia32_ucmpw256_mask:
4810   case X86::BI__builtin_ia32_ucmpd256_mask:
4811   case X86::BI__builtin_ia32_ucmpq256_mask:
4812   case X86::BI__builtin_ia32_ucmpb512_mask:
4813   case X86::BI__builtin_ia32_ucmpw512_mask:
4814   case X86::BI__builtin_ia32_ucmpd512_mask:
4815   case X86::BI__builtin_ia32_ucmpq512_mask:
4816   case X86::BI__builtin_ia32_vpcomub:
4817   case X86::BI__builtin_ia32_vpcomuw:
4818   case X86::BI__builtin_ia32_vpcomud:
4819   case X86::BI__builtin_ia32_vpcomuq:
4820   case X86::BI__builtin_ia32_vpcomb:
4821   case X86::BI__builtin_ia32_vpcomw:
4822   case X86::BI__builtin_ia32_vpcomd:
4823   case X86::BI__builtin_ia32_vpcomq:
4824   case X86::BI__builtin_ia32_vec_set_v8hi:
4825   case X86::BI__builtin_ia32_vec_set_v8si:
4826     i = 2; l = 0; u = 7;
4827     break;
4828   case X86::BI__builtin_ia32_vpermilpd256:
4829   case X86::BI__builtin_ia32_roundps:
4830   case X86::BI__builtin_ia32_roundpd:
4831   case X86::BI__builtin_ia32_roundps256:
4832   case X86::BI__builtin_ia32_roundpd256:
4833   case X86::BI__builtin_ia32_getmantpd128_mask:
4834   case X86::BI__builtin_ia32_getmantpd256_mask:
4835   case X86::BI__builtin_ia32_getmantps128_mask:
4836   case X86::BI__builtin_ia32_getmantps256_mask:
4837   case X86::BI__builtin_ia32_getmantpd512_mask:
4838   case X86::BI__builtin_ia32_getmantps512_mask:
4839   case X86::BI__builtin_ia32_getmantph128_mask:
4840   case X86::BI__builtin_ia32_getmantph256_mask:
4841   case X86::BI__builtin_ia32_getmantph512_mask:
4842   case X86::BI__builtin_ia32_vec_ext_v16qi:
4843   case X86::BI__builtin_ia32_vec_ext_v16hi:
4844     i = 1; l = 0; u = 15;
4845     break;
4846   case X86::BI__builtin_ia32_pblendd128:
4847   case X86::BI__builtin_ia32_blendps:
4848   case X86::BI__builtin_ia32_blendpd256:
4849   case X86::BI__builtin_ia32_shufpd256:
4850   case X86::BI__builtin_ia32_roundss:
4851   case X86::BI__builtin_ia32_roundsd:
4852   case X86::BI__builtin_ia32_rangepd128_mask:
4853   case X86::BI__builtin_ia32_rangepd256_mask:
4854   case X86::BI__builtin_ia32_rangepd512_mask:
4855   case X86::BI__builtin_ia32_rangeps128_mask:
4856   case X86::BI__builtin_ia32_rangeps256_mask:
4857   case X86::BI__builtin_ia32_rangeps512_mask:
4858   case X86::BI__builtin_ia32_getmantsd_round_mask:
4859   case X86::BI__builtin_ia32_getmantss_round_mask:
4860   case X86::BI__builtin_ia32_getmantsh_round_mask:
4861   case X86::BI__builtin_ia32_vec_set_v16qi:
4862   case X86::BI__builtin_ia32_vec_set_v16hi:
4863     i = 2; l = 0; u = 15;
4864     break;
4865   case X86::BI__builtin_ia32_vec_ext_v32qi:
4866     i = 1; l = 0; u = 31;
4867     break;
4868   case X86::BI__builtin_ia32_cmpps:
4869   case X86::BI__builtin_ia32_cmpss:
4870   case X86::BI__builtin_ia32_cmppd:
4871   case X86::BI__builtin_ia32_cmpsd:
4872   case X86::BI__builtin_ia32_cmpps256:
4873   case X86::BI__builtin_ia32_cmppd256:
4874   case X86::BI__builtin_ia32_cmpps128_mask:
4875   case X86::BI__builtin_ia32_cmppd128_mask:
4876   case X86::BI__builtin_ia32_cmpps256_mask:
4877   case X86::BI__builtin_ia32_cmppd256_mask:
4878   case X86::BI__builtin_ia32_cmpps512_mask:
4879   case X86::BI__builtin_ia32_cmppd512_mask:
4880   case X86::BI__builtin_ia32_cmpsd_mask:
4881   case X86::BI__builtin_ia32_cmpss_mask:
4882   case X86::BI__builtin_ia32_vec_set_v32qi:
4883     i = 2; l = 0; u = 31;
4884     break;
4885   case X86::BI__builtin_ia32_permdf256:
4886   case X86::BI__builtin_ia32_permdi256:
4887   case X86::BI__builtin_ia32_permdf512:
4888   case X86::BI__builtin_ia32_permdi512:
4889   case X86::BI__builtin_ia32_vpermilps:
4890   case X86::BI__builtin_ia32_vpermilps256:
4891   case X86::BI__builtin_ia32_vpermilpd512:
4892   case X86::BI__builtin_ia32_vpermilps512:
4893   case X86::BI__builtin_ia32_pshufd:
4894   case X86::BI__builtin_ia32_pshufd256:
4895   case X86::BI__builtin_ia32_pshufd512:
4896   case X86::BI__builtin_ia32_pshufhw:
4897   case X86::BI__builtin_ia32_pshufhw256:
4898   case X86::BI__builtin_ia32_pshufhw512:
4899   case X86::BI__builtin_ia32_pshuflw:
4900   case X86::BI__builtin_ia32_pshuflw256:
4901   case X86::BI__builtin_ia32_pshuflw512:
4902   case X86::BI__builtin_ia32_vcvtps2ph:
4903   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4904   case X86::BI__builtin_ia32_vcvtps2ph256:
4905   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4906   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4907   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4908   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4909   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4910   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4911   case X86::BI__builtin_ia32_rndscaleps_mask:
4912   case X86::BI__builtin_ia32_rndscalepd_mask:
4913   case X86::BI__builtin_ia32_rndscaleph_mask:
4914   case X86::BI__builtin_ia32_reducepd128_mask:
4915   case X86::BI__builtin_ia32_reducepd256_mask:
4916   case X86::BI__builtin_ia32_reducepd512_mask:
4917   case X86::BI__builtin_ia32_reduceps128_mask:
4918   case X86::BI__builtin_ia32_reduceps256_mask:
4919   case X86::BI__builtin_ia32_reduceps512_mask:
4920   case X86::BI__builtin_ia32_reduceph128_mask:
4921   case X86::BI__builtin_ia32_reduceph256_mask:
4922   case X86::BI__builtin_ia32_reduceph512_mask:
4923   case X86::BI__builtin_ia32_prold512:
4924   case X86::BI__builtin_ia32_prolq512:
4925   case X86::BI__builtin_ia32_prold128:
4926   case X86::BI__builtin_ia32_prold256:
4927   case X86::BI__builtin_ia32_prolq128:
4928   case X86::BI__builtin_ia32_prolq256:
4929   case X86::BI__builtin_ia32_prord512:
4930   case X86::BI__builtin_ia32_prorq512:
4931   case X86::BI__builtin_ia32_prord128:
4932   case X86::BI__builtin_ia32_prord256:
4933   case X86::BI__builtin_ia32_prorq128:
4934   case X86::BI__builtin_ia32_prorq256:
4935   case X86::BI__builtin_ia32_fpclasspd128_mask:
4936   case X86::BI__builtin_ia32_fpclasspd256_mask:
4937   case X86::BI__builtin_ia32_fpclassps128_mask:
4938   case X86::BI__builtin_ia32_fpclassps256_mask:
4939   case X86::BI__builtin_ia32_fpclassps512_mask:
4940   case X86::BI__builtin_ia32_fpclasspd512_mask:
4941   case X86::BI__builtin_ia32_fpclassph128_mask:
4942   case X86::BI__builtin_ia32_fpclassph256_mask:
4943   case X86::BI__builtin_ia32_fpclassph512_mask:
4944   case X86::BI__builtin_ia32_fpclasssd_mask:
4945   case X86::BI__builtin_ia32_fpclassss_mask:
4946   case X86::BI__builtin_ia32_fpclasssh_mask:
4947   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4948   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4949   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4950   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4951   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4952   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4953   case X86::BI__builtin_ia32_kshiftliqi:
4954   case X86::BI__builtin_ia32_kshiftlihi:
4955   case X86::BI__builtin_ia32_kshiftlisi:
4956   case X86::BI__builtin_ia32_kshiftlidi:
4957   case X86::BI__builtin_ia32_kshiftriqi:
4958   case X86::BI__builtin_ia32_kshiftrihi:
4959   case X86::BI__builtin_ia32_kshiftrisi:
4960   case X86::BI__builtin_ia32_kshiftridi:
4961     i = 1; l = 0; u = 255;
4962     break;
4963   case X86::BI__builtin_ia32_vperm2f128_pd256:
4964   case X86::BI__builtin_ia32_vperm2f128_ps256:
4965   case X86::BI__builtin_ia32_vperm2f128_si256:
4966   case X86::BI__builtin_ia32_permti256:
4967   case X86::BI__builtin_ia32_pblendw128:
4968   case X86::BI__builtin_ia32_pblendw256:
4969   case X86::BI__builtin_ia32_blendps256:
4970   case X86::BI__builtin_ia32_pblendd256:
4971   case X86::BI__builtin_ia32_palignr128:
4972   case X86::BI__builtin_ia32_palignr256:
4973   case X86::BI__builtin_ia32_palignr512:
4974   case X86::BI__builtin_ia32_alignq512:
4975   case X86::BI__builtin_ia32_alignd512:
4976   case X86::BI__builtin_ia32_alignd128:
4977   case X86::BI__builtin_ia32_alignd256:
4978   case X86::BI__builtin_ia32_alignq128:
4979   case X86::BI__builtin_ia32_alignq256:
4980   case X86::BI__builtin_ia32_vcomisd:
4981   case X86::BI__builtin_ia32_vcomiss:
4982   case X86::BI__builtin_ia32_shuf_f32x4:
4983   case X86::BI__builtin_ia32_shuf_f64x2:
4984   case X86::BI__builtin_ia32_shuf_i32x4:
4985   case X86::BI__builtin_ia32_shuf_i64x2:
4986   case X86::BI__builtin_ia32_shufpd512:
4987   case X86::BI__builtin_ia32_shufps:
4988   case X86::BI__builtin_ia32_shufps256:
4989   case X86::BI__builtin_ia32_shufps512:
4990   case X86::BI__builtin_ia32_dbpsadbw128:
4991   case X86::BI__builtin_ia32_dbpsadbw256:
4992   case X86::BI__builtin_ia32_dbpsadbw512:
4993   case X86::BI__builtin_ia32_vpshldd128:
4994   case X86::BI__builtin_ia32_vpshldd256:
4995   case X86::BI__builtin_ia32_vpshldd512:
4996   case X86::BI__builtin_ia32_vpshldq128:
4997   case X86::BI__builtin_ia32_vpshldq256:
4998   case X86::BI__builtin_ia32_vpshldq512:
4999   case X86::BI__builtin_ia32_vpshldw128:
5000   case X86::BI__builtin_ia32_vpshldw256:
5001   case X86::BI__builtin_ia32_vpshldw512:
5002   case X86::BI__builtin_ia32_vpshrdd128:
5003   case X86::BI__builtin_ia32_vpshrdd256:
5004   case X86::BI__builtin_ia32_vpshrdd512:
5005   case X86::BI__builtin_ia32_vpshrdq128:
5006   case X86::BI__builtin_ia32_vpshrdq256:
5007   case X86::BI__builtin_ia32_vpshrdq512:
5008   case X86::BI__builtin_ia32_vpshrdw128:
5009   case X86::BI__builtin_ia32_vpshrdw256:
5010   case X86::BI__builtin_ia32_vpshrdw512:
5011     i = 2; l = 0; u = 255;
5012     break;
5013   case X86::BI__builtin_ia32_fixupimmpd512_mask:
5014   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
5015   case X86::BI__builtin_ia32_fixupimmps512_mask:
5016   case X86::BI__builtin_ia32_fixupimmps512_maskz:
5017   case X86::BI__builtin_ia32_fixupimmsd_mask:
5018   case X86::BI__builtin_ia32_fixupimmsd_maskz:
5019   case X86::BI__builtin_ia32_fixupimmss_mask:
5020   case X86::BI__builtin_ia32_fixupimmss_maskz:
5021   case X86::BI__builtin_ia32_fixupimmpd128_mask:
5022   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
5023   case X86::BI__builtin_ia32_fixupimmpd256_mask:
5024   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
5025   case X86::BI__builtin_ia32_fixupimmps128_mask:
5026   case X86::BI__builtin_ia32_fixupimmps128_maskz:
5027   case X86::BI__builtin_ia32_fixupimmps256_mask:
5028   case X86::BI__builtin_ia32_fixupimmps256_maskz:
5029   case X86::BI__builtin_ia32_pternlogd512_mask:
5030   case X86::BI__builtin_ia32_pternlogd512_maskz:
5031   case X86::BI__builtin_ia32_pternlogq512_mask:
5032   case X86::BI__builtin_ia32_pternlogq512_maskz:
5033   case X86::BI__builtin_ia32_pternlogd128_mask:
5034   case X86::BI__builtin_ia32_pternlogd128_maskz:
5035   case X86::BI__builtin_ia32_pternlogd256_mask:
5036   case X86::BI__builtin_ia32_pternlogd256_maskz:
5037   case X86::BI__builtin_ia32_pternlogq128_mask:
5038   case X86::BI__builtin_ia32_pternlogq128_maskz:
5039   case X86::BI__builtin_ia32_pternlogq256_mask:
5040   case X86::BI__builtin_ia32_pternlogq256_maskz:
5041     i = 3; l = 0; u = 255;
5042     break;
5043   case X86::BI__builtin_ia32_gatherpfdpd:
5044   case X86::BI__builtin_ia32_gatherpfdps:
5045   case X86::BI__builtin_ia32_gatherpfqpd:
5046   case X86::BI__builtin_ia32_gatherpfqps:
5047   case X86::BI__builtin_ia32_scatterpfdpd:
5048   case X86::BI__builtin_ia32_scatterpfdps:
5049   case X86::BI__builtin_ia32_scatterpfqpd:
5050   case X86::BI__builtin_ia32_scatterpfqps:
5051     i = 4; l = 2; u = 3;
5052     break;
5053   case X86::BI__builtin_ia32_reducesd_mask:
5054   case X86::BI__builtin_ia32_reducess_mask:
5055   case X86::BI__builtin_ia32_rndscalesd_round_mask:
5056   case X86::BI__builtin_ia32_rndscaless_round_mask:
5057   case X86::BI__builtin_ia32_rndscalesh_round_mask:
5058   case X86::BI__builtin_ia32_reducesh_mask:
5059     i = 4; l = 0; u = 255;
5060     break;
5061   }
5062 
5063   // Note that we don't force a hard error on the range check here, allowing
5064   // template-generated or macro-generated dead code to potentially have out-of-
5065   // range values. These need to code generate, but don't need to necessarily
5066   // make any sense. We use a warning that defaults to an error.
5067   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
5068 }
5069 
5070 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
5071 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
5072 /// Returns true when the format fits the function and the FormatStringInfo has
5073 /// been populated.
5074 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
5075                                FormatStringInfo *FSI) {
5076   FSI->HasVAListArg = Format->getFirstArg() == 0;
5077   FSI->FormatIdx = Format->getFormatIdx() - 1;
5078   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
5079 
5080   // The way the format attribute works in GCC, the implicit this argument
5081   // of member functions is counted. However, it doesn't appear in our own
5082   // lists, so decrement format_idx in that case.
5083   if (IsCXXMember) {
5084     if(FSI->FormatIdx == 0)
5085       return false;
5086     --FSI->FormatIdx;
5087     if (FSI->FirstDataArg != 0)
5088       --FSI->FirstDataArg;
5089   }
5090   return true;
5091 }
5092 
5093 /// Checks if a the given expression evaluates to null.
5094 ///
5095 /// Returns true if the value evaluates to null.
5096 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
5097   // If the expression has non-null type, it doesn't evaluate to null.
5098   if (auto nullability
5099         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
5100     if (*nullability == NullabilityKind::NonNull)
5101       return false;
5102   }
5103 
5104   // As a special case, transparent unions initialized with zero are
5105   // considered null for the purposes of the nonnull attribute.
5106   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
5107     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
5108       if (const CompoundLiteralExpr *CLE =
5109           dyn_cast<CompoundLiteralExpr>(Expr))
5110         if (const InitListExpr *ILE =
5111             dyn_cast<InitListExpr>(CLE->getInitializer()))
5112           Expr = ILE->getInit(0);
5113   }
5114 
5115   bool Result;
5116   return (!Expr->isValueDependent() &&
5117           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
5118           !Result);
5119 }
5120 
5121 static void CheckNonNullArgument(Sema &S,
5122                                  const Expr *ArgExpr,
5123                                  SourceLocation CallSiteLoc) {
5124   if (CheckNonNullExpr(S, ArgExpr))
5125     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
5126                           S.PDiag(diag::warn_null_arg)
5127                               << ArgExpr->getSourceRange());
5128 }
5129 
5130 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
5131   FormatStringInfo FSI;
5132   if ((GetFormatStringType(Format) == FST_NSString) &&
5133       getFormatStringInfo(Format, false, &FSI)) {
5134     Idx = FSI.FormatIdx;
5135     return true;
5136   }
5137   return false;
5138 }
5139 
5140 /// Diagnose use of %s directive in an NSString which is being passed
5141 /// as formatting string to formatting method.
5142 static void
5143 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
5144                                         const NamedDecl *FDecl,
5145                                         Expr **Args,
5146                                         unsigned NumArgs) {
5147   unsigned Idx = 0;
5148   bool Format = false;
5149   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
5150   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
5151     Idx = 2;
5152     Format = true;
5153   }
5154   else
5155     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5156       if (S.GetFormatNSStringIdx(I, Idx)) {
5157         Format = true;
5158         break;
5159       }
5160     }
5161   if (!Format || NumArgs <= Idx)
5162     return;
5163   const Expr *FormatExpr = Args[Idx];
5164   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
5165     FormatExpr = CSCE->getSubExpr();
5166   const StringLiteral *FormatString;
5167   if (const ObjCStringLiteral *OSL =
5168       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
5169     FormatString = OSL->getString();
5170   else
5171     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
5172   if (!FormatString)
5173     return;
5174   if (S.FormatStringHasSArg(FormatString)) {
5175     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
5176       << "%s" << 1 << 1;
5177     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
5178       << FDecl->getDeclName();
5179   }
5180 }
5181 
5182 /// Determine whether the given type has a non-null nullability annotation.
5183 static bool isNonNullType(ASTContext &ctx, QualType type) {
5184   if (auto nullability = type->getNullability(ctx))
5185     return *nullability == NullabilityKind::NonNull;
5186 
5187   return false;
5188 }
5189 
5190 static void CheckNonNullArguments(Sema &S,
5191                                   const NamedDecl *FDecl,
5192                                   const FunctionProtoType *Proto,
5193                                   ArrayRef<const Expr *> Args,
5194                                   SourceLocation CallSiteLoc) {
5195   assert((FDecl || Proto) && "Need a function declaration or prototype");
5196 
5197   // Already checked by by constant evaluator.
5198   if (S.isConstantEvaluated())
5199     return;
5200   // Check the attributes attached to the method/function itself.
5201   llvm::SmallBitVector NonNullArgs;
5202   if (FDecl) {
5203     // Handle the nonnull attribute on the function/method declaration itself.
5204     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
5205       if (!NonNull->args_size()) {
5206         // Easy case: all pointer arguments are nonnull.
5207         for (const auto *Arg : Args)
5208           if (S.isValidPointerAttrType(Arg->getType()))
5209             CheckNonNullArgument(S, Arg, CallSiteLoc);
5210         return;
5211       }
5212 
5213       for (const ParamIdx &Idx : NonNull->args()) {
5214         unsigned IdxAST = Idx.getASTIndex();
5215         if (IdxAST >= Args.size())
5216           continue;
5217         if (NonNullArgs.empty())
5218           NonNullArgs.resize(Args.size());
5219         NonNullArgs.set(IdxAST);
5220       }
5221     }
5222   }
5223 
5224   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
5225     // Handle the nonnull attribute on the parameters of the
5226     // function/method.
5227     ArrayRef<ParmVarDecl*> parms;
5228     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
5229       parms = FD->parameters();
5230     else
5231       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
5232 
5233     unsigned ParamIndex = 0;
5234     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
5235          I != E; ++I, ++ParamIndex) {
5236       const ParmVarDecl *PVD = *I;
5237       if (PVD->hasAttr<NonNullAttr>() ||
5238           isNonNullType(S.Context, PVD->getType())) {
5239         if (NonNullArgs.empty())
5240           NonNullArgs.resize(Args.size());
5241 
5242         NonNullArgs.set(ParamIndex);
5243       }
5244     }
5245   } else {
5246     // If we have a non-function, non-method declaration but no
5247     // function prototype, try to dig out the function prototype.
5248     if (!Proto) {
5249       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
5250         QualType type = VD->getType().getNonReferenceType();
5251         if (auto pointerType = type->getAs<PointerType>())
5252           type = pointerType->getPointeeType();
5253         else if (auto blockType = type->getAs<BlockPointerType>())
5254           type = blockType->getPointeeType();
5255         // FIXME: data member pointers?
5256 
5257         // Dig out the function prototype, if there is one.
5258         Proto = type->getAs<FunctionProtoType>();
5259       }
5260     }
5261 
5262     // Fill in non-null argument information from the nullability
5263     // information on the parameter types (if we have them).
5264     if (Proto) {
5265       unsigned Index = 0;
5266       for (auto paramType : Proto->getParamTypes()) {
5267         if (isNonNullType(S.Context, paramType)) {
5268           if (NonNullArgs.empty())
5269             NonNullArgs.resize(Args.size());
5270 
5271           NonNullArgs.set(Index);
5272         }
5273 
5274         ++Index;
5275       }
5276     }
5277   }
5278 
5279   // Check for non-null arguments.
5280   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
5281        ArgIndex != ArgIndexEnd; ++ArgIndex) {
5282     if (NonNullArgs[ArgIndex])
5283       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
5284   }
5285 }
5286 
5287 /// Warn if a pointer or reference argument passed to a function points to an
5288 /// object that is less aligned than the parameter. This can happen when
5289 /// creating a typedef with a lower alignment than the original type and then
5290 /// calling functions defined in terms of the original type.
5291 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
5292                              StringRef ParamName, QualType ArgTy,
5293                              QualType ParamTy) {
5294 
5295   // If a function accepts a pointer or reference type
5296   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
5297     return;
5298 
5299   // If the parameter is a pointer type, get the pointee type for the
5300   // argument too. If the parameter is a reference type, don't try to get
5301   // the pointee type for the argument.
5302   if (ParamTy->isPointerType())
5303     ArgTy = ArgTy->getPointeeType();
5304 
5305   // Remove reference or pointer
5306   ParamTy = ParamTy->getPointeeType();
5307 
5308   // Find expected alignment, and the actual alignment of the passed object.
5309   // getTypeAlignInChars requires complete types
5310   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
5311       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
5312       ArgTy->isUndeducedType())
5313     return;
5314 
5315   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
5316   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
5317 
5318   // If the argument is less aligned than the parameter, there is a
5319   // potential alignment issue.
5320   if (ArgAlign < ParamAlign)
5321     Diag(Loc, diag::warn_param_mismatched_alignment)
5322         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
5323         << ParamName << (FDecl != nullptr) << FDecl;
5324 }
5325 
5326 /// Handles the checks for format strings, non-POD arguments to vararg
5327 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
5328 /// attributes.
5329 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
5330                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
5331                      bool IsMemberFunction, SourceLocation Loc,
5332                      SourceRange Range, VariadicCallType CallType) {
5333   // FIXME: We should check as much as we can in the template definition.
5334   if (CurContext->isDependentContext())
5335     return;
5336 
5337   // Printf and scanf checking.
5338   llvm::SmallBitVector CheckedVarArgs;
5339   if (FDecl) {
5340     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5341       // Only create vector if there are format attributes.
5342       CheckedVarArgs.resize(Args.size());
5343 
5344       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
5345                            CheckedVarArgs);
5346     }
5347   }
5348 
5349   // Refuse POD arguments that weren't caught by the format string
5350   // checks above.
5351   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
5352   if (CallType != VariadicDoesNotApply &&
5353       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
5354     unsigned NumParams = Proto ? Proto->getNumParams()
5355                        : FDecl && isa<FunctionDecl>(FDecl)
5356                            ? cast<FunctionDecl>(FDecl)->getNumParams()
5357                        : FDecl && isa<ObjCMethodDecl>(FDecl)
5358                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
5359                        : 0;
5360 
5361     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
5362       // Args[ArgIdx] can be null in malformed code.
5363       if (const Expr *Arg = Args[ArgIdx]) {
5364         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
5365           checkVariadicArgument(Arg, CallType);
5366       }
5367     }
5368   }
5369 
5370   if (FDecl || Proto) {
5371     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
5372 
5373     // Type safety checking.
5374     if (FDecl) {
5375       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
5376         CheckArgumentWithTypeTag(I, Args, Loc);
5377     }
5378   }
5379 
5380   // Check that passed arguments match the alignment of original arguments.
5381   // Try to get the missing prototype from the declaration.
5382   if (!Proto && FDecl) {
5383     const auto *FT = FDecl->getFunctionType();
5384     if (isa_and_nonnull<FunctionProtoType>(FT))
5385       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
5386   }
5387   if (Proto) {
5388     // For variadic functions, we may have more args than parameters.
5389     // For some K&R functions, we may have less args than parameters.
5390     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
5391     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
5392       // Args[ArgIdx] can be null in malformed code.
5393       if (const Expr *Arg = Args[ArgIdx]) {
5394         if (Arg->containsErrors())
5395           continue;
5396 
5397         QualType ParamTy = Proto->getParamType(ArgIdx);
5398         QualType ArgTy = Arg->getType();
5399         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
5400                           ArgTy, ParamTy);
5401       }
5402     }
5403   }
5404 
5405   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
5406     auto *AA = FDecl->getAttr<AllocAlignAttr>();
5407     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
5408     if (!Arg->isValueDependent()) {
5409       Expr::EvalResult Align;
5410       if (Arg->EvaluateAsInt(Align, Context)) {
5411         const llvm::APSInt &I = Align.Val.getInt();
5412         if (!I.isPowerOf2())
5413           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
5414               << Arg->getSourceRange();
5415 
5416         if (I > Sema::MaximumAlignment)
5417           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
5418               << Arg->getSourceRange() << Sema::MaximumAlignment;
5419       }
5420     }
5421   }
5422 
5423   if (FD)
5424     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
5425 }
5426 
5427 /// CheckConstructorCall - Check a constructor call for correctness and safety
5428 /// properties not enforced by the C type system.
5429 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5430                                 ArrayRef<const Expr *> Args,
5431                                 const FunctionProtoType *Proto,
5432                                 SourceLocation Loc) {
5433   VariadicCallType CallType =
5434       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5435 
5436   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5437   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5438                     Context.getPointerType(Ctor->getThisObjectType()));
5439 
5440   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5441             Loc, SourceRange(), CallType);
5442 }
5443 
5444 /// CheckFunctionCall - Check a direct function call for various correctness
5445 /// and safety properties not strictly enforced by the C type system.
5446 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5447                              const FunctionProtoType *Proto) {
5448   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5449                               isa<CXXMethodDecl>(FDecl);
5450   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5451                           IsMemberOperatorCall;
5452   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5453                                                   TheCall->getCallee());
5454   Expr** Args = TheCall->getArgs();
5455   unsigned NumArgs = TheCall->getNumArgs();
5456 
5457   Expr *ImplicitThis = nullptr;
5458   if (IsMemberOperatorCall) {
5459     // If this is a call to a member operator, hide the first argument
5460     // from checkCall.
5461     // FIXME: Our choice of AST representation here is less than ideal.
5462     ImplicitThis = Args[0];
5463     ++Args;
5464     --NumArgs;
5465   } else if (IsMemberFunction)
5466     ImplicitThis =
5467         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5468 
5469   if (ImplicitThis) {
5470     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5471     // used.
5472     QualType ThisType = ImplicitThis->getType();
5473     if (!ThisType->isPointerType()) {
5474       assert(!ThisType->isReferenceType());
5475       ThisType = Context.getPointerType(ThisType);
5476     }
5477 
5478     QualType ThisTypeFromDecl =
5479         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5480 
5481     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5482                       ThisTypeFromDecl);
5483   }
5484 
5485   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5486             IsMemberFunction, TheCall->getRParenLoc(),
5487             TheCall->getCallee()->getSourceRange(), CallType);
5488 
5489   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5490   // None of the checks below are needed for functions that don't have
5491   // simple names (e.g., C++ conversion functions).
5492   if (!FnInfo)
5493     return false;
5494 
5495   CheckTCBEnforcement(TheCall, FDecl);
5496 
5497   CheckAbsoluteValueFunction(TheCall, FDecl);
5498   CheckMaxUnsignedZero(TheCall, FDecl);
5499 
5500   if (getLangOpts().ObjC)
5501     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5502 
5503   unsigned CMId = FDecl->getMemoryFunctionKind();
5504 
5505   // Handle memory setting and copying functions.
5506   switch (CMId) {
5507   case 0:
5508     return false;
5509   case Builtin::BIstrlcpy: // fallthrough
5510   case Builtin::BIstrlcat:
5511     CheckStrlcpycatArguments(TheCall, FnInfo);
5512     break;
5513   case Builtin::BIstrncat:
5514     CheckStrncatArguments(TheCall, FnInfo);
5515     break;
5516   case Builtin::BIfree:
5517     CheckFreeArguments(TheCall);
5518     break;
5519   default:
5520     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5521   }
5522 
5523   return false;
5524 }
5525 
5526 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5527                                ArrayRef<const Expr *> Args) {
5528   VariadicCallType CallType =
5529       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5530 
5531   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5532             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5533             CallType);
5534 
5535   return false;
5536 }
5537 
5538 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5539                             const FunctionProtoType *Proto) {
5540   QualType Ty;
5541   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5542     Ty = V->getType().getNonReferenceType();
5543   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5544     Ty = F->getType().getNonReferenceType();
5545   else
5546     return false;
5547 
5548   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5549       !Ty->isFunctionProtoType())
5550     return false;
5551 
5552   VariadicCallType CallType;
5553   if (!Proto || !Proto->isVariadic()) {
5554     CallType = VariadicDoesNotApply;
5555   } else if (Ty->isBlockPointerType()) {
5556     CallType = VariadicBlock;
5557   } else { // Ty->isFunctionPointerType()
5558     CallType = VariadicFunction;
5559   }
5560 
5561   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5562             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5563             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5564             TheCall->getCallee()->getSourceRange(), CallType);
5565 
5566   return false;
5567 }
5568 
5569 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5570 /// such as function pointers returned from functions.
5571 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5572   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5573                                                   TheCall->getCallee());
5574   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5575             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5576             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5577             TheCall->getCallee()->getSourceRange(), CallType);
5578 
5579   return false;
5580 }
5581 
5582 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5583   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5584     return false;
5585 
5586   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5587   switch (Op) {
5588   case AtomicExpr::AO__c11_atomic_init:
5589   case AtomicExpr::AO__opencl_atomic_init:
5590     llvm_unreachable("There is no ordering argument for an init");
5591 
5592   case AtomicExpr::AO__c11_atomic_load:
5593   case AtomicExpr::AO__opencl_atomic_load:
5594   case AtomicExpr::AO__hip_atomic_load:
5595   case AtomicExpr::AO__atomic_load_n:
5596   case AtomicExpr::AO__atomic_load:
5597     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5598            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5599 
5600   case AtomicExpr::AO__c11_atomic_store:
5601   case AtomicExpr::AO__opencl_atomic_store:
5602   case AtomicExpr::AO__hip_atomic_store:
5603   case AtomicExpr::AO__atomic_store:
5604   case AtomicExpr::AO__atomic_store_n:
5605     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5606            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5607            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5608 
5609   default:
5610     return true;
5611   }
5612 }
5613 
5614 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5615                                          AtomicExpr::AtomicOp Op) {
5616   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5617   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5618   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5619   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5620                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5621                          Op);
5622 }
5623 
5624 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5625                                  SourceLocation RParenLoc, MultiExprArg Args,
5626                                  AtomicExpr::AtomicOp Op,
5627                                  AtomicArgumentOrder ArgOrder) {
5628   // All the non-OpenCL operations take one of the following forms.
5629   // The OpenCL operations take the __c11 forms with one extra argument for
5630   // synchronization scope.
5631   enum {
5632     // C    __c11_atomic_init(A *, C)
5633     Init,
5634 
5635     // C    __c11_atomic_load(A *, int)
5636     Load,
5637 
5638     // void __atomic_load(A *, CP, int)
5639     LoadCopy,
5640 
5641     // void __atomic_store(A *, CP, int)
5642     Copy,
5643 
5644     // C    __c11_atomic_add(A *, M, int)
5645     Arithmetic,
5646 
5647     // C    __atomic_exchange_n(A *, CP, int)
5648     Xchg,
5649 
5650     // void __atomic_exchange(A *, C *, CP, int)
5651     GNUXchg,
5652 
5653     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5654     C11CmpXchg,
5655 
5656     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5657     GNUCmpXchg
5658   } Form = Init;
5659 
5660   const unsigned NumForm = GNUCmpXchg + 1;
5661   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5662   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5663   // where:
5664   //   C is an appropriate type,
5665   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5666   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5667   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5668   //   the int parameters are for orderings.
5669 
5670   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5671       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5672       "need to update code for modified forms");
5673   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5674                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5675                         AtomicExpr::AO__atomic_load,
5676                 "need to update code for modified C11 atomics");
5677   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5678                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5679   bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load &&
5680                Op <= AtomicExpr::AO__hip_atomic_fetch_max;
5681   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5682                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5683                IsOpenCL;
5684   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5685              Op == AtomicExpr::AO__atomic_store_n ||
5686              Op == AtomicExpr::AO__atomic_exchange_n ||
5687              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5688   bool IsAddSub = false;
5689 
5690   switch (Op) {
5691   case AtomicExpr::AO__c11_atomic_init:
5692   case AtomicExpr::AO__opencl_atomic_init:
5693     Form = Init;
5694     break;
5695 
5696   case AtomicExpr::AO__c11_atomic_load:
5697   case AtomicExpr::AO__opencl_atomic_load:
5698   case AtomicExpr::AO__hip_atomic_load:
5699   case AtomicExpr::AO__atomic_load_n:
5700     Form = Load;
5701     break;
5702 
5703   case AtomicExpr::AO__atomic_load:
5704     Form = LoadCopy;
5705     break;
5706 
5707   case AtomicExpr::AO__c11_atomic_store:
5708   case AtomicExpr::AO__opencl_atomic_store:
5709   case AtomicExpr::AO__hip_atomic_store:
5710   case AtomicExpr::AO__atomic_store:
5711   case AtomicExpr::AO__atomic_store_n:
5712     Form = Copy;
5713     break;
5714   case AtomicExpr::AO__hip_atomic_fetch_add:
5715   case AtomicExpr::AO__hip_atomic_fetch_min:
5716   case AtomicExpr::AO__hip_atomic_fetch_max:
5717   case AtomicExpr::AO__c11_atomic_fetch_add:
5718   case AtomicExpr::AO__c11_atomic_fetch_sub:
5719   case AtomicExpr::AO__opencl_atomic_fetch_add:
5720   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5721   case AtomicExpr::AO__atomic_fetch_add:
5722   case AtomicExpr::AO__atomic_fetch_sub:
5723   case AtomicExpr::AO__atomic_add_fetch:
5724   case AtomicExpr::AO__atomic_sub_fetch:
5725     IsAddSub = true;
5726     Form = Arithmetic;
5727     break;
5728   case AtomicExpr::AO__c11_atomic_fetch_and:
5729   case AtomicExpr::AO__c11_atomic_fetch_or:
5730   case AtomicExpr::AO__c11_atomic_fetch_xor:
5731   case AtomicExpr::AO__hip_atomic_fetch_and:
5732   case AtomicExpr::AO__hip_atomic_fetch_or:
5733   case AtomicExpr::AO__hip_atomic_fetch_xor:
5734   case AtomicExpr::AO__c11_atomic_fetch_nand:
5735   case AtomicExpr::AO__opencl_atomic_fetch_and:
5736   case AtomicExpr::AO__opencl_atomic_fetch_or:
5737   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5738   case AtomicExpr::AO__atomic_fetch_and:
5739   case AtomicExpr::AO__atomic_fetch_or:
5740   case AtomicExpr::AO__atomic_fetch_xor:
5741   case AtomicExpr::AO__atomic_fetch_nand:
5742   case AtomicExpr::AO__atomic_and_fetch:
5743   case AtomicExpr::AO__atomic_or_fetch:
5744   case AtomicExpr::AO__atomic_xor_fetch:
5745   case AtomicExpr::AO__atomic_nand_fetch:
5746     Form = Arithmetic;
5747     break;
5748   case AtomicExpr::AO__c11_atomic_fetch_min:
5749   case AtomicExpr::AO__c11_atomic_fetch_max:
5750   case AtomicExpr::AO__opencl_atomic_fetch_min:
5751   case AtomicExpr::AO__opencl_atomic_fetch_max:
5752   case AtomicExpr::AO__atomic_min_fetch:
5753   case AtomicExpr::AO__atomic_max_fetch:
5754   case AtomicExpr::AO__atomic_fetch_min:
5755   case AtomicExpr::AO__atomic_fetch_max:
5756     Form = Arithmetic;
5757     break;
5758 
5759   case AtomicExpr::AO__c11_atomic_exchange:
5760   case AtomicExpr::AO__hip_atomic_exchange:
5761   case AtomicExpr::AO__opencl_atomic_exchange:
5762   case AtomicExpr::AO__atomic_exchange_n:
5763     Form = Xchg;
5764     break;
5765 
5766   case AtomicExpr::AO__atomic_exchange:
5767     Form = GNUXchg;
5768     break;
5769 
5770   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5771   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5772   case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5773   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5774   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5775   case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5776     Form = C11CmpXchg;
5777     break;
5778 
5779   case AtomicExpr::AO__atomic_compare_exchange:
5780   case AtomicExpr::AO__atomic_compare_exchange_n:
5781     Form = GNUCmpXchg;
5782     break;
5783   }
5784 
5785   unsigned AdjustedNumArgs = NumArgs[Form];
5786   if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init)
5787     ++AdjustedNumArgs;
5788   // Check we have the right number of arguments.
5789   if (Args.size() < AdjustedNumArgs) {
5790     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5791         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5792         << ExprRange;
5793     return ExprError();
5794   } else if (Args.size() > AdjustedNumArgs) {
5795     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5796          diag::err_typecheck_call_too_many_args)
5797         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5798         << ExprRange;
5799     return ExprError();
5800   }
5801 
5802   // Inspect the first argument of the atomic operation.
5803   Expr *Ptr = Args[0];
5804   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5805   if (ConvertedPtr.isInvalid())
5806     return ExprError();
5807 
5808   Ptr = ConvertedPtr.get();
5809   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5810   if (!pointerType) {
5811     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5812         << Ptr->getType() << Ptr->getSourceRange();
5813     return ExprError();
5814   }
5815 
5816   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5817   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5818   QualType ValType = AtomTy; // 'C'
5819   if (IsC11) {
5820     if (!AtomTy->isAtomicType()) {
5821       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5822           << Ptr->getType() << Ptr->getSourceRange();
5823       return ExprError();
5824     }
5825     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5826         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5827       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5828           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5829           << Ptr->getSourceRange();
5830       return ExprError();
5831     }
5832     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5833   } else if (Form != Load && Form != LoadCopy) {
5834     if (ValType.isConstQualified()) {
5835       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5836           << Ptr->getType() << Ptr->getSourceRange();
5837       return ExprError();
5838     }
5839   }
5840 
5841   // For an arithmetic operation, the implied arithmetic must be well-formed.
5842   if (Form == Arithmetic) {
5843     // GCC does not enforce these rules for GNU atomics, but we do to help catch
5844     // trivial type errors.
5845     auto IsAllowedValueType = [&](QualType ValType) {
5846       if (ValType->isIntegerType())
5847         return true;
5848       if (ValType->isPointerType())
5849         return true;
5850       if (!ValType->isFloatingType())
5851         return false;
5852       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5853       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5854           &Context.getTargetInfo().getLongDoubleFormat() ==
5855               &llvm::APFloat::x87DoubleExtended())
5856         return false;
5857       return true;
5858     };
5859     if (IsAddSub && !IsAllowedValueType(ValType)) {
5860       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5861           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5862       return ExprError();
5863     }
5864     if (!IsAddSub && !ValType->isIntegerType()) {
5865       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5866           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5867       return ExprError();
5868     }
5869     if (IsC11 && ValType->isPointerType() &&
5870         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5871                             diag::err_incomplete_type)) {
5872       return ExprError();
5873     }
5874   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5875     // For __atomic_*_n operations, the value type must be a scalar integral or
5876     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5877     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5878         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5879     return ExprError();
5880   }
5881 
5882   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5883       !AtomTy->isScalarType()) {
5884     // For GNU atomics, require a trivially-copyable type. This is not part of
5885     // the GNU atomics specification but we enforce it for consistency with
5886     // other atomics which generally all require a trivially-copyable type. This
5887     // is because atomics just copy bits.
5888     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5889         << Ptr->getType() << Ptr->getSourceRange();
5890     return ExprError();
5891   }
5892 
5893   switch (ValType.getObjCLifetime()) {
5894   case Qualifiers::OCL_None:
5895   case Qualifiers::OCL_ExplicitNone:
5896     // okay
5897     break;
5898 
5899   case Qualifiers::OCL_Weak:
5900   case Qualifiers::OCL_Strong:
5901   case Qualifiers::OCL_Autoreleasing:
5902     // FIXME: Can this happen? By this point, ValType should be known
5903     // to be trivially copyable.
5904     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5905         << ValType << Ptr->getSourceRange();
5906     return ExprError();
5907   }
5908 
5909   // All atomic operations have an overload which takes a pointer to a volatile
5910   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5911   // into the result or the other operands. Similarly atomic_load takes a
5912   // pointer to a const 'A'.
5913   ValType.removeLocalVolatile();
5914   ValType.removeLocalConst();
5915   QualType ResultType = ValType;
5916   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5917       Form == Init)
5918     ResultType = Context.VoidTy;
5919   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5920     ResultType = Context.BoolTy;
5921 
5922   // The type of a parameter passed 'by value'. In the GNU atomics, such
5923   // arguments are actually passed as pointers.
5924   QualType ByValType = ValType; // 'CP'
5925   bool IsPassedByAddress = false;
5926   if (!IsC11 && !IsHIP && !IsN) {
5927     ByValType = Ptr->getType();
5928     IsPassedByAddress = true;
5929   }
5930 
5931   SmallVector<Expr *, 5> APIOrderedArgs;
5932   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5933     APIOrderedArgs.push_back(Args[0]);
5934     switch (Form) {
5935     case Init:
5936     case Load:
5937       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5938       break;
5939     case LoadCopy:
5940     case Copy:
5941     case Arithmetic:
5942     case Xchg:
5943       APIOrderedArgs.push_back(Args[2]); // Val1
5944       APIOrderedArgs.push_back(Args[1]); // Order
5945       break;
5946     case GNUXchg:
5947       APIOrderedArgs.push_back(Args[2]); // Val1
5948       APIOrderedArgs.push_back(Args[3]); // Val2
5949       APIOrderedArgs.push_back(Args[1]); // Order
5950       break;
5951     case C11CmpXchg:
5952       APIOrderedArgs.push_back(Args[2]); // Val1
5953       APIOrderedArgs.push_back(Args[4]); // Val2
5954       APIOrderedArgs.push_back(Args[1]); // Order
5955       APIOrderedArgs.push_back(Args[3]); // OrderFail
5956       break;
5957     case GNUCmpXchg:
5958       APIOrderedArgs.push_back(Args[2]); // Val1
5959       APIOrderedArgs.push_back(Args[4]); // Val2
5960       APIOrderedArgs.push_back(Args[5]); // Weak
5961       APIOrderedArgs.push_back(Args[1]); // Order
5962       APIOrderedArgs.push_back(Args[3]); // OrderFail
5963       break;
5964     }
5965   } else
5966     APIOrderedArgs.append(Args.begin(), Args.end());
5967 
5968   // The first argument's non-CV pointer type is used to deduce the type of
5969   // subsequent arguments, except for:
5970   //  - weak flag (always converted to bool)
5971   //  - memory order (always converted to int)
5972   //  - scope  (always converted to int)
5973   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5974     QualType Ty;
5975     if (i < NumVals[Form] + 1) {
5976       switch (i) {
5977       case 0:
5978         // The first argument is always a pointer. It has a fixed type.
5979         // It is always dereferenced, a nullptr is undefined.
5980         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5981         // Nothing else to do: we already know all we want about this pointer.
5982         continue;
5983       case 1:
5984         // The second argument is the non-atomic operand. For arithmetic, this
5985         // is always passed by value, and for a compare_exchange it is always
5986         // passed by address. For the rest, GNU uses by-address and C11 uses
5987         // by-value.
5988         assert(Form != Load);
5989         if (Form == Arithmetic && ValType->isPointerType())
5990           Ty = Context.getPointerDiffType();
5991         else if (Form == Init || Form == Arithmetic)
5992           Ty = ValType;
5993         else if (Form == Copy || Form == Xchg) {
5994           if (IsPassedByAddress) {
5995             // The value pointer is always dereferenced, a nullptr is undefined.
5996             CheckNonNullArgument(*this, APIOrderedArgs[i],
5997                                  ExprRange.getBegin());
5998           }
5999           Ty = ByValType;
6000         } else {
6001           Expr *ValArg = APIOrderedArgs[i];
6002           // The value pointer is always dereferenced, a nullptr is undefined.
6003           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
6004           LangAS AS = LangAS::Default;
6005           // Keep address space of non-atomic pointer type.
6006           if (const PointerType *PtrTy =
6007                   ValArg->getType()->getAs<PointerType>()) {
6008             AS = PtrTy->getPointeeType().getAddressSpace();
6009           }
6010           Ty = Context.getPointerType(
6011               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
6012         }
6013         break;
6014       case 2:
6015         // The third argument to compare_exchange / GNU exchange is the desired
6016         // value, either by-value (for the C11 and *_n variant) or as a pointer.
6017         if (IsPassedByAddress)
6018           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
6019         Ty = ByValType;
6020         break;
6021       case 3:
6022         // The fourth argument to GNU compare_exchange is a 'weak' flag.
6023         Ty = Context.BoolTy;
6024         break;
6025       }
6026     } else {
6027       // The order(s) and scope are always converted to int.
6028       Ty = Context.IntTy;
6029     }
6030 
6031     InitializedEntity Entity =
6032         InitializedEntity::InitializeParameter(Context, Ty, false);
6033     ExprResult Arg = APIOrderedArgs[i];
6034     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6035     if (Arg.isInvalid())
6036       return true;
6037     APIOrderedArgs[i] = Arg.get();
6038   }
6039 
6040   // Permute the arguments into a 'consistent' order.
6041   SmallVector<Expr*, 5> SubExprs;
6042   SubExprs.push_back(Ptr);
6043   switch (Form) {
6044   case Init:
6045     // Note, AtomicExpr::getVal1() has a special case for this atomic.
6046     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6047     break;
6048   case Load:
6049     SubExprs.push_back(APIOrderedArgs[1]); // Order
6050     break;
6051   case LoadCopy:
6052   case Copy:
6053   case Arithmetic:
6054   case Xchg:
6055     SubExprs.push_back(APIOrderedArgs[2]); // Order
6056     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6057     break;
6058   case GNUXchg:
6059     // Note, AtomicExpr::getVal2() has a special case for this atomic.
6060     SubExprs.push_back(APIOrderedArgs[3]); // Order
6061     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6062     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6063     break;
6064   case C11CmpXchg:
6065     SubExprs.push_back(APIOrderedArgs[3]); // Order
6066     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6067     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
6068     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6069     break;
6070   case GNUCmpXchg:
6071     SubExprs.push_back(APIOrderedArgs[4]); // Order
6072     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6073     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
6074     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6075     SubExprs.push_back(APIOrderedArgs[3]); // Weak
6076     break;
6077   }
6078 
6079   if (SubExprs.size() >= 2 && Form != Init) {
6080     if (Optional<llvm::APSInt> Result =
6081             SubExprs[1]->getIntegerConstantExpr(Context))
6082       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
6083         Diag(SubExprs[1]->getBeginLoc(),
6084              diag::warn_atomic_op_has_invalid_memory_order)
6085             << SubExprs[1]->getSourceRange();
6086   }
6087 
6088   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
6089     auto *Scope = Args[Args.size() - 1];
6090     if (Optional<llvm::APSInt> Result =
6091             Scope->getIntegerConstantExpr(Context)) {
6092       if (!ScopeModel->isValid(Result->getZExtValue()))
6093         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
6094             << Scope->getSourceRange();
6095     }
6096     SubExprs.push_back(Scope);
6097   }
6098 
6099   AtomicExpr *AE = new (Context)
6100       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
6101 
6102   if ((Op == AtomicExpr::AO__c11_atomic_load ||
6103        Op == AtomicExpr::AO__c11_atomic_store ||
6104        Op == AtomicExpr::AO__opencl_atomic_load ||
6105        Op == AtomicExpr::AO__hip_atomic_load ||
6106        Op == AtomicExpr::AO__opencl_atomic_store ||
6107        Op == AtomicExpr::AO__hip_atomic_store) &&
6108       Context.AtomicUsesUnsupportedLibcall(AE))
6109     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
6110         << ((Op == AtomicExpr::AO__c11_atomic_load ||
6111              Op == AtomicExpr::AO__opencl_atomic_load ||
6112              Op == AtomicExpr::AO__hip_atomic_load)
6113                 ? 0
6114                 : 1);
6115 
6116   if (ValType->isBitIntType()) {
6117     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
6118     return ExprError();
6119   }
6120 
6121   return AE;
6122 }
6123 
6124 /// checkBuiltinArgument - Given a call to a builtin function, perform
6125 /// normal type-checking on the given argument, updating the call in
6126 /// place.  This is useful when a builtin function requires custom
6127 /// type-checking for some of its arguments but not necessarily all of
6128 /// them.
6129 ///
6130 /// Returns true on error.
6131 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
6132   FunctionDecl *Fn = E->getDirectCallee();
6133   assert(Fn && "builtin call without direct callee!");
6134 
6135   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
6136   InitializedEntity Entity =
6137     InitializedEntity::InitializeParameter(S.Context, Param);
6138 
6139   ExprResult Arg = E->getArg(0);
6140   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
6141   if (Arg.isInvalid())
6142     return true;
6143 
6144   E->setArg(ArgIndex, Arg.get());
6145   return false;
6146 }
6147 
6148 /// We have a call to a function like __sync_fetch_and_add, which is an
6149 /// overloaded function based on the pointer type of its first argument.
6150 /// The main BuildCallExpr routines have already promoted the types of
6151 /// arguments because all of these calls are prototyped as void(...).
6152 ///
6153 /// This function goes through and does final semantic checking for these
6154 /// builtins, as well as generating any warnings.
6155 ExprResult
6156 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
6157   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
6158   Expr *Callee = TheCall->getCallee();
6159   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
6160   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6161 
6162   // Ensure that we have at least one argument to do type inference from.
6163   if (TheCall->getNumArgs() < 1) {
6164     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6165         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
6166     return ExprError();
6167   }
6168 
6169   // Inspect the first argument of the atomic builtin.  This should always be
6170   // a pointer type, whose element is an integral scalar or pointer type.
6171   // Because it is a pointer type, we don't have to worry about any implicit
6172   // casts here.
6173   // FIXME: We don't allow floating point scalars as input.
6174   Expr *FirstArg = TheCall->getArg(0);
6175   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
6176   if (FirstArgResult.isInvalid())
6177     return ExprError();
6178   FirstArg = FirstArgResult.get();
6179   TheCall->setArg(0, FirstArg);
6180 
6181   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
6182   if (!pointerType) {
6183     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
6184         << FirstArg->getType() << FirstArg->getSourceRange();
6185     return ExprError();
6186   }
6187 
6188   QualType ValType = pointerType->getPointeeType();
6189   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6190       !ValType->isBlockPointerType()) {
6191     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
6192         << FirstArg->getType() << FirstArg->getSourceRange();
6193     return ExprError();
6194   }
6195 
6196   if (ValType.isConstQualified()) {
6197     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
6198         << FirstArg->getType() << FirstArg->getSourceRange();
6199     return ExprError();
6200   }
6201 
6202   switch (ValType.getObjCLifetime()) {
6203   case Qualifiers::OCL_None:
6204   case Qualifiers::OCL_ExplicitNone:
6205     // okay
6206     break;
6207 
6208   case Qualifiers::OCL_Weak:
6209   case Qualifiers::OCL_Strong:
6210   case Qualifiers::OCL_Autoreleasing:
6211     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
6212         << ValType << FirstArg->getSourceRange();
6213     return ExprError();
6214   }
6215 
6216   // Strip any qualifiers off ValType.
6217   ValType = ValType.getUnqualifiedType();
6218 
6219   // The majority of builtins return a value, but a few have special return
6220   // types, so allow them to override appropriately below.
6221   QualType ResultType = ValType;
6222 
6223   // We need to figure out which concrete builtin this maps onto.  For example,
6224   // __sync_fetch_and_add with a 2 byte object turns into
6225   // __sync_fetch_and_add_2.
6226 #define BUILTIN_ROW(x) \
6227   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
6228     Builtin::BI##x##_8, Builtin::BI##x##_16 }
6229 
6230   static const unsigned BuiltinIndices[][5] = {
6231     BUILTIN_ROW(__sync_fetch_and_add),
6232     BUILTIN_ROW(__sync_fetch_and_sub),
6233     BUILTIN_ROW(__sync_fetch_and_or),
6234     BUILTIN_ROW(__sync_fetch_and_and),
6235     BUILTIN_ROW(__sync_fetch_and_xor),
6236     BUILTIN_ROW(__sync_fetch_and_nand),
6237 
6238     BUILTIN_ROW(__sync_add_and_fetch),
6239     BUILTIN_ROW(__sync_sub_and_fetch),
6240     BUILTIN_ROW(__sync_and_and_fetch),
6241     BUILTIN_ROW(__sync_or_and_fetch),
6242     BUILTIN_ROW(__sync_xor_and_fetch),
6243     BUILTIN_ROW(__sync_nand_and_fetch),
6244 
6245     BUILTIN_ROW(__sync_val_compare_and_swap),
6246     BUILTIN_ROW(__sync_bool_compare_and_swap),
6247     BUILTIN_ROW(__sync_lock_test_and_set),
6248     BUILTIN_ROW(__sync_lock_release),
6249     BUILTIN_ROW(__sync_swap)
6250   };
6251 #undef BUILTIN_ROW
6252 
6253   // Determine the index of the size.
6254   unsigned SizeIndex;
6255   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
6256   case 1: SizeIndex = 0; break;
6257   case 2: SizeIndex = 1; break;
6258   case 4: SizeIndex = 2; break;
6259   case 8: SizeIndex = 3; break;
6260   case 16: SizeIndex = 4; break;
6261   default:
6262     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
6263         << FirstArg->getType() << FirstArg->getSourceRange();
6264     return ExprError();
6265   }
6266 
6267   // Each of these builtins has one pointer argument, followed by some number of
6268   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
6269   // that we ignore.  Find out which row of BuiltinIndices to read from as well
6270   // as the number of fixed args.
6271   unsigned BuiltinID = FDecl->getBuiltinID();
6272   unsigned BuiltinIndex, NumFixed = 1;
6273   bool WarnAboutSemanticsChange = false;
6274   switch (BuiltinID) {
6275   default: llvm_unreachable("Unknown overloaded atomic builtin!");
6276   case Builtin::BI__sync_fetch_and_add:
6277   case Builtin::BI__sync_fetch_and_add_1:
6278   case Builtin::BI__sync_fetch_and_add_2:
6279   case Builtin::BI__sync_fetch_and_add_4:
6280   case Builtin::BI__sync_fetch_and_add_8:
6281   case Builtin::BI__sync_fetch_and_add_16:
6282     BuiltinIndex = 0;
6283     break;
6284 
6285   case Builtin::BI__sync_fetch_and_sub:
6286   case Builtin::BI__sync_fetch_and_sub_1:
6287   case Builtin::BI__sync_fetch_and_sub_2:
6288   case Builtin::BI__sync_fetch_and_sub_4:
6289   case Builtin::BI__sync_fetch_and_sub_8:
6290   case Builtin::BI__sync_fetch_and_sub_16:
6291     BuiltinIndex = 1;
6292     break;
6293 
6294   case Builtin::BI__sync_fetch_and_or:
6295   case Builtin::BI__sync_fetch_and_or_1:
6296   case Builtin::BI__sync_fetch_and_or_2:
6297   case Builtin::BI__sync_fetch_and_or_4:
6298   case Builtin::BI__sync_fetch_and_or_8:
6299   case Builtin::BI__sync_fetch_and_or_16:
6300     BuiltinIndex = 2;
6301     break;
6302 
6303   case Builtin::BI__sync_fetch_and_and:
6304   case Builtin::BI__sync_fetch_and_and_1:
6305   case Builtin::BI__sync_fetch_and_and_2:
6306   case Builtin::BI__sync_fetch_and_and_4:
6307   case Builtin::BI__sync_fetch_and_and_8:
6308   case Builtin::BI__sync_fetch_and_and_16:
6309     BuiltinIndex = 3;
6310     break;
6311 
6312   case Builtin::BI__sync_fetch_and_xor:
6313   case Builtin::BI__sync_fetch_and_xor_1:
6314   case Builtin::BI__sync_fetch_and_xor_2:
6315   case Builtin::BI__sync_fetch_and_xor_4:
6316   case Builtin::BI__sync_fetch_and_xor_8:
6317   case Builtin::BI__sync_fetch_and_xor_16:
6318     BuiltinIndex = 4;
6319     break;
6320 
6321   case Builtin::BI__sync_fetch_and_nand:
6322   case Builtin::BI__sync_fetch_and_nand_1:
6323   case Builtin::BI__sync_fetch_and_nand_2:
6324   case Builtin::BI__sync_fetch_and_nand_4:
6325   case Builtin::BI__sync_fetch_and_nand_8:
6326   case Builtin::BI__sync_fetch_and_nand_16:
6327     BuiltinIndex = 5;
6328     WarnAboutSemanticsChange = true;
6329     break;
6330 
6331   case Builtin::BI__sync_add_and_fetch:
6332   case Builtin::BI__sync_add_and_fetch_1:
6333   case Builtin::BI__sync_add_and_fetch_2:
6334   case Builtin::BI__sync_add_and_fetch_4:
6335   case Builtin::BI__sync_add_and_fetch_8:
6336   case Builtin::BI__sync_add_and_fetch_16:
6337     BuiltinIndex = 6;
6338     break;
6339 
6340   case Builtin::BI__sync_sub_and_fetch:
6341   case Builtin::BI__sync_sub_and_fetch_1:
6342   case Builtin::BI__sync_sub_and_fetch_2:
6343   case Builtin::BI__sync_sub_and_fetch_4:
6344   case Builtin::BI__sync_sub_and_fetch_8:
6345   case Builtin::BI__sync_sub_and_fetch_16:
6346     BuiltinIndex = 7;
6347     break;
6348 
6349   case Builtin::BI__sync_and_and_fetch:
6350   case Builtin::BI__sync_and_and_fetch_1:
6351   case Builtin::BI__sync_and_and_fetch_2:
6352   case Builtin::BI__sync_and_and_fetch_4:
6353   case Builtin::BI__sync_and_and_fetch_8:
6354   case Builtin::BI__sync_and_and_fetch_16:
6355     BuiltinIndex = 8;
6356     break;
6357 
6358   case Builtin::BI__sync_or_and_fetch:
6359   case Builtin::BI__sync_or_and_fetch_1:
6360   case Builtin::BI__sync_or_and_fetch_2:
6361   case Builtin::BI__sync_or_and_fetch_4:
6362   case Builtin::BI__sync_or_and_fetch_8:
6363   case Builtin::BI__sync_or_and_fetch_16:
6364     BuiltinIndex = 9;
6365     break;
6366 
6367   case Builtin::BI__sync_xor_and_fetch:
6368   case Builtin::BI__sync_xor_and_fetch_1:
6369   case Builtin::BI__sync_xor_and_fetch_2:
6370   case Builtin::BI__sync_xor_and_fetch_4:
6371   case Builtin::BI__sync_xor_and_fetch_8:
6372   case Builtin::BI__sync_xor_and_fetch_16:
6373     BuiltinIndex = 10;
6374     break;
6375 
6376   case Builtin::BI__sync_nand_and_fetch:
6377   case Builtin::BI__sync_nand_and_fetch_1:
6378   case Builtin::BI__sync_nand_and_fetch_2:
6379   case Builtin::BI__sync_nand_and_fetch_4:
6380   case Builtin::BI__sync_nand_and_fetch_8:
6381   case Builtin::BI__sync_nand_and_fetch_16:
6382     BuiltinIndex = 11;
6383     WarnAboutSemanticsChange = true;
6384     break;
6385 
6386   case Builtin::BI__sync_val_compare_and_swap:
6387   case Builtin::BI__sync_val_compare_and_swap_1:
6388   case Builtin::BI__sync_val_compare_and_swap_2:
6389   case Builtin::BI__sync_val_compare_and_swap_4:
6390   case Builtin::BI__sync_val_compare_and_swap_8:
6391   case Builtin::BI__sync_val_compare_and_swap_16:
6392     BuiltinIndex = 12;
6393     NumFixed = 2;
6394     break;
6395 
6396   case Builtin::BI__sync_bool_compare_and_swap:
6397   case Builtin::BI__sync_bool_compare_and_swap_1:
6398   case Builtin::BI__sync_bool_compare_and_swap_2:
6399   case Builtin::BI__sync_bool_compare_and_swap_4:
6400   case Builtin::BI__sync_bool_compare_and_swap_8:
6401   case Builtin::BI__sync_bool_compare_and_swap_16:
6402     BuiltinIndex = 13;
6403     NumFixed = 2;
6404     ResultType = Context.BoolTy;
6405     break;
6406 
6407   case Builtin::BI__sync_lock_test_and_set:
6408   case Builtin::BI__sync_lock_test_and_set_1:
6409   case Builtin::BI__sync_lock_test_and_set_2:
6410   case Builtin::BI__sync_lock_test_and_set_4:
6411   case Builtin::BI__sync_lock_test_and_set_8:
6412   case Builtin::BI__sync_lock_test_and_set_16:
6413     BuiltinIndex = 14;
6414     break;
6415 
6416   case Builtin::BI__sync_lock_release:
6417   case Builtin::BI__sync_lock_release_1:
6418   case Builtin::BI__sync_lock_release_2:
6419   case Builtin::BI__sync_lock_release_4:
6420   case Builtin::BI__sync_lock_release_8:
6421   case Builtin::BI__sync_lock_release_16:
6422     BuiltinIndex = 15;
6423     NumFixed = 0;
6424     ResultType = Context.VoidTy;
6425     break;
6426 
6427   case Builtin::BI__sync_swap:
6428   case Builtin::BI__sync_swap_1:
6429   case Builtin::BI__sync_swap_2:
6430   case Builtin::BI__sync_swap_4:
6431   case Builtin::BI__sync_swap_8:
6432   case Builtin::BI__sync_swap_16:
6433     BuiltinIndex = 16;
6434     break;
6435   }
6436 
6437   // Now that we know how many fixed arguments we expect, first check that we
6438   // have at least that many.
6439   if (TheCall->getNumArgs() < 1+NumFixed) {
6440     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6441         << 0 << 1 + NumFixed << TheCall->getNumArgs()
6442         << Callee->getSourceRange();
6443     return ExprError();
6444   }
6445 
6446   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6447       << Callee->getSourceRange();
6448 
6449   if (WarnAboutSemanticsChange) {
6450     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6451         << Callee->getSourceRange();
6452   }
6453 
6454   // Get the decl for the concrete builtin from this, we can tell what the
6455   // concrete integer type we should convert to is.
6456   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6457   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6458   FunctionDecl *NewBuiltinDecl;
6459   if (NewBuiltinID == BuiltinID)
6460     NewBuiltinDecl = FDecl;
6461   else {
6462     // Perform builtin lookup to avoid redeclaring it.
6463     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6464     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6465     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6466     assert(Res.getFoundDecl());
6467     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6468     if (!NewBuiltinDecl)
6469       return ExprError();
6470   }
6471 
6472   // The first argument --- the pointer --- has a fixed type; we
6473   // deduce the types of the rest of the arguments accordingly.  Walk
6474   // the remaining arguments, converting them to the deduced value type.
6475   for (unsigned i = 0; i != NumFixed; ++i) {
6476     ExprResult Arg = TheCall->getArg(i+1);
6477 
6478     // GCC does an implicit conversion to the pointer or integer ValType.  This
6479     // can fail in some cases (1i -> int**), check for this error case now.
6480     // Initialize the argument.
6481     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6482                                                    ValType, /*consume*/ false);
6483     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6484     if (Arg.isInvalid())
6485       return ExprError();
6486 
6487     // Okay, we have something that *can* be converted to the right type.  Check
6488     // to see if there is a potentially weird extension going on here.  This can
6489     // happen when you do an atomic operation on something like an char* and
6490     // pass in 42.  The 42 gets converted to char.  This is even more strange
6491     // for things like 45.123 -> char, etc.
6492     // FIXME: Do this check.
6493     TheCall->setArg(i+1, Arg.get());
6494   }
6495 
6496   // Create a new DeclRefExpr to refer to the new decl.
6497   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6498       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6499       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6500       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6501 
6502   // Set the callee in the CallExpr.
6503   // FIXME: This loses syntactic information.
6504   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6505   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6506                                               CK_BuiltinFnToFnPtr);
6507   TheCall->setCallee(PromotedCall.get());
6508 
6509   // Change the result type of the call to match the original value type. This
6510   // is arbitrary, but the codegen for these builtins ins design to handle it
6511   // gracefully.
6512   TheCall->setType(ResultType);
6513 
6514   // Prohibit problematic uses of bit-precise integer types with atomic
6515   // builtins. The arguments would have already been converted to the first
6516   // argument's type, so only need to check the first argument.
6517   const auto *BitIntValType = ValType->getAs<BitIntType>();
6518   if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
6519     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6520     return ExprError();
6521   }
6522 
6523   return TheCallResult;
6524 }
6525 
6526 /// SemaBuiltinNontemporalOverloaded - We have a call to
6527 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6528 /// overloaded function based on the pointer type of its last argument.
6529 ///
6530 /// This function goes through and does final semantic checking for these
6531 /// builtins.
6532 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6533   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6534   DeclRefExpr *DRE =
6535       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6536   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6537   unsigned BuiltinID = FDecl->getBuiltinID();
6538   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6539           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6540          "Unexpected nontemporal load/store builtin!");
6541   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6542   unsigned numArgs = isStore ? 2 : 1;
6543 
6544   // Ensure that we have the proper number of arguments.
6545   if (checkArgCount(*this, TheCall, numArgs))
6546     return ExprError();
6547 
6548   // Inspect the last argument of the nontemporal builtin.  This should always
6549   // be a pointer type, from which we imply the type of the memory access.
6550   // Because it is a pointer type, we don't have to worry about any implicit
6551   // casts here.
6552   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6553   ExprResult PointerArgResult =
6554       DefaultFunctionArrayLvalueConversion(PointerArg);
6555 
6556   if (PointerArgResult.isInvalid())
6557     return ExprError();
6558   PointerArg = PointerArgResult.get();
6559   TheCall->setArg(numArgs - 1, PointerArg);
6560 
6561   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6562   if (!pointerType) {
6563     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6564         << PointerArg->getType() << PointerArg->getSourceRange();
6565     return ExprError();
6566   }
6567 
6568   QualType ValType = pointerType->getPointeeType();
6569 
6570   // Strip any qualifiers off ValType.
6571   ValType = ValType.getUnqualifiedType();
6572   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6573       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6574       !ValType->isVectorType()) {
6575     Diag(DRE->getBeginLoc(),
6576          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6577         << PointerArg->getType() << PointerArg->getSourceRange();
6578     return ExprError();
6579   }
6580 
6581   if (!isStore) {
6582     TheCall->setType(ValType);
6583     return TheCallResult;
6584   }
6585 
6586   ExprResult ValArg = TheCall->getArg(0);
6587   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6588       Context, ValType, /*consume*/ false);
6589   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6590   if (ValArg.isInvalid())
6591     return ExprError();
6592 
6593   TheCall->setArg(0, ValArg.get());
6594   TheCall->setType(Context.VoidTy);
6595   return TheCallResult;
6596 }
6597 
6598 /// CheckObjCString - Checks that the argument to the builtin
6599 /// CFString constructor is correct
6600 /// Note: It might also make sense to do the UTF-16 conversion here (would
6601 /// simplify the backend).
6602 bool Sema::CheckObjCString(Expr *Arg) {
6603   Arg = Arg->IgnoreParenCasts();
6604   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6605 
6606   if (!Literal || !Literal->isAscii()) {
6607     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6608         << Arg->getSourceRange();
6609     return true;
6610   }
6611 
6612   if (Literal->containsNonAsciiOrNull()) {
6613     StringRef String = Literal->getString();
6614     unsigned NumBytes = String.size();
6615     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6616     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6617     llvm::UTF16 *ToPtr = &ToBuf[0];
6618 
6619     llvm::ConversionResult Result =
6620         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6621                                  ToPtr + NumBytes, llvm::strictConversion);
6622     // Check for conversion failure.
6623     if (Result != llvm::conversionOK)
6624       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6625           << Arg->getSourceRange();
6626   }
6627   return false;
6628 }
6629 
6630 /// CheckObjCString - Checks that the format string argument to the os_log()
6631 /// and os_trace() functions is correct, and converts it to const char *.
6632 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6633   Arg = Arg->IgnoreParenCasts();
6634   auto *Literal = dyn_cast<StringLiteral>(Arg);
6635   if (!Literal) {
6636     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6637       Literal = ObjcLiteral->getString();
6638     }
6639   }
6640 
6641   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6642     return ExprError(
6643         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6644         << Arg->getSourceRange());
6645   }
6646 
6647   ExprResult Result(Literal);
6648   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6649   InitializedEntity Entity =
6650       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6651   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6652   return Result;
6653 }
6654 
6655 /// Check that the user is calling the appropriate va_start builtin for the
6656 /// target and calling convention.
6657 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6658   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6659   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6660   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6661                     TT.getArch() == llvm::Triple::aarch64_32);
6662   bool IsWindows = TT.isOSWindows();
6663   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6664   if (IsX64 || IsAArch64) {
6665     CallingConv CC = CC_C;
6666     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6667       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6668     if (IsMSVAStart) {
6669       // Don't allow this in System V ABI functions.
6670       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6671         return S.Diag(Fn->getBeginLoc(),
6672                       diag::err_ms_va_start_used_in_sysv_function);
6673     } else {
6674       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6675       // On x64 Windows, don't allow this in System V ABI functions.
6676       // (Yes, that means there's no corresponding way to support variadic
6677       // System V ABI functions on Windows.)
6678       if ((IsWindows && CC == CC_X86_64SysV) ||
6679           (!IsWindows && CC == CC_Win64))
6680         return S.Diag(Fn->getBeginLoc(),
6681                       diag::err_va_start_used_in_wrong_abi_function)
6682                << !IsWindows;
6683     }
6684     return false;
6685   }
6686 
6687   if (IsMSVAStart)
6688     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6689   return false;
6690 }
6691 
6692 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6693                                              ParmVarDecl **LastParam = nullptr) {
6694   // Determine whether the current function, block, or obj-c method is variadic
6695   // and get its parameter list.
6696   bool IsVariadic = false;
6697   ArrayRef<ParmVarDecl *> Params;
6698   DeclContext *Caller = S.CurContext;
6699   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6700     IsVariadic = Block->isVariadic();
6701     Params = Block->parameters();
6702   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6703     IsVariadic = FD->isVariadic();
6704     Params = FD->parameters();
6705   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6706     IsVariadic = MD->isVariadic();
6707     // FIXME: This isn't correct for methods (results in bogus warning).
6708     Params = MD->parameters();
6709   } else if (isa<CapturedDecl>(Caller)) {
6710     // We don't support va_start in a CapturedDecl.
6711     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6712     return true;
6713   } else {
6714     // This must be some other declcontext that parses exprs.
6715     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6716     return true;
6717   }
6718 
6719   if (!IsVariadic) {
6720     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6721     return true;
6722   }
6723 
6724   if (LastParam)
6725     *LastParam = Params.empty() ? nullptr : Params.back();
6726 
6727   return false;
6728 }
6729 
6730 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6731 /// for validity.  Emit an error and return true on failure; return false
6732 /// on success.
6733 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6734   Expr *Fn = TheCall->getCallee();
6735 
6736   if (checkVAStartABI(*this, BuiltinID, Fn))
6737     return true;
6738 
6739   if (checkArgCount(*this, TheCall, 2))
6740     return true;
6741 
6742   // Type-check the first argument normally.
6743   if (checkBuiltinArgument(*this, TheCall, 0))
6744     return true;
6745 
6746   // Check that the current function is variadic, and get its last parameter.
6747   ParmVarDecl *LastParam;
6748   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6749     return true;
6750 
6751   // Verify that the second argument to the builtin is the last argument of the
6752   // current function or method.
6753   bool SecondArgIsLastNamedArgument = false;
6754   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6755 
6756   // These are valid if SecondArgIsLastNamedArgument is false after the next
6757   // block.
6758   QualType Type;
6759   SourceLocation ParamLoc;
6760   bool IsCRegister = false;
6761 
6762   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6763     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6764       SecondArgIsLastNamedArgument = PV == LastParam;
6765 
6766       Type = PV->getType();
6767       ParamLoc = PV->getLocation();
6768       IsCRegister =
6769           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6770     }
6771   }
6772 
6773   if (!SecondArgIsLastNamedArgument)
6774     Diag(TheCall->getArg(1)->getBeginLoc(),
6775          diag::warn_second_arg_of_va_start_not_last_named_param);
6776   else if (IsCRegister || Type->isReferenceType() ||
6777            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6778              // Promotable integers are UB, but enumerations need a bit of
6779              // extra checking to see what their promotable type actually is.
6780              if (!Type->isPromotableIntegerType())
6781                return false;
6782              if (!Type->isEnumeralType())
6783                return true;
6784              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6785              return !(ED &&
6786                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6787            }()) {
6788     unsigned Reason = 0;
6789     if (Type->isReferenceType())  Reason = 1;
6790     else if (IsCRegister)         Reason = 2;
6791     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6792     Diag(ParamLoc, diag::note_parameter_type) << Type;
6793   }
6794 
6795   TheCall->setType(Context.VoidTy);
6796   return false;
6797 }
6798 
6799 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6800   auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6801     const LangOptions &LO = getLangOpts();
6802 
6803     if (LO.CPlusPlus)
6804       return Arg->getType()
6805                  .getCanonicalType()
6806                  .getTypePtr()
6807                  ->getPointeeType()
6808                  .withoutLocalFastQualifiers() == Context.CharTy;
6809 
6810     // In C, allow aliasing through `char *`, this is required for AArch64 at
6811     // least.
6812     return true;
6813   };
6814 
6815   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6816   //                 const char *named_addr);
6817 
6818   Expr *Func = Call->getCallee();
6819 
6820   if (Call->getNumArgs() < 3)
6821     return Diag(Call->getEndLoc(),
6822                 diag::err_typecheck_call_too_few_args_at_least)
6823            << 0 /*function call*/ << 3 << Call->getNumArgs();
6824 
6825   // Type-check the first argument normally.
6826   if (checkBuiltinArgument(*this, Call, 0))
6827     return true;
6828 
6829   // Check that the current function is variadic.
6830   if (checkVAStartIsInVariadicFunction(*this, Func))
6831     return true;
6832 
6833   // __va_start on Windows does not validate the parameter qualifiers
6834 
6835   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6836   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6837 
6838   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6839   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6840 
6841   const QualType &ConstCharPtrTy =
6842       Context.getPointerType(Context.CharTy.withConst());
6843   if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6844     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6845         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6846         << 0                                      /* qualifier difference */
6847         << 3                                      /* parameter mismatch */
6848         << 2 << Arg1->getType() << ConstCharPtrTy;
6849 
6850   const QualType SizeTy = Context.getSizeType();
6851   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6852     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6853         << Arg2->getType() << SizeTy << 1 /* different class */
6854         << 0                              /* qualifier difference */
6855         << 3                              /* parameter mismatch */
6856         << 3 << Arg2->getType() << SizeTy;
6857 
6858   return false;
6859 }
6860 
6861 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6862 /// friends.  This is declared to take (...), so we have to check everything.
6863 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6864   if (checkArgCount(*this, TheCall, 2))
6865     return true;
6866 
6867   ExprResult OrigArg0 = TheCall->getArg(0);
6868   ExprResult OrigArg1 = TheCall->getArg(1);
6869 
6870   // Do standard promotions between the two arguments, returning their common
6871   // type.
6872   QualType Res = UsualArithmeticConversions(
6873       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6874   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6875     return true;
6876 
6877   // Make sure any conversions are pushed back into the call; this is
6878   // type safe since unordered compare builtins are declared as "_Bool
6879   // foo(...)".
6880   TheCall->setArg(0, OrigArg0.get());
6881   TheCall->setArg(1, OrigArg1.get());
6882 
6883   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6884     return false;
6885 
6886   // If the common type isn't a real floating type, then the arguments were
6887   // invalid for this operation.
6888   if (Res.isNull() || !Res->isRealFloatingType())
6889     return Diag(OrigArg0.get()->getBeginLoc(),
6890                 diag::err_typecheck_call_invalid_ordered_compare)
6891            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6892            << SourceRange(OrigArg0.get()->getBeginLoc(),
6893                           OrigArg1.get()->getEndLoc());
6894 
6895   return false;
6896 }
6897 
6898 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6899 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6900 /// to check everything. We expect the last argument to be a floating point
6901 /// value.
6902 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6903   if (checkArgCount(*this, TheCall, NumArgs))
6904     return true;
6905 
6906   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6907   // on all preceding parameters just being int.  Try all of those.
6908   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6909     Expr *Arg = TheCall->getArg(i);
6910 
6911     if (Arg->isTypeDependent())
6912       return false;
6913 
6914     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6915 
6916     if (Res.isInvalid())
6917       return true;
6918     TheCall->setArg(i, Res.get());
6919   }
6920 
6921   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6922 
6923   if (OrigArg->isTypeDependent())
6924     return false;
6925 
6926   // Usual Unary Conversions will convert half to float, which we want for
6927   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6928   // type how it is, but do normal L->Rvalue conversions.
6929   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6930     OrigArg = UsualUnaryConversions(OrigArg).get();
6931   else
6932     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6933   TheCall->setArg(NumArgs - 1, OrigArg);
6934 
6935   // This operation requires a non-_Complex floating-point number.
6936   if (!OrigArg->getType()->isRealFloatingType())
6937     return Diag(OrigArg->getBeginLoc(),
6938                 diag::err_typecheck_call_invalid_unary_fp)
6939            << OrigArg->getType() << OrigArg->getSourceRange();
6940 
6941   return false;
6942 }
6943 
6944 /// Perform semantic analysis for a call to __builtin_complex.
6945 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6946   if (checkArgCount(*this, TheCall, 2))
6947     return true;
6948 
6949   bool Dependent = false;
6950   for (unsigned I = 0; I != 2; ++I) {
6951     Expr *Arg = TheCall->getArg(I);
6952     QualType T = Arg->getType();
6953     if (T->isDependentType()) {
6954       Dependent = true;
6955       continue;
6956     }
6957 
6958     // Despite supporting _Complex int, GCC requires a real floating point type
6959     // for the operands of __builtin_complex.
6960     if (!T->isRealFloatingType()) {
6961       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6962              << Arg->getType() << Arg->getSourceRange();
6963     }
6964 
6965     ExprResult Converted = DefaultLvalueConversion(Arg);
6966     if (Converted.isInvalid())
6967       return true;
6968     TheCall->setArg(I, Converted.get());
6969   }
6970 
6971   if (Dependent) {
6972     TheCall->setType(Context.DependentTy);
6973     return false;
6974   }
6975 
6976   Expr *Real = TheCall->getArg(0);
6977   Expr *Imag = TheCall->getArg(1);
6978   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6979     return Diag(Real->getBeginLoc(),
6980                 diag::err_typecheck_call_different_arg_types)
6981            << Real->getType() << Imag->getType()
6982            << Real->getSourceRange() << Imag->getSourceRange();
6983   }
6984 
6985   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6986   // don't allow this builtin to form those types either.
6987   // FIXME: Should we allow these types?
6988   if (Real->getType()->isFloat16Type())
6989     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6990            << "_Float16";
6991   if (Real->getType()->isHalfType())
6992     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6993            << "half";
6994 
6995   TheCall->setType(Context.getComplexType(Real->getType()));
6996   return false;
6997 }
6998 
6999 // Customized Sema Checking for VSX builtins that have the following signature:
7000 // vector [...] builtinName(vector [...], vector [...], const int);
7001 // Which takes the same type of vectors (any legal vector type) for the first
7002 // two arguments and takes compile time constant for the third argument.
7003 // Example builtins are :
7004 // vector double vec_xxpermdi(vector double, vector double, int);
7005 // vector short vec_xxsldwi(vector short, vector short, int);
7006 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
7007   unsigned ExpectedNumArgs = 3;
7008   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
7009     return true;
7010 
7011   // Check the third argument is a compile time constant
7012   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
7013     return Diag(TheCall->getBeginLoc(),
7014                 diag::err_vsx_builtin_nonconstant_argument)
7015            << 3 /* argument index */ << TheCall->getDirectCallee()
7016            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
7017                           TheCall->getArg(2)->getEndLoc());
7018 
7019   QualType Arg1Ty = TheCall->getArg(0)->getType();
7020   QualType Arg2Ty = TheCall->getArg(1)->getType();
7021 
7022   // Check the type of argument 1 and argument 2 are vectors.
7023   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
7024   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
7025       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
7026     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
7027            << TheCall->getDirectCallee()
7028            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7029                           TheCall->getArg(1)->getEndLoc());
7030   }
7031 
7032   // Check the first two arguments are the same type.
7033   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
7034     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
7035            << TheCall->getDirectCallee()
7036            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7037                           TheCall->getArg(1)->getEndLoc());
7038   }
7039 
7040   // When default clang type checking is turned off and the customized type
7041   // checking is used, the returning type of the function must be explicitly
7042   // set. Otherwise it is _Bool by default.
7043   TheCall->setType(Arg1Ty);
7044 
7045   return false;
7046 }
7047 
7048 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
7049 // This is declared to take (...), so we have to check everything.
7050 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
7051   if (TheCall->getNumArgs() < 2)
7052     return ExprError(Diag(TheCall->getEndLoc(),
7053                           diag::err_typecheck_call_too_few_args_at_least)
7054                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
7055                      << TheCall->getSourceRange());
7056 
7057   // Determine which of the following types of shufflevector we're checking:
7058   // 1) unary, vector mask: (lhs, mask)
7059   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
7060   QualType resType = TheCall->getArg(0)->getType();
7061   unsigned numElements = 0;
7062 
7063   if (!TheCall->getArg(0)->isTypeDependent() &&
7064       !TheCall->getArg(1)->isTypeDependent()) {
7065     QualType LHSType = TheCall->getArg(0)->getType();
7066     QualType RHSType = TheCall->getArg(1)->getType();
7067 
7068     if (!LHSType->isVectorType() || !RHSType->isVectorType())
7069       return ExprError(
7070           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
7071           << TheCall->getDirectCallee()
7072           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7073                          TheCall->getArg(1)->getEndLoc()));
7074 
7075     numElements = LHSType->castAs<VectorType>()->getNumElements();
7076     unsigned numResElements = TheCall->getNumArgs() - 2;
7077 
7078     // Check to see if we have a call with 2 vector arguments, the unary shuffle
7079     // with mask.  If so, verify that RHS is an integer vector type with the
7080     // same number of elts as lhs.
7081     if (TheCall->getNumArgs() == 2) {
7082       if (!RHSType->hasIntegerRepresentation() ||
7083           RHSType->castAs<VectorType>()->getNumElements() != numElements)
7084         return ExprError(Diag(TheCall->getBeginLoc(),
7085                               diag::err_vec_builtin_incompatible_vector)
7086                          << TheCall->getDirectCallee()
7087                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
7088                                         TheCall->getArg(1)->getEndLoc()));
7089     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
7090       return ExprError(Diag(TheCall->getBeginLoc(),
7091                             diag::err_vec_builtin_incompatible_vector)
7092                        << TheCall->getDirectCallee()
7093                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7094                                       TheCall->getArg(1)->getEndLoc()));
7095     } else if (numElements != numResElements) {
7096       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
7097       resType = Context.getVectorType(eltType, numResElements,
7098                                       VectorType::GenericVector);
7099     }
7100   }
7101 
7102   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
7103     if (TheCall->getArg(i)->isTypeDependent() ||
7104         TheCall->getArg(i)->isValueDependent())
7105       continue;
7106 
7107     Optional<llvm::APSInt> Result;
7108     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
7109       return ExprError(Diag(TheCall->getBeginLoc(),
7110                             diag::err_shufflevector_nonconstant_argument)
7111                        << TheCall->getArg(i)->getSourceRange());
7112 
7113     // Allow -1 which will be translated to undef in the IR.
7114     if (Result->isSigned() && Result->isAllOnes())
7115       continue;
7116 
7117     if (Result->getActiveBits() > 64 ||
7118         Result->getZExtValue() >= numElements * 2)
7119       return ExprError(Diag(TheCall->getBeginLoc(),
7120                             diag::err_shufflevector_argument_too_large)
7121                        << TheCall->getArg(i)->getSourceRange());
7122   }
7123 
7124   SmallVector<Expr*, 32> exprs;
7125 
7126   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
7127     exprs.push_back(TheCall->getArg(i));
7128     TheCall->setArg(i, nullptr);
7129   }
7130 
7131   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
7132                                          TheCall->getCallee()->getBeginLoc(),
7133                                          TheCall->getRParenLoc());
7134 }
7135 
7136 /// SemaConvertVectorExpr - Handle __builtin_convertvector
7137 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
7138                                        SourceLocation BuiltinLoc,
7139                                        SourceLocation RParenLoc) {
7140   ExprValueKind VK = VK_PRValue;
7141   ExprObjectKind OK = OK_Ordinary;
7142   QualType DstTy = TInfo->getType();
7143   QualType SrcTy = E->getType();
7144 
7145   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
7146     return ExprError(Diag(BuiltinLoc,
7147                           diag::err_convertvector_non_vector)
7148                      << E->getSourceRange());
7149   if (!DstTy->isVectorType() && !DstTy->isDependentType())
7150     return ExprError(Diag(BuiltinLoc,
7151                           diag::err_convertvector_non_vector_type));
7152 
7153   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
7154     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
7155     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
7156     if (SrcElts != DstElts)
7157       return ExprError(Diag(BuiltinLoc,
7158                             diag::err_convertvector_incompatible_vector)
7159                        << E->getSourceRange());
7160   }
7161 
7162   return new (Context)
7163       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
7164 }
7165 
7166 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
7167 // This is declared to take (const void*, ...) and can take two
7168 // optional constant int args.
7169 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
7170   unsigned NumArgs = TheCall->getNumArgs();
7171 
7172   if (NumArgs > 3)
7173     return Diag(TheCall->getEndLoc(),
7174                 diag::err_typecheck_call_too_many_args_at_most)
7175            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7176 
7177   // Argument 0 is checked for us and the remaining arguments must be
7178   // constant integers.
7179   for (unsigned i = 1; i != NumArgs; ++i)
7180     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
7181       return true;
7182 
7183   return false;
7184 }
7185 
7186 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
7187 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
7188   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
7189     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
7190            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7191   if (checkArgCount(*this, TheCall, 1))
7192     return true;
7193   Expr *Arg = TheCall->getArg(0);
7194   if (Arg->isInstantiationDependent())
7195     return false;
7196 
7197   QualType ArgTy = Arg->getType();
7198   if (!ArgTy->hasFloatingRepresentation())
7199     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
7200            << ArgTy;
7201   if (Arg->isLValue()) {
7202     ExprResult FirstArg = DefaultLvalueConversion(Arg);
7203     TheCall->setArg(0, FirstArg.get());
7204   }
7205   TheCall->setType(TheCall->getArg(0)->getType());
7206   return false;
7207 }
7208 
7209 /// SemaBuiltinAssume - Handle __assume (MS Extension).
7210 // __assume does not evaluate its arguments, and should warn if its argument
7211 // has side effects.
7212 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
7213   Expr *Arg = TheCall->getArg(0);
7214   if (Arg->isInstantiationDependent()) return false;
7215 
7216   if (Arg->HasSideEffects(Context))
7217     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
7218         << Arg->getSourceRange()
7219         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
7220 
7221   return false;
7222 }
7223 
7224 /// Handle __builtin_alloca_with_align. This is declared
7225 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
7226 /// than 8.
7227 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
7228   // The alignment must be a constant integer.
7229   Expr *Arg = TheCall->getArg(1);
7230 
7231   // We can't check the value of a dependent argument.
7232   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7233     if (const auto *UE =
7234             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
7235       if (UE->getKind() == UETT_AlignOf ||
7236           UE->getKind() == UETT_PreferredAlignOf)
7237         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
7238             << Arg->getSourceRange();
7239 
7240     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
7241 
7242     if (!Result.isPowerOf2())
7243       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7244              << Arg->getSourceRange();
7245 
7246     if (Result < Context.getCharWidth())
7247       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
7248              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
7249 
7250     if (Result > std::numeric_limits<int32_t>::max())
7251       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
7252              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
7253   }
7254 
7255   return false;
7256 }
7257 
7258 /// Handle __builtin_assume_aligned. This is declared
7259 /// as (const void*, size_t, ...) and can take one optional constant int arg.
7260 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
7261   unsigned NumArgs = TheCall->getNumArgs();
7262 
7263   if (NumArgs > 3)
7264     return Diag(TheCall->getEndLoc(),
7265                 diag::err_typecheck_call_too_many_args_at_most)
7266            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7267 
7268   // The alignment must be a constant integer.
7269   Expr *Arg = TheCall->getArg(1);
7270 
7271   // We can't check the value of a dependent argument.
7272   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7273     llvm::APSInt Result;
7274     if (SemaBuiltinConstantArg(TheCall, 1, Result))
7275       return true;
7276 
7277     if (!Result.isPowerOf2())
7278       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7279              << Arg->getSourceRange();
7280 
7281     if (Result > Sema::MaximumAlignment)
7282       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
7283           << Arg->getSourceRange() << Sema::MaximumAlignment;
7284   }
7285 
7286   if (NumArgs > 2) {
7287     ExprResult Arg(TheCall->getArg(2));
7288     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
7289       Context.getSizeType(), false);
7290     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7291     if (Arg.isInvalid()) return true;
7292     TheCall->setArg(2, Arg.get());
7293   }
7294 
7295   return false;
7296 }
7297 
7298 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
7299   unsigned BuiltinID =
7300       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
7301   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
7302 
7303   unsigned NumArgs = TheCall->getNumArgs();
7304   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
7305   if (NumArgs < NumRequiredArgs) {
7306     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
7307            << 0 /* function call */ << NumRequiredArgs << NumArgs
7308            << TheCall->getSourceRange();
7309   }
7310   if (NumArgs >= NumRequiredArgs + 0x100) {
7311     return Diag(TheCall->getEndLoc(),
7312                 diag::err_typecheck_call_too_many_args_at_most)
7313            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
7314            << TheCall->getSourceRange();
7315   }
7316   unsigned i = 0;
7317 
7318   // For formatting call, check buffer arg.
7319   if (!IsSizeCall) {
7320     ExprResult Arg(TheCall->getArg(i));
7321     InitializedEntity Entity = InitializedEntity::InitializeParameter(
7322         Context, Context.VoidPtrTy, false);
7323     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7324     if (Arg.isInvalid())
7325       return true;
7326     TheCall->setArg(i, Arg.get());
7327     i++;
7328   }
7329 
7330   // Check string literal arg.
7331   unsigned FormatIdx = i;
7332   {
7333     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
7334     if (Arg.isInvalid())
7335       return true;
7336     TheCall->setArg(i, Arg.get());
7337     i++;
7338   }
7339 
7340   // Make sure variadic args are scalar.
7341   unsigned FirstDataArg = i;
7342   while (i < NumArgs) {
7343     ExprResult Arg = DefaultVariadicArgumentPromotion(
7344         TheCall->getArg(i), VariadicFunction, nullptr);
7345     if (Arg.isInvalid())
7346       return true;
7347     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
7348     if (ArgSize.getQuantity() >= 0x100) {
7349       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
7350              << i << (int)ArgSize.getQuantity() << 0xff
7351              << TheCall->getSourceRange();
7352     }
7353     TheCall->setArg(i, Arg.get());
7354     i++;
7355   }
7356 
7357   // Check formatting specifiers. NOTE: We're only doing this for the non-size
7358   // call to avoid duplicate diagnostics.
7359   if (!IsSizeCall) {
7360     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
7361     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
7362     bool Success = CheckFormatArguments(
7363         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
7364         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
7365         CheckedVarArgs);
7366     if (!Success)
7367       return true;
7368   }
7369 
7370   if (IsSizeCall) {
7371     TheCall->setType(Context.getSizeType());
7372   } else {
7373     TheCall->setType(Context.VoidPtrTy);
7374   }
7375   return false;
7376 }
7377 
7378 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
7379 /// TheCall is a constant expression.
7380 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7381                                   llvm::APSInt &Result) {
7382   Expr *Arg = TheCall->getArg(ArgNum);
7383   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
7384   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
7385 
7386   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
7387 
7388   Optional<llvm::APSInt> R;
7389   if (!(R = Arg->getIntegerConstantExpr(Context)))
7390     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
7391            << FDecl->getDeclName() << Arg->getSourceRange();
7392   Result = *R;
7393   return false;
7394 }
7395 
7396 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
7397 /// TheCall is a constant expression in the range [Low, High].
7398 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
7399                                        int Low, int High, bool RangeIsError) {
7400   if (isConstantEvaluated())
7401     return false;
7402   llvm::APSInt Result;
7403 
7404   // We can't check the value of a dependent argument.
7405   Expr *Arg = TheCall->getArg(ArgNum);
7406   if (Arg->isTypeDependent() || Arg->isValueDependent())
7407     return false;
7408 
7409   // Check constant-ness first.
7410   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7411     return true;
7412 
7413   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7414     if (RangeIsError)
7415       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
7416              << toString(Result, 10) << Low << High << Arg->getSourceRange();
7417     else
7418       // Defer the warning until we know if the code will be emitted so that
7419       // dead code can ignore this.
7420       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
7421                           PDiag(diag::warn_argument_invalid_range)
7422                               << toString(Result, 10) << Low << High
7423                               << Arg->getSourceRange());
7424   }
7425 
7426   return false;
7427 }
7428 
7429 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
7430 /// TheCall is a constant expression is a multiple of Num..
7431 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
7432                                           unsigned Num) {
7433   llvm::APSInt Result;
7434 
7435   // We can't check the value of a dependent argument.
7436   Expr *Arg = TheCall->getArg(ArgNum);
7437   if (Arg->isTypeDependent() || Arg->isValueDependent())
7438     return false;
7439 
7440   // Check constant-ness first.
7441   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7442     return true;
7443 
7444   if (Result.getSExtValue() % Num != 0)
7445     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7446            << Num << Arg->getSourceRange();
7447 
7448   return false;
7449 }
7450 
7451 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7452 /// constant expression representing a power of 2.
7453 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7454   llvm::APSInt Result;
7455 
7456   // We can't check the value of a dependent argument.
7457   Expr *Arg = TheCall->getArg(ArgNum);
7458   if (Arg->isTypeDependent() || Arg->isValueDependent())
7459     return false;
7460 
7461   // Check constant-ness first.
7462   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7463     return true;
7464 
7465   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7466   // and only if x is a power of 2.
7467   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7468     return false;
7469 
7470   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7471          << Arg->getSourceRange();
7472 }
7473 
7474 static bool IsShiftedByte(llvm::APSInt Value) {
7475   if (Value.isNegative())
7476     return false;
7477 
7478   // Check if it's a shifted byte, by shifting it down
7479   while (true) {
7480     // If the value fits in the bottom byte, the check passes.
7481     if (Value < 0x100)
7482       return true;
7483 
7484     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7485     // fails.
7486     if ((Value & 0xFF) != 0)
7487       return false;
7488 
7489     // If the bottom 8 bits are all 0, but something above that is nonzero,
7490     // then shifting the value right by 8 bits won't affect whether it's a
7491     // shifted byte or not. So do that, and go round again.
7492     Value >>= 8;
7493   }
7494 }
7495 
7496 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7497 /// a constant expression representing an arbitrary byte value shifted left by
7498 /// a multiple of 8 bits.
7499 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7500                                              unsigned ArgBits) {
7501   llvm::APSInt Result;
7502 
7503   // We can't check the value of a dependent argument.
7504   Expr *Arg = TheCall->getArg(ArgNum);
7505   if (Arg->isTypeDependent() || Arg->isValueDependent())
7506     return false;
7507 
7508   // Check constant-ness first.
7509   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7510     return true;
7511 
7512   // Truncate to the given size.
7513   Result = Result.getLoBits(ArgBits);
7514   Result.setIsUnsigned(true);
7515 
7516   if (IsShiftedByte(Result))
7517     return false;
7518 
7519   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7520          << Arg->getSourceRange();
7521 }
7522 
7523 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7524 /// TheCall is a constant expression representing either a shifted byte value,
7525 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7526 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7527 /// Arm MVE intrinsics.
7528 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7529                                                    int ArgNum,
7530                                                    unsigned ArgBits) {
7531   llvm::APSInt Result;
7532 
7533   // We can't check the value of a dependent argument.
7534   Expr *Arg = TheCall->getArg(ArgNum);
7535   if (Arg->isTypeDependent() || Arg->isValueDependent())
7536     return false;
7537 
7538   // Check constant-ness first.
7539   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7540     return true;
7541 
7542   // Truncate to the given size.
7543   Result = Result.getLoBits(ArgBits);
7544   Result.setIsUnsigned(true);
7545 
7546   // Check to see if it's in either of the required forms.
7547   if (IsShiftedByte(Result) ||
7548       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7549     return false;
7550 
7551   return Diag(TheCall->getBeginLoc(),
7552               diag::err_argument_not_shifted_byte_or_xxff)
7553          << Arg->getSourceRange();
7554 }
7555 
7556 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7557 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7558   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7559     if (checkArgCount(*this, TheCall, 2))
7560       return true;
7561     Expr *Arg0 = TheCall->getArg(0);
7562     Expr *Arg1 = TheCall->getArg(1);
7563 
7564     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7565     if (FirstArg.isInvalid())
7566       return true;
7567     QualType FirstArgType = FirstArg.get()->getType();
7568     if (!FirstArgType->isAnyPointerType())
7569       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7570                << "first" << FirstArgType << Arg0->getSourceRange();
7571     TheCall->setArg(0, FirstArg.get());
7572 
7573     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7574     if (SecArg.isInvalid())
7575       return true;
7576     QualType SecArgType = SecArg.get()->getType();
7577     if (!SecArgType->isIntegerType())
7578       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7579                << "second" << SecArgType << Arg1->getSourceRange();
7580 
7581     // Derive the return type from the pointer argument.
7582     TheCall->setType(FirstArgType);
7583     return false;
7584   }
7585 
7586   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7587     if (checkArgCount(*this, TheCall, 2))
7588       return true;
7589 
7590     Expr *Arg0 = TheCall->getArg(0);
7591     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7592     if (FirstArg.isInvalid())
7593       return true;
7594     QualType FirstArgType = FirstArg.get()->getType();
7595     if (!FirstArgType->isAnyPointerType())
7596       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7597                << "first" << FirstArgType << Arg0->getSourceRange();
7598     TheCall->setArg(0, FirstArg.get());
7599 
7600     // Derive the return type from the pointer argument.
7601     TheCall->setType(FirstArgType);
7602 
7603     // Second arg must be an constant in range [0,15]
7604     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7605   }
7606 
7607   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7608     if (checkArgCount(*this, TheCall, 2))
7609       return true;
7610     Expr *Arg0 = TheCall->getArg(0);
7611     Expr *Arg1 = TheCall->getArg(1);
7612 
7613     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7614     if (FirstArg.isInvalid())
7615       return true;
7616     QualType FirstArgType = FirstArg.get()->getType();
7617     if (!FirstArgType->isAnyPointerType())
7618       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7619                << "first" << FirstArgType << Arg0->getSourceRange();
7620 
7621     QualType SecArgType = Arg1->getType();
7622     if (!SecArgType->isIntegerType())
7623       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7624                << "second" << SecArgType << Arg1->getSourceRange();
7625     TheCall->setType(Context.IntTy);
7626     return false;
7627   }
7628 
7629   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7630       BuiltinID == AArch64::BI__builtin_arm_stg) {
7631     if (checkArgCount(*this, TheCall, 1))
7632       return true;
7633     Expr *Arg0 = TheCall->getArg(0);
7634     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7635     if (FirstArg.isInvalid())
7636       return true;
7637 
7638     QualType FirstArgType = FirstArg.get()->getType();
7639     if (!FirstArgType->isAnyPointerType())
7640       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7641                << "first" << FirstArgType << Arg0->getSourceRange();
7642     TheCall->setArg(0, FirstArg.get());
7643 
7644     // Derive the return type from the pointer argument.
7645     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7646       TheCall->setType(FirstArgType);
7647     return false;
7648   }
7649 
7650   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7651     Expr *ArgA = TheCall->getArg(0);
7652     Expr *ArgB = TheCall->getArg(1);
7653 
7654     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7655     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7656 
7657     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7658       return true;
7659 
7660     QualType ArgTypeA = ArgExprA.get()->getType();
7661     QualType ArgTypeB = ArgExprB.get()->getType();
7662 
7663     auto isNull = [&] (Expr *E) -> bool {
7664       return E->isNullPointerConstant(
7665                         Context, Expr::NPC_ValueDependentIsNotNull); };
7666 
7667     // argument should be either a pointer or null
7668     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7669       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7670         << "first" << ArgTypeA << ArgA->getSourceRange();
7671 
7672     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7673       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7674         << "second" << ArgTypeB << ArgB->getSourceRange();
7675 
7676     // Ensure Pointee types are compatible
7677     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7678         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7679       QualType pointeeA = ArgTypeA->getPointeeType();
7680       QualType pointeeB = ArgTypeB->getPointeeType();
7681       if (!Context.typesAreCompatible(
7682              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7683              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7684         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7685           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7686           << ArgB->getSourceRange();
7687       }
7688     }
7689 
7690     // at least one argument should be pointer type
7691     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7692       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7693         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7694 
7695     if (isNull(ArgA)) // adopt type of the other pointer
7696       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7697 
7698     if (isNull(ArgB))
7699       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7700 
7701     TheCall->setArg(0, ArgExprA.get());
7702     TheCall->setArg(1, ArgExprB.get());
7703     TheCall->setType(Context.LongLongTy);
7704     return false;
7705   }
7706   assert(false && "Unhandled ARM MTE intrinsic");
7707   return true;
7708 }
7709 
7710 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7711 /// TheCall is an ARM/AArch64 special register string literal.
7712 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7713                                     int ArgNum, unsigned ExpectedFieldNum,
7714                                     bool AllowName) {
7715   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7716                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7717                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7718                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7719                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7720                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7721   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7722                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7723                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7724                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7725                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7726                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7727   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7728 
7729   // We can't check the value of a dependent argument.
7730   Expr *Arg = TheCall->getArg(ArgNum);
7731   if (Arg->isTypeDependent() || Arg->isValueDependent())
7732     return false;
7733 
7734   // Check if the argument is a string literal.
7735   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7736     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7737            << Arg->getSourceRange();
7738 
7739   // Check the type of special register given.
7740   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7741   SmallVector<StringRef, 6> Fields;
7742   Reg.split(Fields, ":");
7743 
7744   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7745     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7746            << Arg->getSourceRange();
7747 
7748   // If the string is the name of a register then we cannot check that it is
7749   // valid here but if the string is of one the forms described in ACLE then we
7750   // can check that the supplied fields are integers and within the valid
7751   // ranges.
7752   if (Fields.size() > 1) {
7753     bool FiveFields = Fields.size() == 5;
7754 
7755     bool ValidString = true;
7756     if (IsARMBuiltin) {
7757       ValidString &= Fields[0].startswith_insensitive("cp") ||
7758                      Fields[0].startswith_insensitive("p");
7759       if (ValidString)
7760         Fields[0] = Fields[0].drop_front(
7761             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7762 
7763       ValidString &= Fields[2].startswith_insensitive("c");
7764       if (ValidString)
7765         Fields[2] = Fields[2].drop_front(1);
7766 
7767       if (FiveFields) {
7768         ValidString &= Fields[3].startswith_insensitive("c");
7769         if (ValidString)
7770           Fields[3] = Fields[3].drop_front(1);
7771       }
7772     }
7773 
7774     SmallVector<int, 5> Ranges;
7775     if (FiveFields)
7776       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7777     else
7778       Ranges.append({15, 7, 15});
7779 
7780     for (unsigned i=0; i<Fields.size(); ++i) {
7781       int IntField;
7782       ValidString &= !Fields[i].getAsInteger(10, IntField);
7783       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7784     }
7785 
7786     if (!ValidString)
7787       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7788              << Arg->getSourceRange();
7789   } else if (IsAArch64Builtin && Fields.size() == 1) {
7790     // If the register name is one of those that appear in the condition below
7791     // and the special register builtin being used is one of the write builtins,
7792     // then we require that the argument provided for writing to the register
7793     // is an integer constant expression. This is because it will be lowered to
7794     // an MSR (immediate) instruction, so we need to know the immediate at
7795     // compile time.
7796     if (TheCall->getNumArgs() != 2)
7797       return false;
7798 
7799     std::string RegLower = Reg.lower();
7800     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7801         RegLower != "pan" && RegLower != "uao")
7802       return false;
7803 
7804     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7805   }
7806 
7807   return false;
7808 }
7809 
7810 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7811 /// Emit an error and return true on failure; return false on success.
7812 /// TypeStr is a string containing the type descriptor of the value returned by
7813 /// the builtin and the descriptors of the expected type of the arguments.
7814 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
7815                                  const char *TypeStr) {
7816 
7817   assert((TypeStr[0] != '\0') &&
7818          "Invalid types in PPC MMA builtin declaration");
7819 
7820   switch (BuiltinID) {
7821   default:
7822     // This function is called in CheckPPCBuiltinFunctionCall where the
7823     // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here
7824     // we are isolating the pair vector memop builtins that can be used with mma
7825     // off so the default case is every builtin that requires mma and paired
7826     // vector memops.
7827     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7828                          diag::err_ppc_builtin_only_on_arch, "10") ||
7829         SemaFeatureCheck(*this, TheCall, "mma",
7830                          diag::err_ppc_builtin_only_on_arch, "10"))
7831       return true;
7832     break;
7833   case PPC::BI__builtin_vsx_lxvp:
7834   case PPC::BI__builtin_vsx_stxvp:
7835   case PPC::BI__builtin_vsx_assemble_pair:
7836   case PPC::BI__builtin_vsx_disassemble_pair:
7837     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7838                          diag::err_ppc_builtin_only_on_arch, "10"))
7839       return true;
7840     break;
7841   }
7842 
7843   unsigned Mask = 0;
7844   unsigned ArgNum = 0;
7845 
7846   // The first type in TypeStr is the type of the value returned by the
7847   // builtin. So we first read that type and change the type of TheCall.
7848   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7849   TheCall->setType(type);
7850 
7851   while (*TypeStr != '\0') {
7852     Mask = 0;
7853     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7854     if (ArgNum >= TheCall->getNumArgs()) {
7855       ArgNum++;
7856       break;
7857     }
7858 
7859     Expr *Arg = TheCall->getArg(ArgNum);
7860     QualType PassedType = Arg->getType();
7861     QualType StrippedRVType = PassedType.getCanonicalType();
7862 
7863     // Strip Restrict/Volatile qualifiers.
7864     if (StrippedRVType.isRestrictQualified() ||
7865         StrippedRVType.isVolatileQualified())
7866       StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
7867 
7868     // The only case where the argument type and expected type are allowed to
7869     // mismatch is if the argument type is a non-void pointer (or array) and
7870     // expected type is a void pointer.
7871     if (StrippedRVType != ExpectedType)
7872       if (!(ExpectedType->isVoidPointerType() &&
7873             (StrippedRVType->isPointerType() || StrippedRVType->isArrayType())))
7874         return Diag(Arg->getBeginLoc(),
7875                     diag::err_typecheck_convert_incompatible)
7876                << PassedType << ExpectedType << 1 << 0 << 0;
7877 
7878     // If the value of the Mask is not 0, we have a constraint in the size of
7879     // the integer argument so here we ensure the argument is a constant that
7880     // is in the valid range.
7881     if (Mask != 0 &&
7882         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7883       return true;
7884 
7885     ArgNum++;
7886   }
7887 
7888   // In case we exited early from the previous loop, there are other types to
7889   // read from TypeStr. So we need to read them all to ensure we have the right
7890   // number of arguments in TheCall and if it is not the case, to display a
7891   // better error message.
7892   while (*TypeStr != '\0') {
7893     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7894     ArgNum++;
7895   }
7896   if (checkArgCount(*this, TheCall, ArgNum))
7897     return true;
7898 
7899   return false;
7900 }
7901 
7902 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7903 /// This checks that the target supports __builtin_longjmp and
7904 /// that val is a constant 1.
7905 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7906   if (!Context.getTargetInfo().hasSjLjLowering())
7907     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7908            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7909 
7910   Expr *Arg = TheCall->getArg(1);
7911   llvm::APSInt Result;
7912 
7913   // TODO: This is less than ideal. Overload this to take a value.
7914   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7915     return true;
7916 
7917   if (Result != 1)
7918     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7919            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7920 
7921   return false;
7922 }
7923 
7924 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7925 /// This checks that the target supports __builtin_setjmp.
7926 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7927   if (!Context.getTargetInfo().hasSjLjLowering())
7928     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7929            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7930   return false;
7931 }
7932 
7933 namespace {
7934 
7935 class UncoveredArgHandler {
7936   enum { Unknown = -1, AllCovered = -2 };
7937 
7938   signed FirstUncoveredArg = Unknown;
7939   SmallVector<const Expr *, 4> DiagnosticExprs;
7940 
7941 public:
7942   UncoveredArgHandler() = default;
7943 
7944   bool hasUncoveredArg() const {
7945     return (FirstUncoveredArg >= 0);
7946   }
7947 
7948   unsigned getUncoveredArg() const {
7949     assert(hasUncoveredArg() && "no uncovered argument");
7950     return FirstUncoveredArg;
7951   }
7952 
7953   void setAllCovered() {
7954     // A string has been found with all arguments covered, so clear out
7955     // the diagnostics.
7956     DiagnosticExprs.clear();
7957     FirstUncoveredArg = AllCovered;
7958   }
7959 
7960   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7961     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7962 
7963     // Don't update if a previous string covers all arguments.
7964     if (FirstUncoveredArg == AllCovered)
7965       return;
7966 
7967     // UncoveredArgHandler tracks the highest uncovered argument index
7968     // and with it all the strings that match this index.
7969     if (NewFirstUncoveredArg == FirstUncoveredArg)
7970       DiagnosticExprs.push_back(StrExpr);
7971     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7972       DiagnosticExprs.clear();
7973       DiagnosticExprs.push_back(StrExpr);
7974       FirstUncoveredArg = NewFirstUncoveredArg;
7975     }
7976   }
7977 
7978   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7979 };
7980 
7981 enum StringLiteralCheckType {
7982   SLCT_NotALiteral,
7983   SLCT_UncheckedLiteral,
7984   SLCT_CheckedLiteral
7985 };
7986 
7987 } // namespace
7988 
7989 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7990                                      BinaryOperatorKind BinOpKind,
7991                                      bool AddendIsRight) {
7992   unsigned BitWidth = Offset.getBitWidth();
7993   unsigned AddendBitWidth = Addend.getBitWidth();
7994   // There might be negative interim results.
7995   if (Addend.isUnsigned()) {
7996     Addend = Addend.zext(++AddendBitWidth);
7997     Addend.setIsSigned(true);
7998   }
7999   // Adjust the bit width of the APSInts.
8000   if (AddendBitWidth > BitWidth) {
8001     Offset = Offset.sext(AddendBitWidth);
8002     BitWidth = AddendBitWidth;
8003   } else if (BitWidth > AddendBitWidth) {
8004     Addend = Addend.sext(BitWidth);
8005   }
8006 
8007   bool Ov = false;
8008   llvm::APSInt ResOffset = Offset;
8009   if (BinOpKind == BO_Add)
8010     ResOffset = Offset.sadd_ov(Addend, Ov);
8011   else {
8012     assert(AddendIsRight && BinOpKind == BO_Sub &&
8013            "operator must be add or sub with addend on the right");
8014     ResOffset = Offset.ssub_ov(Addend, Ov);
8015   }
8016 
8017   // We add an offset to a pointer here so we should support an offset as big as
8018   // possible.
8019   if (Ov) {
8020     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
8021            "index (intermediate) result too big");
8022     Offset = Offset.sext(2 * BitWidth);
8023     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
8024     return;
8025   }
8026 
8027   Offset = ResOffset;
8028 }
8029 
8030 namespace {
8031 
8032 // This is a wrapper class around StringLiteral to support offsetted string
8033 // literals as format strings. It takes the offset into account when returning
8034 // the string and its length or the source locations to display notes correctly.
8035 class FormatStringLiteral {
8036   const StringLiteral *FExpr;
8037   int64_t Offset;
8038 
8039  public:
8040   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
8041       : FExpr(fexpr), Offset(Offset) {}
8042 
8043   StringRef getString() const {
8044     return FExpr->getString().drop_front(Offset);
8045   }
8046 
8047   unsigned getByteLength() const {
8048     return FExpr->getByteLength() - getCharByteWidth() * Offset;
8049   }
8050 
8051   unsigned getLength() const { return FExpr->getLength() - Offset; }
8052   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
8053 
8054   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
8055 
8056   QualType getType() const { return FExpr->getType(); }
8057 
8058   bool isAscii() const { return FExpr->isAscii(); }
8059   bool isWide() const { return FExpr->isWide(); }
8060   bool isUTF8() const { return FExpr->isUTF8(); }
8061   bool isUTF16() const { return FExpr->isUTF16(); }
8062   bool isUTF32() const { return FExpr->isUTF32(); }
8063   bool isPascal() const { return FExpr->isPascal(); }
8064 
8065   SourceLocation getLocationOfByte(
8066       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
8067       const TargetInfo &Target, unsigned *StartToken = nullptr,
8068       unsigned *StartTokenByteOffset = nullptr) const {
8069     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
8070                                     StartToken, StartTokenByteOffset);
8071   }
8072 
8073   SourceLocation getBeginLoc() const LLVM_READONLY {
8074     return FExpr->getBeginLoc().getLocWithOffset(Offset);
8075   }
8076 
8077   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
8078 };
8079 
8080 }  // namespace
8081 
8082 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8083                               const Expr *OrigFormatExpr,
8084                               ArrayRef<const Expr *> Args,
8085                               bool HasVAListArg, unsigned format_idx,
8086                               unsigned firstDataArg,
8087                               Sema::FormatStringType Type,
8088                               bool inFunctionCall,
8089                               Sema::VariadicCallType CallType,
8090                               llvm::SmallBitVector &CheckedVarArgs,
8091                               UncoveredArgHandler &UncoveredArg,
8092                               bool IgnoreStringsWithoutSpecifiers);
8093 
8094 // Determine if an expression is a string literal or constant string.
8095 // If this function returns false on the arguments to a function expecting a
8096 // format string, we will usually need to emit a warning.
8097 // True string literals are then checked by CheckFormatString.
8098 static StringLiteralCheckType
8099 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
8100                       bool HasVAListArg, unsigned format_idx,
8101                       unsigned firstDataArg, Sema::FormatStringType Type,
8102                       Sema::VariadicCallType CallType, bool InFunctionCall,
8103                       llvm::SmallBitVector &CheckedVarArgs,
8104                       UncoveredArgHandler &UncoveredArg,
8105                       llvm::APSInt Offset,
8106                       bool IgnoreStringsWithoutSpecifiers = false) {
8107   if (S.isConstantEvaluated())
8108     return SLCT_NotALiteral;
8109  tryAgain:
8110   assert(Offset.isSigned() && "invalid offset");
8111 
8112   if (E->isTypeDependent() || E->isValueDependent())
8113     return SLCT_NotALiteral;
8114 
8115   E = E->IgnoreParenCasts();
8116 
8117   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
8118     // Technically -Wformat-nonliteral does not warn about this case.
8119     // The behavior of printf and friends in this case is implementation
8120     // dependent.  Ideally if the format string cannot be null then
8121     // it should have a 'nonnull' attribute in the function prototype.
8122     return SLCT_UncheckedLiteral;
8123 
8124   switch (E->getStmtClass()) {
8125   case Stmt::BinaryConditionalOperatorClass:
8126   case Stmt::ConditionalOperatorClass: {
8127     // The expression is a literal if both sub-expressions were, and it was
8128     // completely checked only if both sub-expressions were checked.
8129     const AbstractConditionalOperator *C =
8130         cast<AbstractConditionalOperator>(E);
8131 
8132     // Determine whether it is necessary to check both sub-expressions, for
8133     // example, because the condition expression is a constant that can be
8134     // evaluated at compile time.
8135     bool CheckLeft = true, CheckRight = true;
8136 
8137     bool Cond;
8138     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
8139                                                  S.isConstantEvaluated())) {
8140       if (Cond)
8141         CheckRight = false;
8142       else
8143         CheckLeft = false;
8144     }
8145 
8146     // We need to maintain the offsets for the right and the left hand side
8147     // separately to check if every possible indexed expression is a valid
8148     // string literal. They might have different offsets for different string
8149     // literals in the end.
8150     StringLiteralCheckType Left;
8151     if (!CheckLeft)
8152       Left = SLCT_UncheckedLiteral;
8153     else {
8154       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
8155                                    HasVAListArg, format_idx, firstDataArg,
8156                                    Type, CallType, InFunctionCall,
8157                                    CheckedVarArgs, UncoveredArg, Offset,
8158                                    IgnoreStringsWithoutSpecifiers);
8159       if (Left == SLCT_NotALiteral || !CheckRight) {
8160         return Left;
8161       }
8162     }
8163 
8164     StringLiteralCheckType Right = checkFormatStringExpr(
8165         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
8166         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8167         IgnoreStringsWithoutSpecifiers);
8168 
8169     return (CheckLeft && Left < Right) ? Left : Right;
8170   }
8171 
8172   case Stmt::ImplicitCastExprClass:
8173     E = cast<ImplicitCastExpr>(E)->getSubExpr();
8174     goto tryAgain;
8175 
8176   case Stmt::OpaqueValueExprClass:
8177     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
8178       E = src;
8179       goto tryAgain;
8180     }
8181     return SLCT_NotALiteral;
8182 
8183   case Stmt::PredefinedExprClass:
8184     // While __func__, etc., are technically not string literals, they
8185     // cannot contain format specifiers and thus are not a security
8186     // liability.
8187     return SLCT_UncheckedLiteral;
8188 
8189   case Stmt::DeclRefExprClass: {
8190     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8191 
8192     // As an exception, do not flag errors for variables binding to
8193     // const string literals.
8194     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
8195       bool isConstant = false;
8196       QualType T = DR->getType();
8197 
8198       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
8199         isConstant = AT->getElementType().isConstant(S.Context);
8200       } else if (const PointerType *PT = T->getAs<PointerType>()) {
8201         isConstant = T.isConstant(S.Context) &&
8202                      PT->getPointeeType().isConstant(S.Context);
8203       } else if (T->isObjCObjectPointerType()) {
8204         // In ObjC, there is usually no "const ObjectPointer" type,
8205         // so don't check if the pointee type is constant.
8206         isConstant = T.isConstant(S.Context);
8207       }
8208 
8209       if (isConstant) {
8210         if (const Expr *Init = VD->getAnyInitializer()) {
8211           // Look through initializers like const char c[] = { "foo" }
8212           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
8213             if (InitList->isStringLiteralInit())
8214               Init = InitList->getInit(0)->IgnoreParenImpCasts();
8215           }
8216           return checkFormatStringExpr(S, Init, Args,
8217                                        HasVAListArg, format_idx,
8218                                        firstDataArg, Type, CallType,
8219                                        /*InFunctionCall*/ false, CheckedVarArgs,
8220                                        UncoveredArg, Offset);
8221         }
8222       }
8223 
8224       // For vprintf* functions (i.e., HasVAListArg==true), we add a
8225       // special check to see if the format string is a function parameter
8226       // of the function calling the printf function.  If the function
8227       // has an attribute indicating it is a printf-like function, then we
8228       // should suppress warnings concerning non-literals being used in a call
8229       // to a vprintf function.  For example:
8230       //
8231       // void
8232       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
8233       //      va_list ap;
8234       //      va_start(ap, fmt);
8235       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
8236       //      ...
8237       // }
8238       if (HasVAListArg) {
8239         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
8240           if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) {
8241             int PVIndex = PV->getFunctionScopeIndex() + 1;
8242             for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
8243               // adjust for implicit parameter
8244               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
8245                 if (MD->isInstance())
8246                   ++PVIndex;
8247               // We also check if the formats are compatible.
8248               // We can't pass a 'scanf' string to a 'printf' function.
8249               if (PVIndex == PVFormat->getFormatIdx() &&
8250                   Type == S.GetFormatStringType(PVFormat))
8251                 return SLCT_UncheckedLiteral;
8252             }
8253           }
8254         }
8255       }
8256     }
8257 
8258     return SLCT_NotALiteral;
8259   }
8260 
8261   case Stmt::CallExprClass:
8262   case Stmt::CXXMemberCallExprClass: {
8263     const CallExpr *CE = cast<CallExpr>(E);
8264     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
8265       bool IsFirst = true;
8266       StringLiteralCheckType CommonResult;
8267       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
8268         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
8269         StringLiteralCheckType Result = checkFormatStringExpr(
8270             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8271             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8272             IgnoreStringsWithoutSpecifiers);
8273         if (IsFirst) {
8274           CommonResult = Result;
8275           IsFirst = false;
8276         }
8277       }
8278       if (!IsFirst)
8279         return CommonResult;
8280 
8281       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
8282         unsigned BuiltinID = FD->getBuiltinID();
8283         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
8284             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
8285           const Expr *Arg = CE->getArg(0);
8286           return checkFormatStringExpr(S, Arg, Args,
8287                                        HasVAListArg, format_idx,
8288                                        firstDataArg, Type, CallType,
8289                                        InFunctionCall, CheckedVarArgs,
8290                                        UncoveredArg, Offset,
8291                                        IgnoreStringsWithoutSpecifiers);
8292         }
8293       }
8294     }
8295 
8296     return SLCT_NotALiteral;
8297   }
8298   case Stmt::ObjCMessageExprClass: {
8299     const auto *ME = cast<ObjCMessageExpr>(E);
8300     if (const auto *MD = ME->getMethodDecl()) {
8301       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
8302         // As a special case heuristic, if we're using the method -[NSBundle
8303         // localizedStringForKey:value:table:], ignore any key strings that lack
8304         // format specifiers. The idea is that if the key doesn't have any
8305         // format specifiers then its probably just a key to map to the
8306         // localized strings. If it does have format specifiers though, then its
8307         // likely that the text of the key is the format string in the
8308         // programmer's language, and should be checked.
8309         const ObjCInterfaceDecl *IFace;
8310         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
8311             IFace->getIdentifier()->isStr("NSBundle") &&
8312             MD->getSelector().isKeywordSelector(
8313                 {"localizedStringForKey", "value", "table"})) {
8314           IgnoreStringsWithoutSpecifiers = true;
8315         }
8316 
8317         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
8318         return checkFormatStringExpr(
8319             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8320             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8321             IgnoreStringsWithoutSpecifiers);
8322       }
8323     }
8324 
8325     return SLCT_NotALiteral;
8326   }
8327   case Stmt::ObjCStringLiteralClass:
8328   case Stmt::StringLiteralClass: {
8329     const StringLiteral *StrE = nullptr;
8330 
8331     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
8332       StrE = ObjCFExpr->getString();
8333     else
8334       StrE = cast<StringLiteral>(E);
8335 
8336     if (StrE) {
8337       if (Offset.isNegative() || Offset > StrE->getLength()) {
8338         // TODO: It would be better to have an explicit warning for out of
8339         // bounds literals.
8340         return SLCT_NotALiteral;
8341       }
8342       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
8343       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
8344                         firstDataArg, Type, InFunctionCall, CallType,
8345                         CheckedVarArgs, UncoveredArg,
8346                         IgnoreStringsWithoutSpecifiers);
8347       return SLCT_CheckedLiteral;
8348     }
8349 
8350     return SLCT_NotALiteral;
8351   }
8352   case Stmt::BinaryOperatorClass: {
8353     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
8354 
8355     // A string literal + an int offset is still a string literal.
8356     if (BinOp->isAdditiveOp()) {
8357       Expr::EvalResult LResult, RResult;
8358 
8359       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
8360           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8361       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
8362           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8363 
8364       if (LIsInt != RIsInt) {
8365         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
8366 
8367         if (LIsInt) {
8368           if (BinOpKind == BO_Add) {
8369             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
8370             E = BinOp->getRHS();
8371             goto tryAgain;
8372           }
8373         } else {
8374           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
8375           E = BinOp->getLHS();
8376           goto tryAgain;
8377         }
8378       }
8379     }
8380 
8381     return SLCT_NotALiteral;
8382   }
8383   case Stmt::UnaryOperatorClass: {
8384     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
8385     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
8386     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
8387       Expr::EvalResult IndexResult;
8388       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
8389                                        Expr::SE_NoSideEffects,
8390                                        S.isConstantEvaluated())) {
8391         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
8392                    /*RHS is int*/ true);
8393         E = ASE->getBase();
8394         goto tryAgain;
8395       }
8396     }
8397 
8398     return SLCT_NotALiteral;
8399   }
8400 
8401   default:
8402     return SLCT_NotALiteral;
8403   }
8404 }
8405 
8406 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
8407   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
8408       .Case("scanf", FST_Scanf)
8409       .Cases("printf", "printf0", FST_Printf)
8410       .Cases("NSString", "CFString", FST_NSString)
8411       .Case("strftime", FST_Strftime)
8412       .Case("strfmon", FST_Strfmon)
8413       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
8414       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
8415       .Case("os_trace", FST_OSLog)
8416       .Case("os_log", FST_OSLog)
8417       .Default(FST_Unknown);
8418 }
8419 
8420 /// CheckFormatArguments - Check calls to printf and scanf (and similar
8421 /// functions) for correct use of format strings.
8422 /// Returns true if a format string has been fully checked.
8423 bool Sema::CheckFormatArguments(const FormatAttr *Format,
8424                                 ArrayRef<const Expr *> Args,
8425                                 bool IsCXXMember,
8426                                 VariadicCallType CallType,
8427                                 SourceLocation Loc, SourceRange Range,
8428                                 llvm::SmallBitVector &CheckedVarArgs) {
8429   FormatStringInfo FSI;
8430   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
8431     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
8432                                 FSI.FirstDataArg, GetFormatStringType(Format),
8433                                 CallType, Loc, Range, CheckedVarArgs);
8434   return false;
8435 }
8436 
8437 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8438                                 bool HasVAListArg, unsigned format_idx,
8439                                 unsigned firstDataArg, FormatStringType Type,
8440                                 VariadicCallType CallType,
8441                                 SourceLocation Loc, SourceRange Range,
8442                                 llvm::SmallBitVector &CheckedVarArgs) {
8443   // CHECK: printf/scanf-like function is called with no format string.
8444   if (format_idx >= Args.size()) {
8445     Diag(Loc, diag::warn_missing_format_string) << Range;
8446     return false;
8447   }
8448 
8449   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8450 
8451   // CHECK: format string is not a string literal.
8452   //
8453   // Dynamically generated format strings are difficult to
8454   // automatically vet at compile time.  Requiring that format strings
8455   // are string literals: (1) permits the checking of format strings by
8456   // the compiler and thereby (2) can practically remove the source of
8457   // many format string exploits.
8458 
8459   // Format string can be either ObjC string (e.g. @"%d") or
8460   // C string (e.g. "%d")
8461   // ObjC string uses the same format specifiers as C string, so we can use
8462   // the same format string checking logic for both ObjC and C strings.
8463   UncoveredArgHandler UncoveredArg;
8464   StringLiteralCheckType CT =
8465       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8466                             format_idx, firstDataArg, Type, CallType,
8467                             /*IsFunctionCall*/ true, CheckedVarArgs,
8468                             UncoveredArg,
8469                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8470 
8471   // Generate a diagnostic where an uncovered argument is detected.
8472   if (UncoveredArg.hasUncoveredArg()) {
8473     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8474     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8475     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8476   }
8477 
8478   if (CT != SLCT_NotALiteral)
8479     // Literal format string found, check done!
8480     return CT == SLCT_CheckedLiteral;
8481 
8482   // Strftime is particular as it always uses a single 'time' argument,
8483   // so it is safe to pass a non-literal string.
8484   if (Type == FST_Strftime)
8485     return false;
8486 
8487   // Do not emit diag when the string param is a macro expansion and the
8488   // format is either NSString or CFString. This is a hack to prevent
8489   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8490   // which are usually used in place of NS and CF string literals.
8491   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8492   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8493     return false;
8494 
8495   // If there are no arguments specified, warn with -Wformat-security, otherwise
8496   // warn only with -Wformat-nonliteral.
8497   if (Args.size() == firstDataArg) {
8498     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8499       << OrigFormatExpr->getSourceRange();
8500     switch (Type) {
8501     default:
8502       break;
8503     case FST_Kprintf:
8504     case FST_FreeBSDKPrintf:
8505     case FST_Printf:
8506       Diag(FormatLoc, diag::note_format_security_fixit)
8507         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8508       break;
8509     case FST_NSString:
8510       Diag(FormatLoc, diag::note_format_security_fixit)
8511         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8512       break;
8513     }
8514   } else {
8515     Diag(FormatLoc, diag::warn_format_nonliteral)
8516       << OrigFormatExpr->getSourceRange();
8517   }
8518   return false;
8519 }
8520 
8521 namespace {
8522 
8523 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8524 protected:
8525   Sema &S;
8526   const FormatStringLiteral *FExpr;
8527   const Expr *OrigFormatExpr;
8528   const Sema::FormatStringType FSType;
8529   const unsigned FirstDataArg;
8530   const unsigned NumDataArgs;
8531   const char *Beg; // Start of format string.
8532   const bool HasVAListArg;
8533   ArrayRef<const Expr *> Args;
8534   unsigned FormatIdx;
8535   llvm::SmallBitVector CoveredArgs;
8536   bool usesPositionalArgs = false;
8537   bool atFirstArg = true;
8538   bool inFunctionCall;
8539   Sema::VariadicCallType CallType;
8540   llvm::SmallBitVector &CheckedVarArgs;
8541   UncoveredArgHandler &UncoveredArg;
8542 
8543 public:
8544   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8545                      const Expr *origFormatExpr,
8546                      const Sema::FormatStringType type, unsigned firstDataArg,
8547                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8548                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8549                      bool inFunctionCall, Sema::VariadicCallType callType,
8550                      llvm::SmallBitVector &CheckedVarArgs,
8551                      UncoveredArgHandler &UncoveredArg)
8552       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8553         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8554         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8555         inFunctionCall(inFunctionCall), CallType(callType),
8556         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8557     CoveredArgs.resize(numDataArgs);
8558     CoveredArgs.reset();
8559   }
8560 
8561   void DoneProcessing();
8562 
8563   void HandleIncompleteSpecifier(const char *startSpecifier,
8564                                  unsigned specifierLen) override;
8565 
8566   void HandleInvalidLengthModifier(
8567                            const analyze_format_string::FormatSpecifier &FS,
8568                            const analyze_format_string::ConversionSpecifier &CS,
8569                            const char *startSpecifier, unsigned specifierLen,
8570                            unsigned DiagID);
8571 
8572   void HandleNonStandardLengthModifier(
8573                     const analyze_format_string::FormatSpecifier &FS,
8574                     const char *startSpecifier, unsigned specifierLen);
8575 
8576   void HandleNonStandardConversionSpecifier(
8577                     const analyze_format_string::ConversionSpecifier &CS,
8578                     const char *startSpecifier, unsigned specifierLen);
8579 
8580   void HandlePosition(const char *startPos, unsigned posLen) override;
8581 
8582   void HandleInvalidPosition(const char *startSpecifier,
8583                              unsigned specifierLen,
8584                              analyze_format_string::PositionContext p) override;
8585 
8586   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8587 
8588   void HandleNullChar(const char *nullCharacter) override;
8589 
8590   template <typename Range>
8591   static void
8592   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8593                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8594                        bool IsStringLocation, Range StringRange,
8595                        ArrayRef<FixItHint> Fixit = None);
8596 
8597 protected:
8598   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8599                                         const char *startSpec,
8600                                         unsigned specifierLen,
8601                                         const char *csStart, unsigned csLen);
8602 
8603   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8604                                          const char *startSpec,
8605                                          unsigned specifierLen);
8606 
8607   SourceRange getFormatStringRange();
8608   CharSourceRange getSpecifierRange(const char *startSpecifier,
8609                                     unsigned specifierLen);
8610   SourceLocation getLocationOfByte(const char *x);
8611 
8612   const Expr *getDataArg(unsigned i) const;
8613 
8614   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8615                     const analyze_format_string::ConversionSpecifier &CS,
8616                     const char *startSpecifier, unsigned specifierLen,
8617                     unsigned argIndex);
8618 
8619   template <typename Range>
8620   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8621                             bool IsStringLocation, Range StringRange,
8622                             ArrayRef<FixItHint> Fixit = None);
8623 };
8624 
8625 } // namespace
8626 
8627 SourceRange CheckFormatHandler::getFormatStringRange() {
8628   return OrigFormatExpr->getSourceRange();
8629 }
8630 
8631 CharSourceRange CheckFormatHandler::
8632 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8633   SourceLocation Start = getLocationOfByte(startSpecifier);
8634   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8635 
8636   // Advance the end SourceLocation by one due to half-open ranges.
8637   End = End.getLocWithOffset(1);
8638 
8639   return CharSourceRange::getCharRange(Start, End);
8640 }
8641 
8642 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8643   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8644                                   S.getLangOpts(), S.Context.getTargetInfo());
8645 }
8646 
8647 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8648                                                    unsigned specifierLen){
8649   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8650                        getLocationOfByte(startSpecifier),
8651                        /*IsStringLocation*/true,
8652                        getSpecifierRange(startSpecifier, specifierLen));
8653 }
8654 
8655 void CheckFormatHandler::HandleInvalidLengthModifier(
8656     const analyze_format_string::FormatSpecifier &FS,
8657     const analyze_format_string::ConversionSpecifier &CS,
8658     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8659   using namespace analyze_format_string;
8660 
8661   const LengthModifier &LM = FS.getLengthModifier();
8662   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8663 
8664   // See if we know how to fix this length modifier.
8665   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8666   if (FixedLM) {
8667     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8668                          getLocationOfByte(LM.getStart()),
8669                          /*IsStringLocation*/true,
8670                          getSpecifierRange(startSpecifier, specifierLen));
8671 
8672     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8673       << FixedLM->toString()
8674       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8675 
8676   } else {
8677     FixItHint Hint;
8678     if (DiagID == diag::warn_format_nonsensical_length)
8679       Hint = FixItHint::CreateRemoval(LMRange);
8680 
8681     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8682                          getLocationOfByte(LM.getStart()),
8683                          /*IsStringLocation*/true,
8684                          getSpecifierRange(startSpecifier, specifierLen),
8685                          Hint);
8686   }
8687 }
8688 
8689 void CheckFormatHandler::HandleNonStandardLengthModifier(
8690     const analyze_format_string::FormatSpecifier &FS,
8691     const char *startSpecifier, unsigned specifierLen) {
8692   using namespace analyze_format_string;
8693 
8694   const LengthModifier &LM = FS.getLengthModifier();
8695   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8696 
8697   // See if we know how to fix this length modifier.
8698   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8699   if (FixedLM) {
8700     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8701                            << LM.toString() << 0,
8702                          getLocationOfByte(LM.getStart()),
8703                          /*IsStringLocation*/true,
8704                          getSpecifierRange(startSpecifier, specifierLen));
8705 
8706     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8707       << FixedLM->toString()
8708       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8709 
8710   } else {
8711     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8712                            << LM.toString() << 0,
8713                          getLocationOfByte(LM.getStart()),
8714                          /*IsStringLocation*/true,
8715                          getSpecifierRange(startSpecifier, specifierLen));
8716   }
8717 }
8718 
8719 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8720     const analyze_format_string::ConversionSpecifier &CS,
8721     const char *startSpecifier, unsigned specifierLen) {
8722   using namespace analyze_format_string;
8723 
8724   // See if we know how to fix this conversion specifier.
8725   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8726   if (FixedCS) {
8727     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8728                           << CS.toString() << /*conversion specifier*/1,
8729                          getLocationOfByte(CS.getStart()),
8730                          /*IsStringLocation*/true,
8731                          getSpecifierRange(startSpecifier, specifierLen));
8732 
8733     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8734     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8735       << FixedCS->toString()
8736       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8737   } else {
8738     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8739                           << CS.toString() << /*conversion specifier*/1,
8740                          getLocationOfByte(CS.getStart()),
8741                          /*IsStringLocation*/true,
8742                          getSpecifierRange(startSpecifier, specifierLen));
8743   }
8744 }
8745 
8746 void CheckFormatHandler::HandlePosition(const char *startPos,
8747                                         unsigned posLen) {
8748   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8749                                getLocationOfByte(startPos),
8750                                /*IsStringLocation*/true,
8751                                getSpecifierRange(startPos, posLen));
8752 }
8753 
8754 void
8755 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8756                                      analyze_format_string::PositionContext p) {
8757   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8758                          << (unsigned) p,
8759                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8760                        getSpecifierRange(startPos, posLen));
8761 }
8762 
8763 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8764                                             unsigned posLen) {
8765   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8766                                getLocationOfByte(startPos),
8767                                /*IsStringLocation*/true,
8768                                getSpecifierRange(startPos, posLen));
8769 }
8770 
8771 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8772   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8773     // The presence of a null character is likely an error.
8774     EmitFormatDiagnostic(
8775       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8776       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8777       getFormatStringRange());
8778   }
8779 }
8780 
8781 // Note that this may return NULL if there was an error parsing or building
8782 // one of the argument expressions.
8783 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8784   return Args[FirstDataArg + i];
8785 }
8786 
8787 void CheckFormatHandler::DoneProcessing() {
8788   // Does the number of data arguments exceed the number of
8789   // format conversions in the format string?
8790   if (!HasVAListArg) {
8791       // Find any arguments that weren't covered.
8792     CoveredArgs.flip();
8793     signed notCoveredArg = CoveredArgs.find_first();
8794     if (notCoveredArg >= 0) {
8795       assert((unsigned)notCoveredArg < NumDataArgs);
8796       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8797     } else {
8798       UncoveredArg.setAllCovered();
8799     }
8800   }
8801 }
8802 
8803 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8804                                    const Expr *ArgExpr) {
8805   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8806          "Invalid state");
8807 
8808   if (!ArgExpr)
8809     return;
8810 
8811   SourceLocation Loc = ArgExpr->getBeginLoc();
8812 
8813   if (S.getSourceManager().isInSystemMacro(Loc))
8814     return;
8815 
8816   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8817   for (auto E : DiagnosticExprs)
8818     PDiag << E->getSourceRange();
8819 
8820   CheckFormatHandler::EmitFormatDiagnostic(
8821                                   S, IsFunctionCall, DiagnosticExprs[0],
8822                                   PDiag, Loc, /*IsStringLocation*/false,
8823                                   DiagnosticExprs[0]->getSourceRange());
8824 }
8825 
8826 bool
8827 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8828                                                      SourceLocation Loc,
8829                                                      const char *startSpec,
8830                                                      unsigned specifierLen,
8831                                                      const char *csStart,
8832                                                      unsigned csLen) {
8833   bool keepGoing = true;
8834   if (argIndex < NumDataArgs) {
8835     // Consider the argument coverered, even though the specifier doesn't
8836     // make sense.
8837     CoveredArgs.set(argIndex);
8838   }
8839   else {
8840     // If argIndex exceeds the number of data arguments we
8841     // don't issue a warning because that is just a cascade of warnings (and
8842     // they may have intended '%%' anyway). We don't want to continue processing
8843     // the format string after this point, however, as we will like just get
8844     // gibberish when trying to match arguments.
8845     keepGoing = false;
8846   }
8847 
8848   StringRef Specifier(csStart, csLen);
8849 
8850   // If the specifier in non-printable, it could be the first byte of a UTF-8
8851   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8852   // hex value.
8853   std::string CodePointStr;
8854   if (!llvm::sys::locale::isPrint(*csStart)) {
8855     llvm::UTF32 CodePoint;
8856     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8857     const llvm::UTF8 *E =
8858         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8859     llvm::ConversionResult Result =
8860         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8861 
8862     if (Result != llvm::conversionOK) {
8863       unsigned char FirstChar = *csStart;
8864       CodePoint = (llvm::UTF32)FirstChar;
8865     }
8866 
8867     llvm::raw_string_ostream OS(CodePointStr);
8868     if (CodePoint < 256)
8869       OS << "\\x" << llvm::format("%02x", CodePoint);
8870     else if (CodePoint <= 0xFFFF)
8871       OS << "\\u" << llvm::format("%04x", CodePoint);
8872     else
8873       OS << "\\U" << llvm::format("%08x", CodePoint);
8874     OS.flush();
8875     Specifier = CodePointStr;
8876   }
8877 
8878   EmitFormatDiagnostic(
8879       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8880       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8881 
8882   return keepGoing;
8883 }
8884 
8885 void
8886 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8887                                                       const char *startSpec,
8888                                                       unsigned specifierLen) {
8889   EmitFormatDiagnostic(
8890     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8891     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8892 }
8893 
8894 bool
8895 CheckFormatHandler::CheckNumArgs(
8896   const analyze_format_string::FormatSpecifier &FS,
8897   const analyze_format_string::ConversionSpecifier &CS,
8898   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8899 
8900   if (argIndex >= NumDataArgs) {
8901     PartialDiagnostic PDiag = FS.usesPositionalArg()
8902       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8903            << (argIndex+1) << NumDataArgs)
8904       : S.PDiag(diag::warn_printf_insufficient_data_args);
8905     EmitFormatDiagnostic(
8906       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8907       getSpecifierRange(startSpecifier, specifierLen));
8908 
8909     // Since more arguments than conversion tokens are given, by extension
8910     // all arguments are covered, so mark this as so.
8911     UncoveredArg.setAllCovered();
8912     return false;
8913   }
8914   return true;
8915 }
8916 
8917 template<typename Range>
8918 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8919                                               SourceLocation Loc,
8920                                               bool IsStringLocation,
8921                                               Range StringRange,
8922                                               ArrayRef<FixItHint> FixIt) {
8923   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8924                        Loc, IsStringLocation, StringRange, FixIt);
8925 }
8926 
8927 /// If the format string is not within the function call, emit a note
8928 /// so that the function call and string are in diagnostic messages.
8929 ///
8930 /// \param InFunctionCall if true, the format string is within the function
8931 /// call and only one diagnostic message will be produced.  Otherwise, an
8932 /// extra note will be emitted pointing to location of the format string.
8933 ///
8934 /// \param ArgumentExpr the expression that is passed as the format string
8935 /// argument in the function call.  Used for getting locations when two
8936 /// diagnostics are emitted.
8937 ///
8938 /// \param PDiag the callee should already have provided any strings for the
8939 /// diagnostic message.  This function only adds locations and fixits
8940 /// to diagnostics.
8941 ///
8942 /// \param Loc primary location for diagnostic.  If two diagnostics are
8943 /// required, one will be at Loc and a new SourceLocation will be created for
8944 /// the other one.
8945 ///
8946 /// \param IsStringLocation if true, Loc points to the format string should be
8947 /// used for the note.  Otherwise, Loc points to the argument list and will
8948 /// be used with PDiag.
8949 ///
8950 /// \param StringRange some or all of the string to highlight.  This is
8951 /// templated so it can accept either a CharSourceRange or a SourceRange.
8952 ///
8953 /// \param FixIt optional fix it hint for the format string.
8954 template <typename Range>
8955 void CheckFormatHandler::EmitFormatDiagnostic(
8956     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8957     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8958     Range StringRange, ArrayRef<FixItHint> FixIt) {
8959   if (InFunctionCall) {
8960     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8961     D << StringRange;
8962     D << FixIt;
8963   } else {
8964     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8965       << ArgumentExpr->getSourceRange();
8966 
8967     const Sema::SemaDiagnosticBuilder &Note =
8968       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8969              diag::note_format_string_defined);
8970 
8971     Note << StringRange;
8972     Note << FixIt;
8973   }
8974 }
8975 
8976 //===--- CHECK: Printf format string checking ------------------------------===//
8977 
8978 namespace {
8979 
8980 class CheckPrintfHandler : public CheckFormatHandler {
8981 public:
8982   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8983                      const Expr *origFormatExpr,
8984                      const Sema::FormatStringType type, unsigned firstDataArg,
8985                      unsigned numDataArgs, bool isObjC, const char *beg,
8986                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8987                      unsigned formatIdx, bool inFunctionCall,
8988                      Sema::VariadicCallType CallType,
8989                      llvm::SmallBitVector &CheckedVarArgs,
8990                      UncoveredArgHandler &UncoveredArg)
8991       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8992                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8993                            inFunctionCall, CallType, CheckedVarArgs,
8994                            UncoveredArg) {}
8995 
8996   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8997 
8998   /// Returns true if '%@' specifiers are allowed in the format string.
8999   bool allowsObjCArg() const {
9000     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
9001            FSType == Sema::FST_OSTrace;
9002   }
9003 
9004   bool HandleInvalidPrintfConversionSpecifier(
9005                                       const analyze_printf::PrintfSpecifier &FS,
9006                                       const char *startSpecifier,
9007                                       unsigned specifierLen) override;
9008 
9009   void handleInvalidMaskType(StringRef MaskType) override;
9010 
9011   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
9012                              const char *startSpecifier, unsigned specifierLen,
9013                              const TargetInfo &Target) override;
9014   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9015                        const char *StartSpecifier,
9016                        unsigned SpecifierLen,
9017                        const Expr *E);
9018 
9019   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
9020                     const char *startSpecifier, unsigned specifierLen);
9021   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
9022                            const analyze_printf::OptionalAmount &Amt,
9023                            unsigned type,
9024                            const char *startSpecifier, unsigned specifierLen);
9025   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
9026                   const analyze_printf::OptionalFlag &flag,
9027                   const char *startSpecifier, unsigned specifierLen);
9028   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
9029                          const analyze_printf::OptionalFlag &ignoredFlag,
9030                          const analyze_printf::OptionalFlag &flag,
9031                          const char *startSpecifier, unsigned specifierLen);
9032   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
9033                            const Expr *E);
9034 
9035   void HandleEmptyObjCModifierFlag(const char *startFlag,
9036                                    unsigned flagLen) override;
9037 
9038   void HandleInvalidObjCModifierFlag(const char *startFlag,
9039                                             unsigned flagLen) override;
9040 
9041   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
9042                                            const char *flagsEnd,
9043                                            const char *conversionPosition)
9044                                              override;
9045 };
9046 
9047 } // namespace
9048 
9049 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
9050                                       const analyze_printf::PrintfSpecifier &FS,
9051                                       const char *startSpecifier,
9052                                       unsigned specifierLen) {
9053   const analyze_printf::PrintfConversionSpecifier &CS =
9054     FS.getConversionSpecifier();
9055 
9056   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9057                                           getLocationOfByte(CS.getStart()),
9058                                           startSpecifier, specifierLen,
9059                                           CS.getStart(), CS.getLength());
9060 }
9061 
9062 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
9063   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
9064 }
9065 
9066 bool CheckPrintfHandler::HandleAmount(
9067                                const analyze_format_string::OptionalAmount &Amt,
9068                                unsigned k, const char *startSpecifier,
9069                                unsigned specifierLen) {
9070   if (Amt.hasDataArgument()) {
9071     if (!HasVAListArg) {
9072       unsigned argIndex = Amt.getArgIndex();
9073       if (argIndex >= NumDataArgs) {
9074         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
9075                                << k,
9076                              getLocationOfByte(Amt.getStart()),
9077                              /*IsStringLocation*/true,
9078                              getSpecifierRange(startSpecifier, specifierLen));
9079         // Don't do any more checking.  We will just emit
9080         // spurious errors.
9081         return false;
9082       }
9083 
9084       // Type check the data argument.  It should be an 'int'.
9085       // Although not in conformance with C99, we also allow the argument to be
9086       // an 'unsigned int' as that is a reasonably safe case.  GCC also
9087       // doesn't emit a warning for that case.
9088       CoveredArgs.set(argIndex);
9089       const Expr *Arg = getDataArg(argIndex);
9090       if (!Arg)
9091         return false;
9092 
9093       QualType T = Arg->getType();
9094 
9095       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
9096       assert(AT.isValid());
9097 
9098       if (!AT.matchesType(S.Context, T)) {
9099         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
9100                                << k << AT.getRepresentativeTypeName(S.Context)
9101                                << T << Arg->getSourceRange(),
9102                              getLocationOfByte(Amt.getStart()),
9103                              /*IsStringLocation*/true,
9104                              getSpecifierRange(startSpecifier, specifierLen));
9105         // Don't do any more checking.  We will just emit
9106         // spurious errors.
9107         return false;
9108       }
9109     }
9110   }
9111   return true;
9112 }
9113 
9114 void CheckPrintfHandler::HandleInvalidAmount(
9115                                       const analyze_printf::PrintfSpecifier &FS,
9116                                       const analyze_printf::OptionalAmount &Amt,
9117                                       unsigned type,
9118                                       const char *startSpecifier,
9119                                       unsigned specifierLen) {
9120   const analyze_printf::PrintfConversionSpecifier &CS =
9121     FS.getConversionSpecifier();
9122 
9123   FixItHint fixit =
9124     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
9125       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
9126                                  Amt.getConstantLength()))
9127       : FixItHint();
9128 
9129   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
9130                          << type << CS.toString(),
9131                        getLocationOfByte(Amt.getStart()),
9132                        /*IsStringLocation*/true,
9133                        getSpecifierRange(startSpecifier, specifierLen),
9134                        fixit);
9135 }
9136 
9137 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
9138                                     const analyze_printf::OptionalFlag &flag,
9139                                     const char *startSpecifier,
9140                                     unsigned specifierLen) {
9141   // Warn about pointless flag with a fixit removal.
9142   const analyze_printf::PrintfConversionSpecifier &CS =
9143     FS.getConversionSpecifier();
9144   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
9145                          << flag.toString() << CS.toString(),
9146                        getLocationOfByte(flag.getPosition()),
9147                        /*IsStringLocation*/true,
9148                        getSpecifierRange(startSpecifier, specifierLen),
9149                        FixItHint::CreateRemoval(
9150                          getSpecifierRange(flag.getPosition(), 1)));
9151 }
9152 
9153 void CheckPrintfHandler::HandleIgnoredFlag(
9154                                 const analyze_printf::PrintfSpecifier &FS,
9155                                 const analyze_printf::OptionalFlag &ignoredFlag,
9156                                 const analyze_printf::OptionalFlag &flag,
9157                                 const char *startSpecifier,
9158                                 unsigned specifierLen) {
9159   // Warn about ignored flag with a fixit removal.
9160   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
9161                          << ignoredFlag.toString() << flag.toString(),
9162                        getLocationOfByte(ignoredFlag.getPosition()),
9163                        /*IsStringLocation*/true,
9164                        getSpecifierRange(startSpecifier, specifierLen),
9165                        FixItHint::CreateRemoval(
9166                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
9167 }
9168 
9169 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
9170                                                      unsigned flagLen) {
9171   // Warn about an empty flag.
9172   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
9173                        getLocationOfByte(startFlag),
9174                        /*IsStringLocation*/true,
9175                        getSpecifierRange(startFlag, flagLen));
9176 }
9177 
9178 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
9179                                                        unsigned flagLen) {
9180   // Warn about an invalid flag.
9181   auto Range = getSpecifierRange(startFlag, flagLen);
9182   StringRef flag(startFlag, flagLen);
9183   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
9184                       getLocationOfByte(startFlag),
9185                       /*IsStringLocation*/true,
9186                       Range, FixItHint::CreateRemoval(Range));
9187 }
9188 
9189 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
9190     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
9191     // Warn about using '[...]' without a '@' conversion.
9192     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
9193     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
9194     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
9195                          getLocationOfByte(conversionPosition),
9196                          /*IsStringLocation*/true,
9197                          Range, FixItHint::CreateRemoval(Range));
9198 }
9199 
9200 // Determines if the specified is a C++ class or struct containing
9201 // a member with the specified name and kind (e.g. a CXXMethodDecl named
9202 // "c_str()").
9203 template<typename MemberKind>
9204 static llvm::SmallPtrSet<MemberKind*, 1>
9205 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9206   const RecordType *RT = Ty->getAs<RecordType>();
9207   llvm::SmallPtrSet<MemberKind*, 1> Results;
9208 
9209   if (!RT)
9210     return Results;
9211   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
9212   if (!RD || !RD->getDefinition())
9213     return Results;
9214 
9215   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9216                  Sema::LookupMemberName);
9217   R.suppressDiagnostics();
9218 
9219   // We just need to include all members of the right kind turned up by the
9220   // filter, at this point.
9221   if (S.LookupQualifiedName(R, RT->getDecl()))
9222     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9223       NamedDecl *decl = (*I)->getUnderlyingDecl();
9224       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9225         Results.insert(FK);
9226     }
9227   return Results;
9228 }
9229 
9230 /// Check if we could call '.c_str()' on an object.
9231 ///
9232 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9233 /// allow the call, or if it would be ambiguous).
9234 bool Sema::hasCStrMethod(const Expr *E) {
9235   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9236 
9237   MethodSet Results =
9238       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
9239   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9240        MI != ME; ++MI)
9241     if ((*MI)->getMinRequiredArguments() == 0)
9242       return true;
9243   return false;
9244 }
9245 
9246 // Check if a (w)string was passed when a (w)char* was needed, and offer a
9247 // better diagnostic if so. AT is assumed to be valid.
9248 // Returns true when a c_str() conversion method is found.
9249 bool CheckPrintfHandler::checkForCStrMembers(
9250     const analyze_printf::ArgType &AT, const Expr *E) {
9251   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9252 
9253   MethodSet Results =
9254       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
9255 
9256   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9257        MI != ME; ++MI) {
9258     const CXXMethodDecl *Method = *MI;
9259     if (Method->getMinRequiredArguments() == 0 &&
9260         AT.matchesType(S.Context, Method->getReturnType())) {
9261       // FIXME: Suggest parens if the expression needs them.
9262       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
9263       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
9264           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
9265       return true;
9266     }
9267   }
9268 
9269   return false;
9270 }
9271 
9272 bool CheckPrintfHandler::HandlePrintfSpecifier(
9273     const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9274     unsigned specifierLen, const TargetInfo &Target) {
9275   using namespace analyze_format_string;
9276   using namespace analyze_printf;
9277 
9278   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9279 
9280   if (FS.consumesDataArgument()) {
9281     if (atFirstArg) {
9282         atFirstArg = false;
9283         usesPositionalArgs = FS.usesPositionalArg();
9284     }
9285     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9286       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9287                                         startSpecifier, specifierLen);
9288       return false;
9289     }
9290   }
9291 
9292   // First check if the field width, precision, and conversion specifier
9293   // have matching data arguments.
9294   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
9295                     startSpecifier, specifierLen)) {
9296     return false;
9297   }
9298 
9299   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
9300                     startSpecifier, specifierLen)) {
9301     return false;
9302   }
9303 
9304   if (!CS.consumesDataArgument()) {
9305     // FIXME: Technically specifying a precision or field width here
9306     // makes no sense.  Worth issuing a warning at some point.
9307     return true;
9308   }
9309 
9310   // Consume the argument.
9311   unsigned argIndex = FS.getArgIndex();
9312   if (argIndex < NumDataArgs) {
9313     // The check to see if the argIndex is valid will come later.
9314     // We set the bit here because we may exit early from this
9315     // function if we encounter some other error.
9316     CoveredArgs.set(argIndex);
9317   }
9318 
9319   // FreeBSD kernel extensions.
9320   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9321       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9322     // We need at least two arguments.
9323     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9324       return false;
9325 
9326     // Claim the second argument.
9327     CoveredArgs.set(argIndex + 1);
9328 
9329     // Type check the first argument (int for %b, pointer for %D)
9330     const Expr *Ex = getDataArg(argIndex);
9331     const analyze_printf::ArgType &AT =
9332       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
9333         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
9334     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9335       EmitFormatDiagnostic(
9336           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9337               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9338               << false << Ex->getSourceRange(),
9339           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9340           getSpecifierRange(startSpecifier, specifierLen));
9341 
9342     // Type check the second argument (char * for both %b and %D)
9343     Ex = getDataArg(argIndex + 1);
9344     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
9345     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9346       EmitFormatDiagnostic(
9347           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9348               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9349               << false << Ex->getSourceRange(),
9350           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9351           getSpecifierRange(startSpecifier, specifierLen));
9352 
9353      return true;
9354   }
9355 
9356   // Check for using an Objective-C specific conversion specifier
9357   // in a non-ObjC literal.
9358   if (!allowsObjCArg() && CS.isObjCArg()) {
9359     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9360                                                   specifierLen);
9361   }
9362 
9363   // %P can only be used with os_log.
9364   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
9365     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9366                                                   specifierLen);
9367   }
9368 
9369   // %n is not allowed with os_log.
9370   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
9371     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9372                          getLocationOfByte(CS.getStart()),
9373                          /*IsStringLocation*/ false,
9374                          getSpecifierRange(startSpecifier, specifierLen));
9375 
9376     return true;
9377   }
9378 
9379   // Only scalars are allowed for os_trace.
9380   if (FSType == Sema::FST_OSTrace &&
9381       (CS.getKind() == ConversionSpecifier::PArg ||
9382        CS.getKind() == ConversionSpecifier::sArg ||
9383        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9384     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9385                                                   specifierLen);
9386   }
9387 
9388   // Check for use of public/private annotation outside of os_log().
9389   if (FSType != Sema::FST_OSLog) {
9390     if (FS.isPublic().isSet()) {
9391       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9392                                << "public",
9393                            getLocationOfByte(FS.isPublic().getPosition()),
9394                            /*IsStringLocation*/ false,
9395                            getSpecifierRange(startSpecifier, specifierLen));
9396     }
9397     if (FS.isPrivate().isSet()) {
9398       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9399                                << "private",
9400                            getLocationOfByte(FS.isPrivate().getPosition()),
9401                            /*IsStringLocation*/ false,
9402                            getSpecifierRange(startSpecifier, specifierLen));
9403     }
9404   }
9405 
9406   const llvm::Triple &Triple = Target.getTriple();
9407   if (CS.getKind() == ConversionSpecifier::nArg &&
9408       (Triple.isAndroid() || Triple.isOSFuchsia())) {
9409     EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
9410                          getLocationOfByte(CS.getStart()),
9411                          /*IsStringLocation*/ false,
9412                          getSpecifierRange(startSpecifier, specifierLen));
9413   }
9414 
9415   // Check for invalid use of field width
9416   if (!FS.hasValidFieldWidth()) {
9417     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9418         startSpecifier, specifierLen);
9419   }
9420 
9421   // Check for invalid use of precision
9422   if (!FS.hasValidPrecision()) {
9423     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9424         startSpecifier, specifierLen);
9425   }
9426 
9427   // Precision is mandatory for %P specifier.
9428   if (CS.getKind() == ConversionSpecifier::PArg &&
9429       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9430     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9431                          getLocationOfByte(startSpecifier),
9432                          /*IsStringLocation*/ false,
9433                          getSpecifierRange(startSpecifier, specifierLen));
9434   }
9435 
9436   // Check each flag does not conflict with any other component.
9437   if (!FS.hasValidThousandsGroupingPrefix())
9438     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9439   if (!FS.hasValidLeadingZeros())
9440     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9441   if (!FS.hasValidPlusPrefix())
9442     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9443   if (!FS.hasValidSpacePrefix())
9444     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9445   if (!FS.hasValidAlternativeForm())
9446     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9447   if (!FS.hasValidLeftJustified())
9448     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9449 
9450   // Check that flags are not ignored by another flag
9451   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9452     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9453         startSpecifier, specifierLen);
9454   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9455     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9456             startSpecifier, specifierLen);
9457 
9458   // Check the length modifier is valid with the given conversion specifier.
9459   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9460                                  S.getLangOpts()))
9461     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9462                                 diag::warn_format_nonsensical_length);
9463   else if (!FS.hasStandardLengthModifier())
9464     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9465   else if (!FS.hasStandardLengthConversionCombination())
9466     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9467                                 diag::warn_format_non_standard_conversion_spec);
9468 
9469   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9470     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9471 
9472   // The remaining checks depend on the data arguments.
9473   if (HasVAListArg)
9474     return true;
9475 
9476   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9477     return false;
9478 
9479   const Expr *Arg = getDataArg(argIndex);
9480   if (!Arg)
9481     return true;
9482 
9483   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9484 }
9485 
9486 static bool requiresParensToAddCast(const Expr *E) {
9487   // FIXME: We should have a general way to reason about operator
9488   // precedence and whether parens are actually needed here.
9489   // Take care of a few common cases where they aren't.
9490   const Expr *Inside = E->IgnoreImpCasts();
9491   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9492     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9493 
9494   switch (Inside->getStmtClass()) {
9495   case Stmt::ArraySubscriptExprClass:
9496   case Stmt::CallExprClass:
9497   case Stmt::CharacterLiteralClass:
9498   case Stmt::CXXBoolLiteralExprClass:
9499   case Stmt::DeclRefExprClass:
9500   case Stmt::FloatingLiteralClass:
9501   case Stmt::IntegerLiteralClass:
9502   case Stmt::MemberExprClass:
9503   case Stmt::ObjCArrayLiteralClass:
9504   case Stmt::ObjCBoolLiteralExprClass:
9505   case Stmt::ObjCBoxedExprClass:
9506   case Stmt::ObjCDictionaryLiteralClass:
9507   case Stmt::ObjCEncodeExprClass:
9508   case Stmt::ObjCIvarRefExprClass:
9509   case Stmt::ObjCMessageExprClass:
9510   case Stmt::ObjCPropertyRefExprClass:
9511   case Stmt::ObjCStringLiteralClass:
9512   case Stmt::ObjCSubscriptRefExprClass:
9513   case Stmt::ParenExprClass:
9514   case Stmt::StringLiteralClass:
9515   case Stmt::UnaryOperatorClass:
9516     return false;
9517   default:
9518     return true;
9519   }
9520 }
9521 
9522 static std::pair<QualType, StringRef>
9523 shouldNotPrintDirectly(const ASTContext &Context,
9524                        QualType IntendedTy,
9525                        const Expr *E) {
9526   // Use a 'while' to peel off layers of typedefs.
9527   QualType TyTy = IntendedTy;
9528   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9529     StringRef Name = UserTy->getDecl()->getName();
9530     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9531       .Case("CFIndex", Context.getNSIntegerType())
9532       .Case("NSInteger", Context.getNSIntegerType())
9533       .Case("NSUInteger", Context.getNSUIntegerType())
9534       .Case("SInt32", Context.IntTy)
9535       .Case("UInt32", Context.UnsignedIntTy)
9536       .Default(QualType());
9537 
9538     if (!CastTy.isNull())
9539       return std::make_pair(CastTy, Name);
9540 
9541     TyTy = UserTy->desugar();
9542   }
9543 
9544   // Strip parens if necessary.
9545   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9546     return shouldNotPrintDirectly(Context,
9547                                   PE->getSubExpr()->getType(),
9548                                   PE->getSubExpr());
9549 
9550   // If this is a conditional expression, then its result type is constructed
9551   // via usual arithmetic conversions and thus there might be no necessary
9552   // typedef sugar there.  Recurse to operands to check for NSInteger &
9553   // Co. usage condition.
9554   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9555     QualType TrueTy, FalseTy;
9556     StringRef TrueName, FalseName;
9557 
9558     std::tie(TrueTy, TrueName) =
9559       shouldNotPrintDirectly(Context,
9560                              CO->getTrueExpr()->getType(),
9561                              CO->getTrueExpr());
9562     std::tie(FalseTy, FalseName) =
9563       shouldNotPrintDirectly(Context,
9564                              CO->getFalseExpr()->getType(),
9565                              CO->getFalseExpr());
9566 
9567     if (TrueTy == FalseTy)
9568       return std::make_pair(TrueTy, TrueName);
9569     else if (TrueTy.isNull())
9570       return std::make_pair(FalseTy, FalseName);
9571     else if (FalseTy.isNull())
9572       return std::make_pair(TrueTy, TrueName);
9573   }
9574 
9575   return std::make_pair(QualType(), StringRef());
9576 }
9577 
9578 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9579 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9580 /// type do not count.
9581 static bool
9582 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9583   QualType From = ICE->getSubExpr()->getType();
9584   QualType To = ICE->getType();
9585   // It's an integer promotion if the destination type is the promoted
9586   // source type.
9587   if (ICE->getCastKind() == CK_IntegralCast &&
9588       From->isPromotableIntegerType() &&
9589       S.Context.getPromotedIntegerType(From) == To)
9590     return true;
9591   // Look through vector types, since we do default argument promotion for
9592   // those in OpenCL.
9593   if (const auto *VecTy = From->getAs<ExtVectorType>())
9594     From = VecTy->getElementType();
9595   if (const auto *VecTy = To->getAs<ExtVectorType>())
9596     To = VecTy->getElementType();
9597   // It's a floating promotion if the source type is a lower rank.
9598   return ICE->getCastKind() == CK_FloatingCast &&
9599          S.Context.getFloatingTypeOrder(From, To) < 0;
9600 }
9601 
9602 bool
9603 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9604                                     const char *StartSpecifier,
9605                                     unsigned SpecifierLen,
9606                                     const Expr *E) {
9607   using namespace analyze_format_string;
9608   using namespace analyze_printf;
9609 
9610   // Now type check the data expression that matches the
9611   // format specifier.
9612   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9613   if (!AT.isValid())
9614     return true;
9615 
9616   QualType ExprTy = E->getType();
9617   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9618     ExprTy = TET->getUnderlyingExpr()->getType();
9619   }
9620 
9621   // Diagnose attempts to print a boolean value as a character. Unlike other
9622   // -Wformat diagnostics, this is fine from a type perspective, but it still
9623   // doesn't make sense.
9624   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9625       E->isKnownToHaveBooleanValue()) {
9626     const CharSourceRange &CSR =
9627         getSpecifierRange(StartSpecifier, SpecifierLen);
9628     SmallString<4> FSString;
9629     llvm::raw_svector_ostream os(FSString);
9630     FS.toString(os);
9631     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9632                              << FSString,
9633                          E->getExprLoc(), false, CSR);
9634     return true;
9635   }
9636 
9637   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9638   if (Match == analyze_printf::ArgType::Match)
9639     return true;
9640 
9641   // Look through argument promotions for our error message's reported type.
9642   // This includes the integral and floating promotions, but excludes array
9643   // and function pointer decay (seeing that an argument intended to be a
9644   // string has type 'char [6]' is probably more confusing than 'char *') and
9645   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9646   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9647     if (isArithmeticArgumentPromotion(S, ICE)) {
9648       E = ICE->getSubExpr();
9649       ExprTy = E->getType();
9650 
9651       // Check if we didn't match because of an implicit cast from a 'char'
9652       // or 'short' to an 'int'.  This is done because printf is a varargs
9653       // function.
9654       if (ICE->getType() == S.Context.IntTy ||
9655           ICE->getType() == S.Context.UnsignedIntTy) {
9656         // All further checking is done on the subexpression
9657         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9658             AT.matchesType(S.Context, ExprTy);
9659         if (ImplicitMatch == analyze_printf::ArgType::Match)
9660           return true;
9661         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9662             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9663           Match = ImplicitMatch;
9664       }
9665     }
9666   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9667     // Special case for 'a', which has type 'int' in C.
9668     // Note, however, that we do /not/ want to treat multibyte constants like
9669     // 'MooV' as characters! This form is deprecated but still exists. In
9670     // addition, don't treat expressions as of type 'char' if one byte length
9671     // modifier is provided.
9672     if (ExprTy == S.Context.IntTy &&
9673         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9674       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9675         ExprTy = S.Context.CharTy;
9676   }
9677 
9678   // Look through enums to their underlying type.
9679   bool IsEnum = false;
9680   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9681     ExprTy = EnumTy->getDecl()->getIntegerType();
9682     IsEnum = true;
9683   }
9684 
9685   // %C in an Objective-C context prints a unichar, not a wchar_t.
9686   // If the argument is an integer of some kind, believe the %C and suggest
9687   // a cast instead of changing the conversion specifier.
9688   QualType IntendedTy = ExprTy;
9689   if (isObjCContext() &&
9690       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9691     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9692         !ExprTy->isCharType()) {
9693       // 'unichar' is defined as a typedef of unsigned short, but we should
9694       // prefer using the typedef if it is visible.
9695       IntendedTy = S.Context.UnsignedShortTy;
9696 
9697       // While we are here, check if the value is an IntegerLiteral that happens
9698       // to be within the valid range.
9699       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9700         const llvm::APInt &V = IL->getValue();
9701         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9702           return true;
9703       }
9704 
9705       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9706                           Sema::LookupOrdinaryName);
9707       if (S.LookupName(Result, S.getCurScope())) {
9708         NamedDecl *ND = Result.getFoundDecl();
9709         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9710           if (TD->getUnderlyingType() == IntendedTy)
9711             IntendedTy = S.Context.getTypedefType(TD);
9712       }
9713     }
9714   }
9715 
9716   // Special-case some of Darwin's platform-independence types by suggesting
9717   // casts to primitive types that are known to be large enough.
9718   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9719   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9720     QualType CastTy;
9721     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9722     if (!CastTy.isNull()) {
9723       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9724       // (long in ASTContext). Only complain to pedants.
9725       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9726           (AT.isSizeT() || AT.isPtrdiffT()) &&
9727           AT.matchesType(S.Context, CastTy))
9728         Match = ArgType::NoMatchPedantic;
9729       IntendedTy = CastTy;
9730       ShouldNotPrintDirectly = true;
9731     }
9732   }
9733 
9734   // We may be able to offer a FixItHint if it is a supported type.
9735   PrintfSpecifier fixedFS = FS;
9736   bool Success =
9737       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9738 
9739   if (Success) {
9740     // Get the fix string from the fixed format specifier
9741     SmallString<16> buf;
9742     llvm::raw_svector_ostream os(buf);
9743     fixedFS.toString(os);
9744 
9745     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9746 
9747     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9748       unsigned Diag;
9749       switch (Match) {
9750       case ArgType::Match: llvm_unreachable("expected non-matching");
9751       case ArgType::NoMatchPedantic:
9752         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9753         break;
9754       case ArgType::NoMatchTypeConfusion:
9755         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9756         break;
9757       case ArgType::NoMatch:
9758         Diag = diag::warn_format_conversion_argument_type_mismatch;
9759         break;
9760       }
9761 
9762       // In this case, the specifier is wrong and should be changed to match
9763       // the argument.
9764       EmitFormatDiagnostic(S.PDiag(Diag)
9765                                << AT.getRepresentativeTypeName(S.Context)
9766                                << IntendedTy << IsEnum << E->getSourceRange(),
9767                            E->getBeginLoc(),
9768                            /*IsStringLocation*/ false, SpecRange,
9769                            FixItHint::CreateReplacement(SpecRange, os.str()));
9770     } else {
9771       // The canonical type for formatting this value is different from the
9772       // actual type of the expression. (This occurs, for example, with Darwin's
9773       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9774       // should be printed as 'long' for 64-bit compatibility.)
9775       // Rather than emitting a normal format/argument mismatch, we want to
9776       // add a cast to the recommended type (and correct the format string
9777       // if necessary).
9778       SmallString<16> CastBuf;
9779       llvm::raw_svector_ostream CastFix(CastBuf);
9780       CastFix << "(";
9781       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9782       CastFix << ")";
9783 
9784       SmallVector<FixItHint,4> Hints;
9785       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9786         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9787 
9788       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9789         // If there's already a cast present, just replace it.
9790         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9791         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9792 
9793       } else if (!requiresParensToAddCast(E)) {
9794         // If the expression has high enough precedence,
9795         // just write the C-style cast.
9796         Hints.push_back(
9797             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9798       } else {
9799         // Otherwise, add parens around the expression as well as the cast.
9800         CastFix << "(";
9801         Hints.push_back(
9802             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9803 
9804         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9805         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9806       }
9807 
9808       if (ShouldNotPrintDirectly) {
9809         // The expression has a type that should not be printed directly.
9810         // We extract the name from the typedef because we don't want to show
9811         // the underlying type in the diagnostic.
9812         StringRef Name;
9813         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9814           Name = TypedefTy->getDecl()->getName();
9815         else
9816           Name = CastTyName;
9817         unsigned Diag = Match == ArgType::NoMatchPedantic
9818                             ? diag::warn_format_argument_needs_cast_pedantic
9819                             : diag::warn_format_argument_needs_cast;
9820         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9821                                            << E->getSourceRange(),
9822                              E->getBeginLoc(), /*IsStringLocation=*/false,
9823                              SpecRange, Hints);
9824       } else {
9825         // In this case, the expression could be printed using a different
9826         // specifier, but we've decided that the specifier is probably correct
9827         // and we should cast instead. Just use the normal warning message.
9828         EmitFormatDiagnostic(
9829             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9830                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9831                 << E->getSourceRange(),
9832             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9833       }
9834     }
9835   } else {
9836     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9837                                                    SpecifierLen);
9838     // Since the warning for passing non-POD types to variadic functions
9839     // was deferred until now, we emit a warning for non-POD
9840     // arguments here.
9841     switch (S.isValidVarArgType(ExprTy)) {
9842     case Sema::VAK_Valid:
9843     case Sema::VAK_ValidInCXX11: {
9844       unsigned Diag;
9845       switch (Match) {
9846       case ArgType::Match: llvm_unreachable("expected non-matching");
9847       case ArgType::NoMatchPedantic:
9848         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9849         break;
9850       case ArgType::NoMatchTypeConfusion:
9851         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9852         break;
9853       case ArgType::NoMatch:
9854         Diag = diag::warn_format_conversion_argument_type_mismatch;
9855         break;
9856       }
9857 
9858       EmitFormatDiagnostic(
9859           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9860                         << IsEnum << CSR << E->getSourceRange(),
9861           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9862       break;
9863     }
9864     case Sema::VAK_Undefined:
9865     case Sema::VAK_MSVCUndefined:
9866       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9867                                << S.getLangOpts().CPlusPlus11 << ExprTy
9868                                << CallType
9869                                << AT.getRepresentativeTypeName(S.Context) << CSR
9870                                << E->getSourceRange(),
9871                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9872       checkForCStrMembers(AT, E);
9873       break;
9874 
9875     case Sema::VAK_Invalid:
9876       if (ExprTy->isObjCObjectType())
9877         EmitFormatDiagnostic(
9878             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9879                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9880                 << AT.getRepresentativeTypeName(S.Context) << CSR
9881                 << E->getSourceRange(),
9882             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9883       else
9884         // FIXME: If this is an initializer list, suggest removing the braces
9885         // or inserting a cast to the target type.
9886         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9887             << isa<InitListExpr>(E) << ExprTy << CallType
9888             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9889       break;
9890     }
9891 
9892     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9893            "format string specifier index out of range");
9894     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9895   }
9896 
9897   return true;
9898 }
9899 
9900 //===--- CHECK: Scanf format string checking ------------------------------===//
9901 
9902 namespace {
9903 
9904 class CheckScanfHandler : public CheckFormatHandler {
9905 public:
9906   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9907                     const Expr *origFormatExpr, Sema::FormatStringType type,
9908                     unsigned firstDataArg, unsigned numDataArgs,
9909                     const char *beg, bool hasVAListArg,
9910                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9911                     bool inFunctionCall, Sema::VariadicCallType CallType,
9912                     llvm::SmallBitVector &CheckedVarArgs,
9913                     UncoveredArgHandler &UncoveredArg)
9914       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9915                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9916                            inFunctionCall, CallType, CheckedVarArgs,
9917                            UncoveredArg) {}
9918 
9919   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9920                             const char *startSpecifier,
9921                             unsigned specifierLen) override;
9922 
9923   bool HandleInvalidScanfConversionSpecifier(
9924           const analyze_scanf::ScanfSpecifier &FS,
9925           const char *startSpecifier,
9926           unsigned specifierLen) override;
9927 
9928   void HandleIncompleteScanList(const char *start, const char *end) override;
9929 };
9930 
9931 } // namespace
9932 
9933 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9934                                                  const char *end) {
9935   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9936                        getLocationOfByte(end), /*IsStringLocation*/true,
9937                        getSpecifierRange(start, end - start));
9938 }
9939 
9940 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9941                                         const analyze_scanf::ScanfSpecifier &FS,
9942                                         const char *startSpecifier,
9943                                         unsigned specifierLen) {
9944   const analyze_scanf::ScanfConversionSpecifier &CS =
9945     FS.getConversionSpecifier();
9946 
9947   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9948                                           getLocationOfByte(CS.getStart()),
9949                                           startSpecifier, specifierLen,
9950                                           CS.getStart(), CS.getLength());
9951 }
9952 
9953 bool CheckScanfHandler::HandleScanfSpecifier(
9954                                        const analyze_scanf::ScanfSpecifier &FS,
9955                                        const char *startSpecifier,
9956                                        unsigned specifierLen) {
9957   using namespace analyze_scanf;
9958   using namespace analyze_format_string;
9959 
9960   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9961 
9962   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9963   // be used to decide if we are using positional arguments consistently.
9964   if (FS.consumesDataArgument()) {
9965     if (atFirstArg) {
9966       atFirstArg = false;
9967       usesPositionalArgs = FS.usesPositionalArg();
9968     }
9969     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9970       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9971                                         startSpecifier, specifierLen);
9972       return false;
9973     }
9974   }
9975 
9976   // Check if the field with is non-zero.
9977   const OptionalAmount &Amt = FS.getFieldWidth();
9978   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9979     if (Amt.getConstantAmount() == 0) {
9980       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9981                                                    Amt.getConstantLength());
9982       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9983                            getLocationOfByte(Amt.getStart()),
9984                            /*IsStringLocation*/true, R,
9985                            FixItHint::CreateRemoval(R));
9986     }
9987   }
9988 
9989   if (!FS.consumesDataArgument()) {
9990     // FIXME: Technically specifying a precision or field width here
9991     // makes no sense.  Worth issuing a warning at some point.
9992     return true;
9993   }
9994 
9995   // Consume the argument.
9996   unsigned argIndex = FS.getArgIndex();
9997   if (argIndex < NumDataArgs) {
9998       // The check to see if the argIndex is valid will come later.
9999       // We set the bit here because we may exit early from this
10000       // function if we encounter some other error.
10001     CoveredArgs.set(argIndex);
10002   }
10003 
10004   // Check the length modifier is valid with the given conversion specifier.
10005   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
10006                                  S.getLangOpts()))
10007     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10008                                 diag::warn_format_nonsensical_length);
10009   else if (!FS.hasStandardLengthModifier())
10010     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
10011   else if (!FS.hasStandardLengthConversionCombination())
10012     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10013                                 diag::warn_format_non_standard_conversion_spec);
10014 
10015   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
10016     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
10017 
10018   // The remaining checks depend on the data arguments.
10019   if (HasVAListArg)
10020     return true;
10021 
10022   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
10023     return false;
10024 
10025   // Check that the argument type matches the format specifier.
10026   const Expr *Ex = getDataArg(argIndex);
10027   if (!Ex)
10028     return true;
10029 
10030   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
10031 
10032   if (!AT.isValid()) {
10033     return true;
10034   }
10035 
10036   analyze_format_string::ArgType::MatchKind Match =
10037       AT.matchesType(S.Context, Ex->getType());
10038   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
10039   if (Match == analyze_format_string::ArgType::Match)
10040     return true;
10041 
10042   ScanfSpecifier fixedFS = FS;
10043   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
10044                                  S.getLangOpts(), S.Context);
10045 
10046   unsigned Diag =
10047       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
10048                : diag::warn_format_conversion_argument_type_mismatch;
10049 
10050   if (Success) {
10051     // Get the fix string from the fixed format specifier.
10052     SmallString<128> buf;
10053     llvm::raw_svector_ostream os(buf);
10054     fixedFS.toString(os);
10055 
10056     EmitFormatDiagnostic(
10057         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
10058                       << Ex->getType() << false << Ex->getSourceRange(),
10059         Ex->getBeginLoc(),
10060         /*IsStringLocation*/ false,
10061         getSpecifierRange(startSpecifier, specifierLen),
10062         FixItHint::CreateReplacement(
10063             getSpecifierRange(startSpecifier, specifierLen), os.str()));
10064   } else {
10065     EmitFormatDiagnostic(S.PDiag(Diag)
10066                              << AT.getRepresentativeTypeName(S.Context)
10067                              << Ex->getType() << false << Ex->getSourceRange(),
10068                          Ex->getBeginLoc(),
10069                          /*IsStringLocation*/ false,
10070                          getSpecifierRange(startSpecifier, specifierLen));
10071   }
10072 
10073   return true;
10074 }
10075 
10076 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
10077                               const Expr *OrigFormatExpr,
10078                               ArrayRef<const Expr *> Args,
10079                               bool HasVAListArg, unsigned format_idx,
10080                               unsigned firstDataArg,
10081                               Sema::FormatStringType Type,
10082                               bool inFunctionCall,
10083                               Sema::VariadicCallType CallType,
10084                               llvm::SmallBitVector &CheckedVarArgs,
10085                               UncoveredArgHandler &UncoveredArg,
10086                               bool IgnoreStringsWithoutSpecifiers) {
10087   // CHECK: is the format string a wide literal?
10088   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
10089     CheckFormatHandler::EmitFormatDiagnostic(
10090         S, inFunctionCall, Args[format_idx],
10091         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
10092         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10093     return;
10094   }
10095 
10096   // Str - The format string.  NOTE: this is NOT null-terminated!
10097   StringRef StrRef = FExpr->getString();
10098   const char *Str = StrRef.data();
10099   // Account for cases where the string literal is truncated in a declaration.
10100   const ConstantArrayType *T =
10101     S.Context.getAsConstantArrayType(FExpr->getType());
10102   assert(T && "String literal not of constant array type!");
10103   size_t TypeSize = T->getSize().getZExtValue();
10104   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10105   const unsigned numDataArgs = Args.size() - firstDataArg;
10106 
10107   if (IgnoreStringsWithoutSpecifiers &&
10108       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
10109           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10110     return;
10111 
10112   // Emit a warning if the string literal is truncated and does not contain an
10113   // embedded null character.
10114   if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
10115     CheckFormatHandler::EmitFormatDiagnostic(
10116         S, inFunctionCall, Args[format_idx],
10117         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
10118         FExpr->getBeginLoc(),
10119         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
10120     return;
10121   }
10122 
10123   // CHECK: empty format string?
10124   if (StrLen == 0 && numDataArgs > 0) {
10125     CheckFormatHandler::EmitFormatDiagnostic(
10126         S, inFunctionCall, Args[format_idx],
10127         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
10128         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10129     return;
10130   }
10131 
10132   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
10133       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
10134       Type == Sema::FST_OSTrace) {
10135     CheckPrintfHandler H(
10136         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
10137         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
10138         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
10139         CheckedVarArgs, UncoveredArg);
10140 
10141     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
10142                                                   S.getLangOpts(),
10143                                                   S.Context.getTargetInfo(),
10144                                             Type == Sema::FST_FreeBSDKPrintf))
10145       H.DoneProcessing();
10146   } else if (Type == Sema::FST_Scanf) {
10147     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10148                         numDataArgs, Str, HasVAListArg, Args, format_idx,
10149                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
10150 
10151     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
10152                                                  S.getLangOpts(),
10153                                                  S.Context.getTargetInfo()))
10154       H.DoneProcessing();
10155   } // TODO: handle other formats
10156 }
10157 
10158 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
10159   // Str - The format string.  NOTE: this is NOT null-terminated!
10160   StringRef StrRef = FExpr->getString();
10161   const char *Str = StrRef.data();
10162   // Account for cases where the string literal is truncated in a declaration.
10163   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
10164   assert(T && "String literal not of constant array type!");
10165   size_t TypeSize = T->getSize().getZExtValue();
10166   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10167   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
10168                                                          getLangOpts(),
10169                                                          Context.getTargetInfo());
10170 }
10171 
10172 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10173 
10174 // Returns the related absolute value function that is larger, of 0 if one
10175 // does not exist.
10176 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10177   switch (AbsFunction) {
10178   default:
10179     return 0;
10180 
10181   case Builtin::BI__builtin_abs:
10182     return Builtin::BI__builtin_labs;
10183   case Builtin::BI__builtin_labs:
10184     return Builtin::BI__builtin_llabs;
10185   case Builtin::BI__builtin_llabs:
10186     return 0;
10187 
10188   case Builtin::BI__builtin_fabsf:
10189     return Builtin::BI__builtin_fabs;
10190   case Builtin::BI__builtin_fabs:
10191     return Builtin::BI__builtin_fabsl;
10192   case Builtin::BI__builtin_fabsl:
10193     return 0;
10194 
10195   case Builtin::BI__builtin_cabsf:
10196     return Builtin::BI__builtin_cabs;
10197   case Builtin::BI__builtin_cabs:
10198     return Builtin::BI__builtin_cabsl;
10199   case Builtin::BI__builtin_cabsl:
10200     return 0;
10201 
10202   case Builtin::BIabs:
10203     return Builtin::BIlabs;
10204   case Builtin::BIlabs:
10205     return Builtin::BIllabs;
10206   case Builtin::BIllabs:
10207     return 0;
10208 
10209   case Builtin::BIfabsf:
10210     return Builtin::BIfabs;
10211   case Builtin::BIfabs:
10212     return Builtin::BIfabsl;
10213   case Builtin::BIfabsl:
10214     return 0;
10215 
10216   case Builtin::BIcabsf:
10217    return Builtin::BIcabs;
10218   case Builtin::BIcabs:
10219     return Builtin::BIcabsl;
10220   case Builtin::BIcabsl:
10221     return 0;
10222   }
10223 }
10224 
10225 // Returns the argument type of the absolute value function.
10226 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
10227                                              unsigned AbsType) {
10228   if (AbsType == 0)
10229     return QualType();
10230 
10231   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
10232   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10233   if (Error != ASTContext::GE_None)
10234     return QualType();
10235 
10236   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
10237   if (!FT)
10238     return QualType();
10239 
10240   if (FT->getNumParams() != 1)
10241     return QualType();
10242 
10243   return FT->getParamType(0);
10244 }
10245 
10246 // Returns the best absolute value function, or zero, based on type and
10247 // current absolute value function.
10248 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10249                                    unsigned AbsFunctionKind) {
10250   unsigned BestKind = 0;
10251   uint64_t ArgSize = Context.getTypeSize(ArgType);
10252   for (unsigned Kind = AbsFunctionKind; Kind != 0;
10253        Kind = getLargerAbsoluteValueFunction(Kind)) {
10254     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10255     if (Context.getTypeSize(ParamType) >= ArgSize) {
10256       if (BestKind == 0)
10257         BestKind = Kind;
10258       else if (Context.hasSameType(ParamType, ArgType)) {
10259         BestKind = Kind;
10260         break;
10261       }
10262     }
10263   }
10264   return BestKind;
10265 }
10266 
10267 enum AbsoluteValueKind {
10268   AVK_Integer,
10269   AVK_Floating,
10270   AVK_Complex
10271 };
10272 
10273 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
10274   if (T->isIntegralOrEnumerationType())
10275     return AVK_Integer;
10276   if (T->isRealFloatingType())
10277     return AVK_Floating;
10278   if (T->isAnyComplexType())
10279     return AVK_Complex;
10280 
10281   llvm_unreachable("Type not integer, floating, or complex");
10282 }
10283 
10284 // Changes the absolute value function to a different type.  Preserves whether
10285 // the function is a builtin.
10286 static unsigned changeAbsFunction(unsigned AbsKind,
10287                                   AbsoluteValueKind ValueKind) {
10288   switch (ValueKind) {
10289   case AVK_Integer:
10290     switch (AbsKind) {
10291     default:
10292       return 0;
10293     case Builtin::BI__builtin_fabsf:
10294     case Builtin::BI__builtin_fabs:
10295     case Builtin::BI__builtin_fabsl:
10296     case Builtin::BI__builtin_cabsf:
10297     case Builtin::BI__builtin_cabs:
10298     case Builtin::BI__builtin_cabsl:
10299       return Builtin::BI__builtin_abs;
10300     case Builtin::BIfabsf:
10301     case Builtin::BIfabs:
10302     case Builtin::BIfabsl:
10303     case Builtin::BIcabsf:
10304     case Builtin::BIcabs:
10305     case Builtin::BIcabsl:
10306       return Builtin::BIabs;
10307     }
10308   case AVK_Floating:
10309     switch (AbsKind) {
10310     default:
10311       return 0;
10312     case Builtin::BI__builtin_abs:
10313     case Builtin::BI__builtin_labs:
10314     case Builtin::BI__builtin_llabs:
10315     case Builtin::BI__builtin_cabsf:
10316     case Builtin::BI__builtin_cabs:
10317     case Builtin::BI__builtin_cabsl:
10318       return Builtin::BI__builtin_fabsf;
10319     case Builtin::BIabs:
10320     case Builtin::BIlabs:
10321     case Builtin::BIllabs:
10322     case Builtin::BIcabsf:
10323     case Builtin::BIcabs:
10324     case Builtin::BIcabsl:
10325       return Builtin::BIfabsf;
10326     }
10327   case AVK_Complex:
10328     switch (AbsKind) {
10329     default:
10330       return 0;
10331     case Builtin::BI__builtin_abs:
10332     case Builtin::BI__builtin_labs:
10333     case Builtin::BI__builtin_llabs:
10334     case Builtin::BI__builtin_fabsf:
10335     case Builtin::BI__builtin_fabs:
10336     case Builtin::BI__builtin_fabsl:
10337       return Builtin::BI__builtin_cabsf;
10338     case Builtin::BIabs:
10339     case Builtin::BIlabs:
10340     case Builtin::BIllabs:
10341     case Builtin::BIfabsf:
10342     case Builtin::BIfabs:
10343     case Builtin::BIfabsl:
10344       return Builtin::BIcabsf;
10345     }
10346   }
10347   llvm_unreachable("Unable to convert function");
10348 }
10349 
10350 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10351   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10352   if (!FnInfo)
10353     return 0;
10354 
10355   switch (FDecl->getBuiltinID()) {
10356   default:
10357     return 0;
10358   case Builtin::BI__builtin_abs:
10359   case Builtin::BI__builtin_fabs:
10360   case Builtin::BI__builtin_fabsf:
10361   case Builtin::BI__builtin_fabsl:
10362   case Builtin::BI__builtin_labs:
10363   case Builtin::BI__builtin_llabs:
10364   case Builtin::BI__builtin_cabs:
10365   case Builtin::BI__builtin_cabsf:
10366   case Builtin::BI__builtin_cabsl:
10367   case Builtin::BIabs:
10368   case Builtin::BIlabs:
10369   case Builtin::BIllabs:
10370   case Builtin::BIfabs:
10371   case Builtin::BIfabsf:
10372   case Builtin::BIfabsl:
10373   case Builtin::BIcabs:
10374   case Builtin::BIcabsf:
10375   case Builtin::BIcabsl:
10376     return FDecl->getBuiltinID();
10377   }
10378   llvm_unreachable("Unknown Builtin type");
10379 }
10380 
10381 // If the replacement is valid, emit a note with replacement function.
10382 // Additionally, suggest including the proper header if not already included.
10383 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10384                             unsigned AbsKind, QualType ArgType) {
10385   bool EmitHeaderHint = true;
10386   const char *HeaderName = nullptr;
10387   const char *FunctionName = nullptr;
10388   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10389     FunctionName = "std::abs";
10390     if (ArgType->isIntegralOrEnumerationType()) {
10391       HeaderName = "cstdlib";
10392     } else if (ArgType->isRealFloatingType()) {
10393       HeaderName = "cmath";
10394     } else {
10395       llvm_unreachable("Invalid Type");
10396     }
10397 
10398     // Lookup all std::abs
10399     if (NamespaceDecl *Std = S.getStdNamespace()) {
10400       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10401       R.suppressDiagnostics();
10402       S.LookupQualifiedName(R, Std);
10403 
10404       for (const auto *I : R) {
10405         const FunctionDecl *FDecl = nullptr;
10406         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10407           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10408         } else {
10409           FDecl = dyn_cast<FunctionDecl>(I);
10410         }
10411         if (!FDecl)
10412           continue;
10413 
10414         // Found std::abs(), check that they are the right ones.
10415         if (FDecl->getNumParams() != 1)
10416           continue;
10417 
10418         // Check that the parameter type can handle the argument.
10419         QualType ParamType = FDecl->getParamDecl(0)->getType();
10420         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10421             S.Context.getTypeSize(ArgType) <=
10422                 S.Context.getTypeSize(ParamType)) {
10423           // Found a function, don't need the header hint.
10424           EmitHeaderHint = false;
10425           break;
10426         }
10427       }
10428     }
10429   } else {
10430     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10431     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10432 
10433     if (HeaderName) {
10434       DeclarationName DN(&S.Context.Idents.get(FunctionName));
10435       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10436       R.suppressDiagnostics();
10437       S.LookupName(R, S.getCurScope());
10438 
10439       if (R.isSingleResult()) {
10440         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10441         if (FD && FD->getBuiltinID() == AbsKind) {
10442           EmitHeaderHint = false;
10443         } else {
10444           return;
10445         }
10446       } else if (!R.empty()) {
10447         return;
10448       }
10449     }
10450   }
10451 
10452   S.Diag(Loc, diag::note_replace_abs_function)
10453       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10454 
10455   if (!HeaderName)
10456     return;
10457 
10458   if (!EmitHeaderHint)
10459     return;
10460 
10461   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10462                                                     << FunctionName;
10463 }
10464 
10465 template <std::size_t StrLen>
10466 static bool IsStdFunction(const FunctionDecl *FDecl,
10467                           const char (&Str)[StrLen]) {
10468   if (!FDecl)
10469     return false;
10470   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10471     return false;
10472   if (!FDecl->isInStdNamespace())
10473     return false;
10474 
10475   return true;
10476 }
10477 
10478 // Warn when using the wrong abs() function.
10479 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10480                                       const FunctionDecl *FDecl) {
10481   if (Call->getNumArgs() != 1)
10482     return;
10483 
10484   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10485   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10486   if (AbsKind == 0 && !IsStdAbs)
10487     return;
10488 
10489   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10490   QualType ParamType = Call->getArg(0)->getType();
10491 
10492   // Unsigned types cannot be negative.  Suggest removing the absolute value
10493   // function call.
10494   if (ArgType->isUnsignedIntegerType()) {
10495     const char *FunctionName =
10496         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10497     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10498     Diag(Call->getExprLoc(), diag::note_remove_abs)
10499         << FunctionName
10500         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10501     return;
10502   }
10503 
10504   // Taking the absolute value of a pointer is very suspicious, they probably
10505   // wanted to index into an array, dereference a pointer, call a function, etc.
10506   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10507     unsigned DiagType = 0;
10508     if (ArgType->isFunctionType())
10509       DiagType = 1;
10510     else if (ArgType->isArrayType())
10511       DiagType = 2;
10512 
10513     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10514     return;
10515   }
10516 
10517   // std::abs has overloads which prevent most of the absolute value problems
10518   // from occurring.
10519   if (IsStdAbs)
10520     return;
10521 
10522   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10523   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10524 
10525   // The argument and parameter are the same kind.  Check if they are the right
10526   // size.
10527   if (ArgValueKind == ParamValueKind) {
10528     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10529       return;
10530 
10531     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10532     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10533         << FDecl << ArgType << ParamType;
10534 
10535     if (NewAbsKind == 0)
10536       return;
10537 
10538     emitReplacement(*this, Call->getExprLoc(),
10539                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10540     return;
10541   }
10542 
10543   // ArgValueKind != ParamValueKind
10544   // The wrong type of absolute value function was used.  Attempt to find the
10545   // proper one.
10546   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10547   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10548   if (NewAbsKind == 0)
10549     return;
10550 
10551   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10552       << FDecl << ParamValueKind << ArgValueKind;
10553 
10554   emitReplacement(*this, Call->getExprLoc(),
10555                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10556 }
10557 
10558 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10559 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10560                                 const FunctionDecl *FDecl) {
10561   if (!Call || !FDecl) return;
10562 
10563   // Ignore template specializations and macros.
10564   if (inTemplateInstantiation()) return;
10565   if (Call->getExprLoc().isMacroID()) return;
10566 
10567   // Only care about the one template argument, two function parameter std::max
10568   if (Call->getNumArgs() != 2) return;
10569   if (!IsStdFunction(FDecl, "max")) return;
10570   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10571   if (!ArgList) return;
10572   if (ArgList->size() != 1) return;
10573 
10574   // Check that template type argument is unsigned integer.
10575   const auto& TA = ArgList->get(0);
10576   if (TA.getKind() != TemplateArgument::Type) return;
10577   QualType ArgType = TA.getAsType();
10578   if (!ArgType->isUnsignedIntegerType()) return;
10579 
10580   // See if either argument is a literal zero.
10581   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10582     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10583     if (!MTE) return false;
10584     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10585     if (!Num) return false;
10586     if (Num->getValue() != 0) return false;
10587     return true;
10588   };
10589 
10590   const Expr *FirstArg = Call->getArg(0);
10591   const Expr *SecondArg = Call->getArg(1);
10592   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10593   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10594 
10595   // Only warn when exactly one argument is zero.
10596   if (IsFirstArgZero == IsSecondArgZero) return;
10597 
10598   SourceRange FirstRange = FirstArg->getSourceRange();
10599   SourceRange SecondRange = SecondArg->getSourceRange();
10600 
10601   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10602 
10603   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10604       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10605 
10606   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10607   SourceRange RemovalRange;
10608   if (IsFirstArgZero) {
10609     RemovalRange = SourceRange(FirstRange.getBegin(),
10610                                SecondRange.getBegin().getLocWithOffset(-1));
10611   } else {
10612     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10613                                SecondRange.getEnd());
10614   }
10615 
10616   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10617         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10618         << FixItHint::CreateRemoval(RemovalRange);
10619 }
10620 
10621 //===--- CHECK: Standard memory functions ---------------------------------===//
10622 
10623 /// Takes the expression passed to the size_t parameter of functions
10624 /// such as memcmp, strncat, etc and warns if it's a comparison.
10625 ///
10626 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10627 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10628                                            IdentifierInfo *FnName,
10629                                            SourceLocation FnLoc,
10630                                            SourceLocation RParenLoc) {
10631   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10632   if (!Size)
10633     return false;
10634 
10635   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10636   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10637     return false;
10638 
10639   SourceRange SizeRange = Size->getSourceRange();
10640   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10641       << SizeRange << FnName;
10642   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10643       << FnName
10644       << FixItHint::CreateInsertion(
10645              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10646       << FixItHint::CreateRemoval(RParenLoc);
10647   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10648       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10649       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10650                                     ")");
10651 
10652   return true;
10653 }
10654 
10655 /// Determine whether the given type is or contains a dynamic class type
10656 /// (e.g., whether it has a vtable).
10657 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10658                                                      bool &IsContained) {
10659   // Look through array types while ignoring qualifiers.
10660   const Type *Ty = T->getBaseElementTypeUnsafe();
10661   IsContained = false;
10662 
10663   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10664   RD = RD ? RD->getDefinition() : nullptr;
10665   if (!RD || RD->isInvalidDecl())
10666     return nullptr;
10667 
10668   if (RD->isDynamicClass())
10669     return RD;
10670 
10671   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10672   // It's impossible for a class to transitively contain itself by value, so
10673   // infinite recursion is impossible.
10674   for (auto *FD : RD->fields()) {
10675     bool SubContained;
10676     if (const CXXRecordDecl *ContainedRD =
10677             getContainedDynamicClass(FD->getType(), SubContained)) {
10678       IsContained = true;
10679       return ContainedRD;
10680     }
10681   }
10682 
10683   return nullptr;
10684 }
10685 
10686 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10687   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10688     if (Unary->getKind() == UETT_SizeOf)
10689       return Unary;
10690   return nullptr;
10691 }
10692 
10693 /// If E is a sizeof expression, returns its argument expression,
10694 /// otherwise returns NULL.
10695 static const Expr *getSizeOfExprArg(const Expr *E) {
10696   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10697     if (!SizeOf->isArgumentType())
10698       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10699   return nullptr;
10700 }
10701 
10702 /// If E is a sizeof expression, returns its argument type.
10703 static QualType getSizeOfArgType(const Expr *E) {
10704   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10705     return SizeOf->getTypeOfArgument();
10706   return QualType();
10707 }
10708 
10709 namespace {
10710 
10711 struct SearchNonTrivialToInitializeField
10712     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10713   using Super =
10714       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10715 
10716   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10717 
10718   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10719                      SourceLocation SL) {
10720     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10721       asDerived().visitArray(PDIK, AT, SL);
10722       return;
10723     }
10724 
10725     Super::visitWithKind(PDIK, FT, SL);
10726   }
10727 
10728   void visitARCStrong(QualType FT, SourceLocation SL) {
10729     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10730   }
10731   void visitARCWeak(QualType FT, SourceLocation SL) {
10732     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10733   }
10734   void visitStruct(QualType FT, SourceLocation SL) {
10735     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10736       visit(FD->getType(), FD->getLocation());
10737   }
10738   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10739                   const ArrayType *AT, SourceLocation SL) {
10740     visit(getContext().getBaseElementType(AT), SL);
10741   }
10742   void visitTrivial(QualType FT, SourceLocation SL) {}
10743 
10744   static void diag(QualType RT, const Expr *E, Sema &S) {
10745     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10746   }
10747 
10748   ASTContext &getContext() { return S.getASTContext(); }
10749 
10750   const Expr *E;
10751   Sema &S;
10752 };
10753 
10754 struct SearchNonTrivialToCopyField
10755     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10756   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10757 
10758   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10759 
10760   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10761                      SourceLocation SL) {
10762     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10763       asDerived().visitArray(PCK, AT, SL);
10764       return;
10765     }
10766 
10767     Super::visitWithKind(PCK, FT, SL);
10768   }
10769 
10770   void visitARCStrong(QualType FT, SourceLocation SL) {
10771     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10772   }
10773   void visitARCWeak(QualType FT, SourceLocation SL) {
10774     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10775   }
10776   void visitStruct(QualType FT, SourceLocation SL) {
10777     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10778       visit(FD->getType(), FD->getLocation());
10779   }
10780   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10781                   SourceLocation SL) {
10782     visit(getContext().getBaseElementType(AT), SL);
10783   }
10784   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10785                 SourceLocation SL) {}
10786   void visitTrivial(QualType FT, SourceLocation SL) {}
10787   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10788 
10789   static void diag(QualType RT, const Expr *E, Sema &S) {
10790     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10791   }
10792 
10793   ASTContext &getContext() { return S.getASTContext(); }
10794 
10795   const Expr *E;
10796   Sema &S;
10797 };
10798 
10799 }
10800 
10801 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10802 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10803   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10804 
10805   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10806     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10807       return false;
10808 
10809     return doesExprLikelyComputeSize(BO->getLHS()) ||
10810            doesExprLikelyComputeSize(BO->getRHS());
10811   }
10812 
10813   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10814 }
10815 
10816 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10817 ///
10818 /// \code
10819 ///   #define MACRO 0
10820 ///   foo(MACRO);
10821 ///   foo(0);
10822 /// \endcode
10823 ///
10824 /// This should return true for the first call to foo, but not for the second
10825 /// (regardless of whether foo is a macro or function).
10826 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10827                                         SourceLocation CallLoc,
10828                                         SourceLocation ArgLoc) {
10829   if (!CallLoc.isMacroID())
10830     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10831 
10832   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10833          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10834 }
10835 
10836 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10837 /// last two arguments transposed.
10838 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10839   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10840     return;
10841 
10842   const Expr *SizeArg =
10843     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10844 
10845   auto isLiteralZero = [](const Expr *E) {
10846     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10847   };
10848 
10849   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10850   SourceLocation CallLoc = Call->getRParenLoc();
10851   SourceManager &SM = S.getSourceManager();
10852   if (isLiteralZero(SizeArg) &&
10853       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10854 
10855     SourceLocation DiagLoc = SizeArg->getExprLoc();
10856 
10857     // Some platforms #define bzero to __builtin_memset. See if this is the
10858     // case, and if so, emit a better diagnostic.
10859     if (BId == Builtin::BIbzero ||
10860         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10861                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10862       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10863       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10864     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10865       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10866       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10867     }
10868     return;
10869   }
10870 
10871   // If the second argument to a memset is a sizeof expression and the third
10872   // isn't, this is also likely an error. This should catch
10873   // 'memset(buf, sizeof(buf), 0xff)'.
10874   if (BId == Builtin::BImemset &&
10875       doesExprLikelyComputeSize(Call->getArg(1)) &&
10876       !doesExprLikelyComputeSize(Call->getArg(2))) {
10877     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10878     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10879     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10880     return;
10881   }
10882 }
10883 
10884 /// Check for dangerous or invalid arguments to memset().
10885 ///
10886 /// This issues warnings on known problematic, dangerous or unspecified
10887 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10888 /// function calls.
10889 ///
10890 /// \param Call The call expression to diagnose.
10891 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10892                                    unsigned BId,
10893                                    IdentifierInfo *FnName) {
10894   assert(BId != 0);
10895 
10896   // It is possible to have a non-standard definition of memset.  Validate
10897   // we have enough arguments, and if not, abort further checking.
10898   unsigned ExpectedNumArgs =
10899       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10900   if (Call->getNumArgs() < ExpectedNumArgs)
10901     return;
10902 
10903   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10904                       BId == Builtin::BIstrndup ? 1 : 2);
10905   unsigned LenArg =
10906       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10907   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10908 
10909   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10910                                      Call->getBeginLoc(), Call->getRParenLoc()))
10911     return;
10912 
10913   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10914   CheckMemaccessSize(*this, BId, Call);
10915 
10916   // We have special checking when the length is a sizeof expression.
10917   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10918   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10919   llvm::FoldingSetNodeID SizeOfArgID;
10920 
10921   // Although widely used, 'bzero' is not a standard function. Be more strict
10922   // with the argument types before allowing diagnostics and only allow the
10923   // form bzero(ptr, sizeof(...)).
10924   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10925   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10926     return;
10927 
10928   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10929     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10930     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10931 
10932     QualType DestTy = Dest->getType();
10933     QualType PointeeTy;
10934     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10935       PointeeTy = DestPtrTy->getPointeeType();
10936 
10937       // Never warn about void type pointers. This can be used to suppress
10938       // false positives.
10939       if (PointeeTy->isVoidType())
10940         continue;
10941 
10942       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10943       // actually comparing the expressions for equality. Because computing the
10944       // expression IDs can be expensive, we only do this if the diagnostic is
10945       // enabled.
10946       if (SizeOfArg &&
10947           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10948                            SizeOfArg->getExprLoc())) {
10949         // We only compute IDs for expressions if the warning is enabled, and
10950         // cache the sizeof arg's ID.
10951         if (SizeOfArgID == llvm::FoldingSetNodeID())
10952           SizeOfArg->Profile(SizeOfArgID, Context, true);
10953         llvm::FoldingSetNodeID DestID;
10954         Dest->Profile(DestID, Context, true);
10955         if (DestID == SizeOfArgID) {
10956           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10957           //       over sizeof(src) as well.
10958           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10959           StringRef ReadableName = FnName->getName();
10960 
10961           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10962             if (UnaryOp->getOpcode() == UO_AddrOf)
10963               ActionIdx = 1; // If its an address-of operator, just remove it.
10964           if (!PointeeTy->isIncompleteType() &&
10965               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10966             ActionIdx = 2; // If the pointee's size is sizeof(char),
10967                            // suggest an explicit length.
10968 
10969           // If the function is defined as a builtin macro, do not show macro
10970           // expansion.
10971           SourceLocation SL = SizeOfArg->getExprLoc();
10972           SourceRange DSR = Dest->getSourceRange();
10973           SourceRange SSR = SizeOfArg->getSourceRange();
10974           SourceManager &SM = getSourceManager();
10975 
10976           if (SM.isMacroArgExpansion(SL)) {
10977             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10978             SL = SM.getSpellingLoc(SL);
10979             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10980                              SM.getSpellingLoc(DSR.getEnd()));
10981             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10982                              SM.getSpellingLoc(SSR.getEnd()));
10983           }
10984 
10985           DiagRuntimeBehavior(SL, SizeOfArg,
10986                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10987                                 << ReadableName
10988                                 << PointeeTy
10989                                 << DestTy
10990                                 << DSR
10991                                 << SSR);
10992           DiagRuntimeBehavior(SL, SizeOfArg,
10993                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10994                                 << ActionIdx
10995                                 << SSR);
10996 
10997           break;
10998         }
10999       }
11000 
11001       // Also check for cases where the sizeof argument is the exact same
11002       // type as the memory argument, and where it points to a user-defined
11003       // record type.
11004       if (SizeOfArgTy != QualType()) {
11005         if (PointeeTy->isRecordType() &&
11006             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
11007           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
11008                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
11009                                 << FnName << SizeOfArgTy << ArgIdx
11010                                 << PointeeTy << Dest->getSourceRange()
11011                                 << LenExpr->getSourceRange());
11012           break;
11013         }
11014       }
11015     } else if (DestTy->isArrayType()) {
11016       PointeeTy = DestTy;
11017     }
11018 
11019     if (PointeeTy == QualType())
11020       continue;
11021 
11022     // Always complain about dynamic classes.
11023     bool IsContained;
11024     if (const CXXRecordDecl *ContainedRD =
11025             getContainedDynamicClass(PointeeTy, IsContained)) {
11026 
11027       unsigned OperationType = 0;
11028       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
11029       // "overwritten" if we're warning about the destination for any call
11030       // but memcmp; otherwise a verb appropriate to the call.
11031       if (ArgIdx != 0 || IsCmp) {
11032         if (BId == Builtin::BImemcpy)
11033           OperationType = 1;
11034         else if(BId == Builtin::BImemmove)
11035           OperationType = 2;
11036         else if (IsCmp)
11037           OperationType = 3;
11038       }
11039 
11040       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11041                           PDiag(diag::warn_dyn_class_memaccess)
11042                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
11043                               << IsContained << ContainedRD << OperationType
11044                               << Call->getCallee()->getSourceRange());
11045     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
11046              BId != Builtin::BImemset)
11047       DiagRuntimeBehavior(
11048         Dest->getExprLoc(), Dest,
11049         PDiag(diag::warn_arc_object_memaccess)
11050           << ArgIdx << FnName << PointeeTy
11051           << Call->getCallee()->getSourceRange());
11052     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
11053       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11054           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
11055         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11056                             PDiag(diag::warn_cstruct_memaccess)
11057                                 << ArgIdx << FnName << PointeeTy << 0);
11058         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
11059       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11060                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
11061         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11062                             PDiag(diag::warn_cstruct_memaccess)
11063                                 << ArgIdx << FnName << PointeeTy << 1);
11064         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
11065       } else {
11066         continue;
11067       }
11068     } else
11069       continue;
11070 
11071     DiagRuntimeBehavior(
11072       Dest->getExprLoc(), Dest,
11073       PDiag(diag::note_bad_memaccess_silence)
11074         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
11075     break;
11076   }
11077 }
11078 
11079 // A little helper routine: ignore addition and subtraction of integer literals.
11080 // This intentionally does not ignore all integer constant expressions because
11081 // we don't want to remove sizeof().
11082 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11083   Ex = Ex->IgnoreParenCasts();
11084 
11085   while (true) {
11086     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
11087     if (!BO || !BO->isAdditiveOp())
11088       break;
11089 
11090     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11091     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11092 
11093     if (isa<IntegerLiteral>(RHS))
11094       Ex = LHS;
11095     else if (isa<IntegerLiteral>(LHS))
11096       Ex = RHS;
11097     else
11098       break;
11099   }
11100 
11101   return Ex;
11102 }
11103 
11104 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
11105                                                       ASTContext &Context) {
11106   // Only handle constant-sized or VLAs, but not flexible members.
11107   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
11108     // Only issue the FIXIT for arrays of size > 1.
11109     if (CAT->getSize().getSExtValue() <= 1)
11110       return false;
11111   } else if (!Ty->isVariableArrayType()) {
11112     return false;
11113   }
11114   return true;
11115 }
11116 
11117 // Warn if the user has made the 'size' argument to strlcpy or strlcat
11118 // be the size of the source, instead of the destination.
11119 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11120                                     IdentifierInfo *FnName) {
11121 
11122   // Don't crash if the user has the wrong number of arguments
11123   unsigned NumArgs = Call->getNumArgs();
11124   if ((NumArgs != 3) && (NumArgs != 4))
11125     return;
11126 
11127   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
11128   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
11129   const Expr *CompareWithSrc = nullptr;
11130 
11131   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
11132                                      Call->getBeginLoc(), Call->getRParenLoc()))
11133     return;
11134 
11135   // Look for 'strlcpy(dst, x, sizeof(x))'
11136   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
11137     CompareWithSrc = Ex;
11138   else {
11139     // Look for 'strlcpy(dst, x, strlen(x))'
11140     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11141       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11142           SizeCall->getNumArgs() == 1)
11143         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
11144     }
11145   }
11146 
11147   if (!CompareWithSrc)
11148     return;
11149 
11150   // Determine if the argument to sizeof/strlen is equal to the source
11151   // argument.  In principle there's all kinds of things you could do
11152   // here, for instance creating an == expression and evaluating it with
11153   // EvaluateAsBooleanCondition, but this uses a more direct technique:
11154   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11155   if (!SrcArgDRE)
11156     return;
11157 
11158   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11159   if (!CompareWithSrcDRE ||
11160       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11161     return;
11162 
11163   const Expr *OriginalSizeArg = Call->getArg(2);
11164   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11165       << OriginalSizeArg->getSourceRange() << FnName;
11166 
11167   // Output a FIXIT hint if the destination is an array (rather than a
11168   // pointer to an array).  This could be enhanced to handle some
11169   // pointers if we know the actual size, like if DstArg is 'array+2'
11170   // we could say 'sizeof(array)-2'.
11171   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
11172   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
11173     return;
11174 
11175   SmallString<128> sizeString;
11176   llvm::raw_svector_ostream OS(sizeString);
11177   OS << "sizeof(";
11178   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11179   OS << ")";
11180 
11181   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
11182       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
11183                                       OS.str());
11184 }
11185 
11186 /// Check if two expressions refer to the same declaration.
11187 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11188   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11189     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11190       return D1->getDecl() == D2->getDecl();
11191   return false;
11192 }
11193 
11194 static const Expr *getStrlenExprArg(const Expr *E) {
11195   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11196     const FunctionDecl *FD = CE->getDirectCallee();
11197     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11198       return nullptr;
11199     return CE->getArg(0)->IgnoreParenCasts();
11200   }
11201   return nullptr;
11202 }
11203 
11204 // Warn on anti-patterns as the 'size' argument to strncat.
11205 // The correct size argument should look like following:
11206 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
11207 void Sema::CheckStrncatArguments(const CallExpr *CE,
11208                                  IdentifierInfo *FnName) {
11209   // Don't crash if the user has the wrong number of arguments.
11210   if (CE->getNumArgs() < 3)
11211     return;
11212   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11213   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11214   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11215 
11216   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11217                                      CE->getRParenLoc()))
11218     return;
11219 
11220   // Identify common expressions, which are wrongly used as the size argument
11221   // to strncat and may lead to buffer overflows.
11222   unsigned PatternType = 0;
11223   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11224     // - sizeof(dst)
11225     if (referToTheSameDecl(SizeOfArg, DstArg))
11226       PatternType = 1;
11227     // - sizeof(src)
11228     else if (referToTheSameDecl(SizeOfArg, SrcArg))
11229       PatternType = 2;
11230   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11231     if (BE->getOpcode() == BO_Sub) {
11232       const Expr *L = BE->getLHS()->IgnoreParenCasts();
11233       const Expr *R = BE->getRHS()->IgnoreParenCasts();
11234       // - sizeof(dst) - strlen(dst)
11235       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11236           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
11237         PatternType = 1;
11238       // - sizeof(src) - (anything)
11239       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11240         PatternType = 2;
11241     }
11242   }
11243 
11244   if (PatternType == 0)
11245     return;
11246 
11247   // Generate the diagnostic.
11248   SourceLocation SL = LenArg->getBeginLoc();
11249   SourceRange SR = LenArg->getSourceRange();
11250   SourceManager &SM = getSourceManager();
11251 
11252   // If the function is defined as a builtin macro, do not show macro expansion.
11253   if (SM.isMacroArgExpansion(SL)) {
11254     SL = SM.getSpellingLoc(SL);
11255     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11256                      SM.getSpellingLoc(SR.getEnd()));
11257   }
11258 
11259   // Check if the destination is an array (rather than a pointer to an array).
11260   QualType DstTy = DstArg->getType();
11261   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11262                                                                     Context);
11263   if (!isKnownSizeArray) {
11264     if (PatternType == 1)
11265       Diag(SL, diag::warn_strncat_wrong_size) << SR;
11266     else
11267       Diag(SL, diag::warn_strncat_src_size) << SR;
11268     return;
11269   }
11270 
11271   if (PatternType == 1)
11272     Diag(SL, diag::warn_strncat_large_size) << SR;
11273   else
11274     Diag(SL, diag::warn_strncat_src_size) << SR;
11275 
11276   SmallString<128> sizeString;
11277   llvm::raw_svector_ostream OS(sizeString);
11278   OS << "sizeof(";
11279   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11280   OS << ") - ";
11281   OS << "strlen(";
11282   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11283   OS << ") - 1";
11284 
11285   Diag(SL, diag::note_strncat_wrong_size)
11286     << FixItHint::CreateReplacement(SR, OS.str());
11287 }
11288 
11289 namespace {
11290 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11291                                 const UnaryOperator *UnaryExpr, const Decl *D) {
11292   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
11293     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11294         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11295     return;
11296   }
11297 }
11298 
11299 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11300                                  const UnaryOperator *UnaryExpr) {
11301   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11302     const Decl *D = Lvalue->getDecl();
11303     if (isa<DeclaratorDecl>(D))
11304       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
11305         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11306   }
11307 
11308   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11309     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11310                                       Lvalue->getMemberDecl());
11311 }
11312 
11313 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11314                             const UnaryOperator *UnaryExpr) {
11315   const auto *Lambda = dyn_cast<LambdaExpr>(
11316       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11317   if (!Lambda)
11318     return;
11319 
11320   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11321       << CalleeName << 2 /*object: lambda expression*/;
11322 }
11323 
11324 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11325                                   const DeclRefExpr *Lvalue) {
11326   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11327   if (Var == nullptr)
11328     return;
11329 
11330   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11331       << CalleeName << 0 /*object: */ << Var;
11332 }
11333 
11334 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11335                             const CastExpr *Cast) {
11336   SmallString<128> SizeString;
11337   llvm::raw_svector_ostream OS(SizeString);
11338 
11339   clang::CastKind Kind = Cast->getCastKind();
11340   if (Kind == clang::CK_BitCast &&
11341       !Cast->getSubExpr()->getType()->isFunctionPointerType())
11342     return;
11343   if (Kind == clang::CK_IntegralToPointer &&
11344       !isa<IntegerLiteral>(
11345           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11346     return;
11347 
11348   switch (Cast->getCastKind()) {
11349   case clang::CK_BitCast:
11350   case clang::CK_IntegralToPointer:
11351   case clang::CK_FunctionToPointerDecay:
11352     OS << '\'';
11353     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11354     OS << '\'';
11355     break;
11356   default:
11357     return;
11358   }
11359 
11360   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11361       << CalleeName << 0 /*object: */ << OS.str();
11362 }
11363 } // namespace
11364 
11365 /// Alerts the user that they are attempting to free a non-malloc'd object.
11366 void Sema::CheckFreeArguments(const CallExpr *E) {
11367   const std::string CalleeName =
11368       cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11369 
11370   { // Prefer something that doesn't involve a cast to make things simpler.
11371     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11372     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11373       switch (UnaryExpr->getOpcode()) {
11374       case UnaryOperator::Opcode::UO_AddrOf:
11375         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11376       case UnaryOperator::Opcode::UO_Plus:
11377         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11378       default:
11379         break;
11380       }
11381 
11382     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11383       if (Lvalue->getType()->isArrayType())
11384         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11385 
11386     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11387       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11388           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11389       return;
11390     }
11391 
11392     if (isa<BlockExpr>(Arg)) {
11393       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11394           << CalleeName << 1 /*object: block*/;
11395       return;
11396     }
11397   }
11398   // Maybe the cast was important, check after the other cases.
11399   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11400     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11401 }
11402 
11403 void
11404 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11405                          SourceLocation ReturnLoc,
11406                          bool isObjCMethod,
11407                          const AttrVec *Attrs,
11408                          const FunctionDecl *FD) {
11409   // Check if the return value is null but should not be.
11410   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11411        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
11412       CheckNonNullExpr(*this, RetValExp))
11413     Diag(ReturnLoc, diag::warn_null_ret)
11414       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11415 
11416   // C++11 [basic.stc.dynamic.allocation]p4:
11417   //   If an allocation function declared with a non-throwing
11418   //   exception-specification fails to allocate storage, it shall return
11419   //   a null pointer. Any other allocation function that fails to allocate
11420   //   storage shall indicate failure only by throwing an exception [...]
11421   if (FD) {
11422     OverloadedOperatorKind Op = FD->getOverloadedOperator();
11423     if (Op == OO_New || Op == OO_Array_New) {
11424       const FunctionProtoType *Proto
11425         = FD->getType()->castAs<FunctionProtoType>();
11426       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11427           CheckNonNullExpr(*this, RetValExp))
11428         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11429           << FD << getLangOpts().CPlusPlus11;
11430     }
11431   }
11432 
11433   // PPC MMA non-pointer types are not allowed as return type. Checking the type
11434   // here prevent the user from using a PPC MMA type as trailing return type.
11435   if (Context.getTargetInfo().getTriple().isPPC64())
11436     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11437 }
11438 
11439 /// Check for comparisons of floating-point values using == and !=. Issue a
11440 /// warning if the comparison is not likely to do what the programmer intended.
11441 void Sema::CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS,
11442                                 BinaryOperatorKind Opcode) {
11443   // Match and capture subexpressions such as "(float) X == 0.1".
11444   FloatingLiteral *FPLiteral;
11445   CastExpr *FPCast;
11446   auto getCastAndLiteral = [&FPLiteral, &FPCast](Expr *L, Expr *R) {
11447     FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
11448     FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
11449     return FPLiteral && FPCast;
11450   };
11451 
11452   if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11453     auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11454     auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11455     if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11456         TargetTy->isFloatingPoint()) {
11457       bool Lossy;
11458       llvm::APFloat TargetC = FPLiteral->getValue();
11459       TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
11460                       llvm::APFloat::rmNearestTiesToEven, &Lossy);
11461       if (Lossy) {
11462         // If the literal cannot be represented in the source type, then a
11463         // check for == is always false and check for != is always true.
11464         Diag(Loc, diag::warn_float_compare_literal)
11465             << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11466             << LHS->getSourceRange() << RHS->getSourceRange();
11467         return;
11468       }
11469     }
11470   }
11471 
11472   // Match a more general floating-point equality comparison (-Wfloat-equal).
11473   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
11474   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
11475 
11476   // Special case: check for x == x (which is OK).
11477   // Do not emit warnings for such cases.
11478   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11479     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11480       if (DRL->getDecl() == DRR->getDecl())
11481         return;
11482 
11483   // Special case: check for comparisons against literals that can be exactly
11484   //  represented by APFloat.  In such cases, do not emit a warning.  This
11485   //  is a heuristic: often comparison against such literals are used to
11486   //  detect if a value in a variable has not changed.  This clearly can
11487   //  lead to false negatives.
11488   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11489     if (FLL->isExact())
11490       return;
11491   } else
11492     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11493       if (FLR->isExact())
11494         return;
11495 
11496   // Check for comparisons with builtin types.
11497   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11498     if (CL->getBuiltinCallee())
11499       return;
11500 
11501   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11502     if (CR->getBuiltinCallee())
11503       return;
11504 
11505   // Emit the diagnostic.
11506   Diag(Loc, diag::warn_floatingpoint_eq)
11507     << LHS->getSourceRange() << RHS->getSourceRange();
11508 }
11509 
11510 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11511 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11512 
11513 namespace {
11514 
11515 /// Structure recording the 'active' range of an integer-valued
11516 /// expression.
11517 struct IntRange {
11518   /// The number of bits active in the int. Note that this includes exactly one
11519   /// sign bit if !NonNegative.
11520   unsigned Width;
11521 
11522   /// True if the int is known not to have negative values. If so, all leading
11523   /// bits before Width are known zero, otherwise they are known to be the
11524   /// same as the MSB within Width.
11525   bool NonNegative;
11526 
11527   IntRange(unsigned Width, bool NonNegative)
11528       : Width(Width), NonNegative(NonNegative) {}
11529 
11530   /// Number of bits excluding the sign bit.
11531   unsigned valueBits() const {
11532     return NonNegative ? Width : Width - 1;
11533   }
11534 
11535   /// Returns the range of the bool type.
11536   static IntRange forBoolType() {
11537     return IntRange(1, true);
11538   }
11539 
11540   /// Returns the range of an opaque value of the given integral type.
11541   static IntRange forValueOfType(ASTContext &C, QualType T) {
11542     return forValueOfCanonicalType(C,
11543                           T->getCanonicalTypeInternal().getTypePtr());
11544   }
11545 
11546   /// Returns the range of an opaque value of a canonical integral type.
11547   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11548     assert(T->isCanonicalUnqualified());
11549 
11550     if (const VectorType *VT = dyn_cast<VectorType>(T))
11551       T = VT->getElementType().getTypePtr();
11552     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11553       T = CT->getElementType().getTypePtr();
11554     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11555       T = AT->getValueType().getTypePtr();
11556 
11557     if (!C.getLangOpts().CPlusPlus) {
11558       // For enum types in C code, use the underlying datatype.
11559       if (const EnumType *ET = dyn_cast<EnumType>(T))
11560         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11561     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11562       // For enum types in C++, use the known bit width of the enumerators.
11563       EnumDecl *Enum = ET->getDecl();
11564       // In C++11, enums can have a fixed underlying type. Use this type to
11565       // compute the range.
11566       if (Enum->isFixed()) {
11567         return IntRange(C.getIntWidth(QualType(T, 0)),
11568                         !ET->isSignedIntegerOrEnumerationType());
11569       }
11570 
11571       unsigned NumPositive = Enum->getNumPositiveBits();
11572       unsigned NumNegative = Enum->getNumNegativeBits();
11573 
11574       if (NumNegative == 0)
11575         return IntRange(NumPositive, true/*NonNegative*/);
11576       else
11577         return IntRange(std::max(NumPositive + 1, NumNegative),
11578                         false/*NonNegative*/);
11579     }
11580 
11581     if (const auto *EIT = dyn_cast<BitIntType>(T))
11582       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11583 
11584     const BuiltinType *BT = cast<BuiltinType>(T);
11585     assert(BT->isInteger());
11586 
11587     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11588   }
11589 
11590   /// Returns the "target" range of a canonical integral type, i.e.
11591   /// the range of values expressible in the type.
11592   ///
11593   /// This matches forValueOfCanonicalType except that enums have the
11594   /// full range of their type, not the range of their enumerators.
11595   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11596     assert(T->isCanonicalUnqualified());
11597 
11598     if (const VectorType *VT = dyn_cast<VectorType>(T))
11599       T = VT->getElementType().getTypePtr();
11600     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11601       T = CT->getElementType().getTypePtr();
11602     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11603       T = AT->getValueType().getTypePtr();
11604     if (const EnumType *ET = dyn_cast<EnumType>(T))
11605       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11606 
11607     if (const auto *EIT = dyn_cast<BitIntType>(T))
11608       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11609 
11610     const BuiltinType *BT = cast<BuiltinType>(T);
11611     assert(BT->isInteger());
11612 
11613     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11614   }
11615 
11616   /// Returns the supremum of two ranges: i.e. their conservative merge.
11617   static IntRange join(IntRange L, IntRange R) {
11618     bool Unsigned = L.NonNegative && R.NonNegative;
11619     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11620                     L.NonNegative && R.NonNegative);
11621   }
11622 
11623   /// Return the range of a bitwise-AND of the two ranges.
11624   static IntRange bit_and(IntRange L, IntRange R) {
11625     unsigned Bits = std::max(L.Width, R.Width);
11626     bool NonNegative = false;
11627     if (L.NonNegative) {
11628       Bits = std::min(Bits, L.Width);
11629       NonNegative = true;
11630     }
11631     if (R.NonNegative) {
11632       Bits = std::min(Bits, R.Width);
11633       NonNegative = true;
11634     }
11635     return IntRange(Bits, NonNegative);
11636   }
11637 
11638   /// Return the range of a sum of the two ranges.
11639   static IntRange sum(IntRange L, IntRange R) {
11640     bool Unsigned = L.NonNegative && R.NonNegative;
11641     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11642                     Unsigned);
11643   }
11644 
11645   /// Return the range of a difference of the two ranges.
11646   static IntRange difference(IntRange L, IntRange R) {
11647     // We need a 1-bit-wider range if:
11648     //   1) LHS can be negative: least value can be reduced.
11649     //   2) RHS can be negative: greatest value can be increased.
11650     bool CanWiden = !L.NonNegative || !R.NonNegative;
11651     bool Unsigned = L.NonNegative && R.Width == 0;
11652     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11653                         !Unsigned,
11654                     Unsigned);
11655   }
11656 
11657   /// Return the range of a product of the two ranges.
11658   static IntRange product(IntRange L, IntRange R) {
11659     // If both LHS and RHS can be negative, we can form
11660     //   -2^L * -2^R = 2^(L + R)
11661     // which requires L + R + 1 value bits to represent.
11662     bool CanWiden = !L.NonNegative && !R.NonNegative;
11663     bool Unsigned = L.NonNegative && R.NonNegative;
11664     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11665                     Unsigned);
11666   }
11667 
11668   /// Return the range of a remainder operation between the two ranges.
11669   static IntRange rem(IntRange L, IntRange R) {
11670     // The result of a remainder can't be larger than the result of
11671     // either side. The sign of the result is the sign of the LHS.
11672     bool Unsigned = L.NonNegative;
11673     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11674                     Unsigned);
11675   }
11676 };
11677 
11678 } // namespace
11679 
11680 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11681                               unsigned MaxWidth) {
11682   if (value.isSigned() && value.isNegative())
11683     return IntRange(value.getMinSignedBits(), false);
11684 
11685   if (value.getBitWidth() > MaxWidth)
11686     value = value.trunc(MaxWidth);
11687 
11688   // isNonNegative() just checks the sign bit without considering
11689   // signedness.
11690   return IntRange(value.getActiveBits(), true);
11691 }
11692 
11693 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11694                               unsigned MaxWidth) {
11695   if (result.isInt())
11696     return GetValueRange(C, result.getInt(), MaxWidth);
11697 
11698   if (result.isVector()) {
11699     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11700     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11701       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11702       R = IntRange::join(R, El);
11703     }
11704     return R;
11705   }
11706 
11707   if (result.isComplexInt()) {
11708     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11709     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11710     return IntRange::join(R, I);
11711   }
11712 
11713   // This can happen with lossless casts to intptr_t of "based" lvalues.
11714   // Assume it might use arbitrary bits.
11715   // FIXME: The only reason we need to pass the type in here is to get
11716   // the sign right on this one case.  It would be nice if APValue
11717   // preserved this.
11718   assert(result.isLValue() || result.isAddrLabelDiff());
11719   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11720 }
11721 
11722 static QualType GetExprType(const Expr *E) {
11723   QualType Ty = E->getType();
11724   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11725     Ty = AtomicRHS->getValueType();
11726   return Ty;
11727 }
11728 
11729 /// Pseudo-evaluate the given integer expression, estimating the
11730 /// range of values it might take.
11731 ///
11732 /// \param MaxWidth The width to which the value will be truncated.
11733 /// \param Approximate If \c true, return a likely range for the result: in
11734 ///        particular, assume that arithmetic on narrower types doesn't leave
11735 ///        those types. If \c false, return a range including all possible
11736 ///        result values.
11737 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11738                              bool InConstantContext, bool Approximate) {
11739   E = E->IgnoreParens();
11740 
11741   // Try a full evaluation first.
11742   Expr::EvalResult result;
11743   if (E->EvaluateAsRValue(result, C, InConstantContext))
11744     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11745 
11746   // I think we only want to look through implicit casts here; if the
11747   // user has an explicit widening cast, we should treat the value as
11748   // being of the new, wider type.
11749   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11750     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11751       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11752                           Approximate);
11753 
11754     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11755 
11756     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11757                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11758 
11759     // Assume that non-integer casts can span the full range of the type.
11760     if (!isIntegerCast)
11761       return OutputTypeRange;
11762 
11763     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11764                                      std::min(MaxWidth, OutputTypeRange.Width),
11765                                      InConstantContext, Approximate);
11766 
11767     // Bail out if the subexpr's range is as wide as the cast type.
11768     if (SubRange.Width >= OutputTypeRange.Width)
11769       return OutputTypeRange;
11770 
11771     // Otherwise, we take the smaller width, and we're non-negative if
11772     // either the output type or the subexpr is.
11773     return IntRange(SubRange.Width,
11774                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11775   }
11776 
11777   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11778     // If we can fold the condition, just take that operand.
11779     bool CondResult;
11780     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11781       return GetExprRange(C,
11782                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11783                           MaxWidth, InConstantContext, Approximate);
11784 
11785     // Otherwise, conservatively merge.
11786     // GetExprRange requires an integer expression, but a throw expression
11787     // results in a void type.
11788     Expr *E = CO->getTrueExpr();
11789     IntRange L = E->getType()->isVoidType()
11790                      ? IntRange{0, true}
11791                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11792     E = CO->getFalseExpr();
11793     IntRange R = E->getType()->isVoidType()
11794                      ? IntRange{0, true}
11795                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11796     return IntRange::join(L, R);
11797   }
11798 
11799   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11800     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11801 
11802     switch (BO->getOpcode()) {
11803     case BO_Cmp:
11804       llvm_unreachable("builtin <=> should have class type");
11805 
11806     // Boolean-valued operations are single-bit and positive.
11807     case BO_LAnd:
11808     case BO_LOr:
11809     case BO_LT:
11810     case BO_GT:
11811     case BO_LE:
11812     case BO_GE:
11813     case BO_EQ:
11814     case BO_NE:
11815       return IntRange::forBoolType();
11816 
11817     // The type of the assignments is the type of the LHS, so the RHS
11818     // is not necessarily the same type.
11819     case BO_MulAssign:
11820     case BO_DivAssign:
11821     case BO_RemAssign:
11822     case BO_AddAssign:
11823     case BO_SubAssign:
11824     case BO_XorAssign:
11825     case BO_OrAssign:
11826       // TODO: bitfields?
11827       return IntRange::forValueOfType(C, GetExprType(E));
11828 
11829     // Simple assignments just pass through the RHS, which will have
11830     // been coerced to the LHS type.
11831     case BO_Assign:
11832       // TODO: bitfields?
11833       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11834                           Approximate);
11835 
11836     // Operations with opaque sources are black-listed.
11837     case BO_PtrMemD:
11838     case BO_PtrMemI:
11839       return IntRange::forValueOfType(C, GetExprType(E));
11840 
11841     // Bitwise-and uses the *infinum* of the two source ranges.
11842     case BO_And:
11843     case BO_AndAssign:
11844       Combine = IntRange::bit_and;
11845       break;
11846 
11847     // Left shift gets black-listed based on a judgement call.
11848     case BO_Shl:
11849       // ...except that we want to treat '1 << (blah)' as logically
11850       // positive.  It's an important idiom.
11851       if (IntegerLiteral *I
11852             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11853         if (I->getValue() == 1) {
11854           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11855           return IntRange(R.Width, /*NonNegative*/ true);
11856         }
11857       }
11858       LLVM_FALLTHROUGH;
11859 
11860     case BO_ShlAssign:
11861       return IntRange::forValueOfType(C, GetExprType(E));
11862 
11863     // Right shift by a constant can narrow its left argument.
11864     case BO_Shr:
11865     case BO_ShrAssign: {
11866       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11867                                 Approximate);
11868 
11869       // If the shift amount is a positive constant, drop the width by
11870       // that much.
11871       if (Optional<llvm::APSInt> shift =
11872               BO->getRHS()->getIntegerConstantExpr(C)) {
11873         if (shift->isNonNegative()) {
11874           unsigned zext = shift->getZExtValue();
11875           if (zext >= L.Width)
11876             L.Width = (L.NonNegative ? 0 : 1);
11877           else
11878             L.Width -= zext;
11879         }
11880       }
11881 
11882       return L;
11883     }
11884 
11885     // Comma acts as its right operand.
11886     case BO_Comma:
11887       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11888                           Approximate);
11889 
11890     case BO_Add:
11891       if (!Approximate)
11892         Combine = IntRange::sum;
11893       break;
11894 
11895     case BO_Sub:
11896       if (BO->getLHS()->getType()->isPointerType())
11897         return IntRange::forValueOfType(C, GetExprType(E));
11898       if (!Approximate)
11899         Combine = IntRange::difference;
11900       break;
11901 
11902     case BO_Mul:
11903       if (!Approximate)
11904         Combine = IntRange::product;
11905       break;
11906 
11907     // The width of a division result is mostly determined by the size
11908     // of the LHS.
11909     case BO_Div: {
11910       // Don't 'pre-truncate' the operands.
11911       unsigned opWidth = C.getIntWidth(GetExprType(E));
11912       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11913                                 Approximate);
11914 
11915       // If the divisor is constant, use that.
11916       if (Optional<llvm::APSInt> divisor =
11917               BO->getRHS()->getIntegerConstantExpr(C)) {
11918         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11919         if (log2 >= L.Width)
11920           L.Width = (L.NonNegative ? 0 : 1);
11921         else
11922           L.Width = std::min(L.Width - log2, MaxWidth);
11923         return L;
11924       }
11925 
11926       // Otherwise, just use the LHS's width.
11927       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11928       // could be -1.
11929       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11930                                 Approximate);
11931       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11932     }
11933 
11934     case BO_Rem:
11935       Combine = IntRange::rem;
11936       break;
11937 
11938     // The default behavior is okay for these.
11939     case BO_Xor:
11940     case BO_Or:
11941       break;
11942     }
11943 
11944     // Combine the two ranges, but limit the result to the type in which we
11945     // performed the computation.
11946     QualType T = GetExprType(E);
11947     unsigned opWidth = C.getIntWidth(T);
11948     IntRange L =
11949         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11950     IntRange R =
11951         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11952     IntRange C = Combine(L, R);
11953     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11954     C.Width = std::min(C.Width, MaxWidth);
11955     return C;
11956   }
11957 
11958   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11959     switch (UO->getOpcode()) {
11960     // Boolean-valued operations are white-listed.
11961     case UO_LNot:
11962       return IntRange::forBoolType();
11963 
11964     // Operations with opaque sources are black-listed.
11965     case UO_Deref:
11966     case UO_AddrOf: // should be impossible
11967       return IntRange::forValueOfType(C, GetExprType(E));
11968 
11969     default:
11970       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11971                           Approximate);
11972     }
11973   }
11974 
11975   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11976     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11977                         Approximate);
11978 
11979   if (const auto *BitField = E->getSourceBitField())
11980     return IntRange(BitField->getBitWidthValue(C),
11981                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11982 
11983   return IntRange::forValueOfType(C, GetExprType(E));
11984 }
11985 
11986 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11987                              bool InConstantContext, bool Approximate) {
11988   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11989                       Approximate);
11990 }
11991 
11992 /// Checks whether the given value, which currently has the given
11993 /// source semantics, has the same value when coerced through the
11994 /// target semantics.
11995 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11996                                  const llvm::fltSemantics &Src,
11997                                  const llvm::fltSemantics &Tgt) {
11998   llvm::APFloat truncated = value;
11999 
12000   bool ignored;
12001   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
12002   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
12003 
12004   return truncated.bitwiseIsEqual(value);
12005 }
12006 
12007 /// Checks whether the given value, which currently has the given
12008 /// source semantics, has the same value when coerced through the
12009 /// target semantics.
12010 ///
12011 /// The value might be a vector of floats (or a complex number).
12012 static bool IsSameFloatAfterCast(const APValue &value,
12013                                  const llvm::fltSemantics &Src,
12014                                  const llvm::fltSemantics &Tgt) {
12015   if (value.isFloat())
12016     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
12017 
12018   if (value.isVector()) {
12019     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
12020       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
12021         return false;
12022     return true;
12023   }
12024 
12025   assert(value.isComplexFloat());
12026   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
12027           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
12028 }
12029 
12030 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
12031                                        bool IsListInit = false);
12032 
12033 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
12034   // Suppress cases where we are comparing against an enum constant.
12035   if (const DeclRefExpr *DR =
12036       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
12037     if (isa<EnumConstantDecl>(DR->getDecl()))
12038       return true;
12039 
12040   // Suppress cases where the value is expanded from a macro, unless that macro
12041   // is how a language represents a boolean literal. This is the case in both C
12042   // and Objective-C.
12043   SourceLocation BeginLoc = E->getBeginLoc();
12044   if (BeginLoc.isMacroID()) {
12045     StringRef MacroName = Lexer::getImmediateMacroName(
12046         BeginLoc, S.getSourceManager(), S.getLangOpts());
12047     return MacroName != "YES" && MacroName != "NO" &&
12048            MacroName != "true" && MacroName != "false";
12049   }
12050 
12051   return false;
12052 }
12053 
12054 static bool isKnownToHaveUnsignedValue(Expr *E) {
12055   return E->getType()->isIntegerType() &&
12056          (!E->getType()->isSignedIntegerType() ||
12057           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
12058 }
12059 
12060 namespace {
12061 /// The promoted range of values of a type. In general this has the
12062 /// following structure:
12063 ///
12064 ///     |-----------| . . . |-----------|
12065 ///     ^           ^       ^           ^
12066 ///    Min       HoleMin  HoleMax      Max
12067 ///
12068 /// ... where there is only a hole if a signed type is promoted to unsigned
12069 /// (in which case Min and Max are the smallest and largest representable
12070 /// values).
12071 struct PromotedRange {
12072   // Min, or HoleMax if there is a hole.
12073   llvm::APSInt PromotedMin;
12074   // Max, or HoleMin if there is a hole.
12075   llvm::APSInt PromotedMax;
12076 
12077   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12078     if (R.Width == 0)
12079       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12080     else if (R.Width >= BitWidth && !Unsigned) {
12081       // Promotion made the type *narrower*. This happens when promoting
12082       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12083       // Treat all values of 'signed int' as being in range for now.
12084       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
12085       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
12086     } else {
12087       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
12088                         .extOrTrunc(BitWidth);
12089       PromotedMin.setIsUnsigned(Unsigned);
12090 
12091       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
12092                         .extOrTrunc(BitWidth);
12093       PromotedMax.setIsUnsigned(Unsigned);
12094     }
12095   }
12096 
12097   // Determine whether this range is contiguous (has no hole).
12098   bool isContiguous() const { return PromotedMin <= PromotedMax; }
12099 
12100   // Where a constant value is within the range.
12101   enum ComparisonResult {
12102     LT = 0x1,
12103     LE = 0x2,
12104     GT = 0x4,
12105     GE = 0x8,
12106     EQ = 0x10,
12107     NE = 0x20,
12108     InRangeFlag = 0x40,
12109 
12110     Less = LE | LT | NE,
12111     Min = LE | InRangeFlag,
12112     InRange = InRangeFlag,
12113     Max = GE | InRangeFlag,
12114     Greater = GE | GT | NE,
12115 
12116     OnlyValue = LE | GE | EQ | InRangeFlag,
12117     InHole = NE
12118   };
12119 
12120   ComparisonResult compare(const llvm::APSInt &Value) const {
12121     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12122            Value.isUnsigned() == PromotedMin.isUnsigned());
12123     if (!isContiguous()) {
12124       assert(Value.isUnsigned() && "discontiguous range for signed compare");
12125       if (Value.isMinValue()) return Min;
12126       if (Value.isMaxValue()) return Max;
12127       if (Value >= PromotedMin) return InRange;
12128       if (Value <= PromotedMax) return InRange;
12129       return InHole;
12130     }
12131 
12132     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
12133     case -1: return Less;
12134     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12135     case 1:
12136       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
12137       case -1: return InRange;
12138       case 0: return Max;
12139       case 1: return Greater;
12140       }
12141     }
12142 
12143     llvm_unreachable("impossible compare result");
12144   }
12145 
12146   static llvm::Optional<StringRef>
12147   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12148     if (Op == BO_Cmp) {
12149       ComparisonResult LTFlag = LT, GTFlag = GT;
12150       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
12151 
12152       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12153       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12154       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12155       return llvm::None;
12156     }
12157 
12158     ComparisonResult TrueFlag, FalseFlag;
12159     if (Op == BO_EQ) {
12160       TrueFlag = EQ;
12161       FalseFlag = NE;
12162     } else if (Op == BO_NE) {
12163       TrueFlag = NE;
12164       FalseFlag = EQ;
12165     } else {
12166       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12167         TrueFlag = LT;
12168         FalseFlag = GE;
12169       } else {
12170         TrueFlag = GT;
12171         FalseFlag = LE;
12172       }
12173       if (Op == BO_GE || Op == BO_LE)
12174         std::swap(TrueFlag, FalseFlag);
12175     }
12176     if (R & TrueFlag)
12177       return StringRef("true");
12178     if (R & FalseFlag)
12179       return StringRef("false");
12180     return llvm::None;
12181   }
12182 };
12183 }
12184 
12185 static bool HasEnumType(Expr *E) {
12186   // Strip off implicit integral promotions.
12187   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12188     if (ICE->getCastKind() != CK_IntegralCast &&
12189         ICE->getCastKind() != CK_NoOp)
12190       break;
12191     E = ICE->getSubExpr();
12192   }
12193 
12194   return E->getType()->isEnumeralType();
12195 }
12196 
12197 static int classifyConstantValue(Expr *Constant) {
12198   // The values of this enumeration are used in the diagnostics
12199   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12200   enum ConstantValueKind {
12201     Miscellaneous = 0,
12202     LiteralTrue,
12203     LiteralFalse
12204   };
12205   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12206     return BL->getValue() ? ConstantValueKind::LiteralTrue
12207                           : ConstantValueKind::LiteralFalse;
12208   return ConstantValueKind::Miscellaneous;
12209 }
12210 
12211 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
12212                                         Expr *Constant, Expr *Other,
12213                                         const llvm::APSInt &Value,
12214                                         bool RhsConstant) {
12215   if (S.inTemplateInstantiation())
12216     return false;
12217 
12218   Expr *OriginalOther = Other;
12219 
12220   Constant = Constant->IgnoreParenImpCasts();
12221   Other = Other->IgnoreParenImpCasts();
12222 
12223   // Suppress warnings on tautological comparisons between values of the same
12224   // enumeration type. There are only two ways we could warn on this:
12225   //  - If the constant is outside the range of representable values of
12226   //    the enumeration. In such a case, we should warn about the cast
12227   //    to enumeration type, not about the comparison.
12228   //  - If the constant is the maximum / minimum in-range value. For an
12229   //    enumeratin type, such comparisons can be meaningful and useful.
12230   if (Constant->getType()->isEnumeralType() &&
12231       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12232     return false;
12233 
12234   IntRange OtherValueRange = GetExprRange(
12235       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
12236 
12237   QualType OtherT = Other->getType();
12238   if (const auto *AT = OtherT->getAs<AtomicType>())
12239     OtherT = AT->getValueType();
12240   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12241 
12242   // Special case for ObjC BOOL on targets where its a typedef for a signed char
12243   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12244   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12245                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
12246                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12247 
12248   // Whether we're treating Other as being a bool because of the form of
12249   // expression despite it having another type (typically 'int' in C).
12250   bool OtherIsBooleanDespiteType =
12251       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12252   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12253     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
12254 
12255   // Check if all values in the range of possible values of this expression
12256   // lead to the same comparison outcome.
12257   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
12258                                         Value.isUnsigned());
12259   auto Cmp = OtherPromotedValueRange.compare(Value);
12260   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12261   if (!Result)
12262     return false;
12263 
12264   // Also consider the range determined by the type alone. This allows us to
12265   // classify the warning under the proper diagnostic group.
12266   bool TautologicalTypeCompare = false;
12267   {
12268     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12269                                          Value.isUnsigned());
12270     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12271     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12272                                                        RhsConstant)) {
12273       TautologicalTypeCompare = true;
12274       Cmp = TypeCmp;
12275       Result = TypeResult;
12276     }
12277   }
12278 
12279   // Don't warn if the non-constant operand actually always evaluates to the
12280   // same value.
12281   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
12282     return false;
12283 
12284   // Suppress the diagnostic for an in-range comparison if the constant comes
12285   // from a macro or enumerator. We don't want to diagnose
12286   //
12287   //   some_long_value <= INT_MAX
12288   //
12289   // when sizeof(int) == sizeof(long).
12290   bool InRange = Cmp & PromotedRange::InRangeFlag;
12291   if (InRange && IsEnumConstOrFromMacro(S, Constant))
12292     return false;
12293 
12294   // A comparison of an unsigned bit-field against 0 is really a type problem,
12295   // even though at the type level the bit-field might promote to 'signed int'.
12296   if (Other->refersToBitField() && InRange && Value == 0 &&
12297       Other->getType()->isUnsignedIntegerOrEnumerationType())
12298     TautologicalTypeCompare = true;
12299 
12300   // If this is a comparison to an enum constant, include that
12301   // constant in the diagnostic.
12302   const EnumConstantDecl *ED = nullptr;
12303   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
12304     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12305 
12306   // Should be enough for uint128 (39 decimal digits)
12307   SmallString<64> PrettySourceValue;
12308   llvm::raw_svector_ostream OS(PrettySourceValue);
12309   if (ED) {
12310     OS << '\'' << *ED << "' (" << Value << ")";
12311   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12312                Constant->IgnoreParenImpCasts())) {
12313     OS << (BL->getValue() ? "YES" : "NO");
12314   } else {
12315     OS << Value;
12316   }
12317 
12318   if (!TautologicalTypeCompare) {
12319     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12320         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
12321         << E->getOpcodeStr() << OS.str() << *Result
12322         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12323     return true;
12324   }
12325 
12326   if (IsObjCSignedCharBool) {
12327     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12328                           S.PDiag(diag::warn_tautological_compare_objc_bool)
12329                               << OS.str() << *Result);
12330     return true;
12331   }
12332 
12333   // FIXME: We use a somewhat different formatting for the in-range cases and
12334   // cases involving boolean values for historical reasons. We should pick a
12335   // consistent way of presenting these diagnostics.
12336   if (!InRange || Other->isKnownToHaveBooleanValue()) {
12337 
12338     S.DiagRuntimeBehavior(
12339         E->getOperatorLoc(), E,
12340         S.PDiag(!InRange ? diag::warn_out_of_range_compare
12341                          : diag::warn_tautological_bool_compare)
12342             << OS.str() << classifyConstantValue(Constant) << OtherT
12343             << OtherIsBooleanDespiteType << *Result
12344             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12345   } else {
12346     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12347     unsigned Diag =
12348         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12349             ? (HasEnumType(OriginalOther)
12350                    ? diag::warn_unsigned_enum_always_true_comparison
12351                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12352                               : diag::warn_unsigned_always_true_comparison)
12353             : diag::warn_tautological_constant_compare;
12354 
12355     S.Diag(E->getOperatorLoc(), Diag)
12356         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12357         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12358   }
12359 
12360   return true;
12361 }
12362 
12363 /// Analyze the operands of the given comparison.  Implements the
12364 /// fallback case from AnalyzeComparison.
12365 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12366   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12367   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12368 }
12369 
12370 /// Implements -Wsign-compare.
12371 ///
12372 /// \param E the binary operator to check for warnings
12373 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12374   // The type the comparison is being performed in.
12375   QualType T = E->getLHS()->getType();
12376 
12377   // Only analyze comparison operators where both sides have been converted to
12378   // the same type.
12379   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12380     return AnalyzeImpConvsInComparison(S, E);
12381 
12382   // Don't analyze value-dependent comparisons directly.
12383   if (E->isValueDependent())
12384     return AnalyzeImpConvsInComparison(S, E);
12385 
12386   Expr *LHS = E->getLHS();
12387   Expr *RHS = E->getRHS();
12388 
12389   if (T->isIntegralType(S.Context)) {
12390     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
12391     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
12392 
12393     // We don't care about expressions whose result is a constant.
12394     if (RHSValue && LHSValue)
12395       return AnalyzeImpConvsInComparison(S, E);
12396 
12397     // We only care about expressions where just one side is literal
12398     if ((bool)RHSValue ^ (bool)LHSValue) {
12399       // Is the constant on the RHS or LHS?
12400       const bool RhsConstant = (bool)RHSValue;
12401       Expr *Const = RhsConstant ? RHS : LHS;
12402       Expr *Other = RhsConstant ? LHS : RHS;
12403       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12404 
12405       // Check whether an integer constant comparison results in a value
12406       // of 'true' or 'false'.
12407       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12408         return AnalyzeImpConvsInComparison(S, E);
12409     }
12410   }
12411 
12412   if (!T->hasUnsignedIntegerRepresentation()) {
12413     // We don't do anything special if this isn't an unsigned integral
12414     // comparison:  we're only interested in integral comparisons, and
12415     // signed comparisons only happen in cases we don't care to warn about.
12416     return AnalyzeImpConvsInComparison(S, E);
12417   }
12418 
12419   LHS = LHS->IgnoreParenImpCasts();
12420   RHS = RHS->IgnoreParenImpCasts();
12421 
12422   if (!S.getLangOpts().CPlusPlus) {
12423     // Avoid warning about comparison of integers with different signs when
12424     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12425     // the type of `E`.
12426     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12427       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12428     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12429       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12430   }
12431 
12432   // Check to see if one of the (unmodified) operands is of different
12433   // signedness.
12434   Expr *signedOperand, *unsignedOperand;
12435   if (LHS->getType()->hasSignedIntegerRepresentation()) {
12436     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12437            "unsigned comparison between two signed integer expressions?");
12438     signedOperand = LHS;
12439     unsignedOperand = RHS;
12440   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12441     signedOperand = RHS;
12442     unsignedOperand = LHS;
12443   } else {
12444     return AnalyzeImpConvsInComparison(S, E);
12445   }
12446 
12447   // Otherwise, calculate the effective range of the signed operand.
12448   IntRange signedRange = GetExprRange(
12449       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
12450 
12451   // Go ahead and analyze implicit conversions in the operands.  Note
12452   // that we skip the implicit conversions on both sides.
12453   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
12454   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
12455 
12456   // If the signed range is non-negative, -Wsign-compare won't fire.
12457   if (signedRange.NonNegative)
12458     return;
12459 
12460   // For (in)equality comparisons, if the unsigned operand is a
12461   // constant which cannot collide with a overflowed signed operand,
12462   // then reinterpreting the signed operand as unsigned will not
12463   // change the result of the comparison.
12464   if (E->isEqualityOp()) {
12465     unsigned comparisonWidth = S.Context.getIntWidth(T);
12466     IntRange unsignedRange =
12467         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
12468                      /*Approximate*/ true);
12469 
12470     // We should never be unable to prove that the unsigned operand is
12471     // non-negative.
12472     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
12473 
12474     if (unsignedRange.Width < comparisonWidth)
12475       return;
12476   }
12477 
12478   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12479                         S.PDiag(diag::warn_mixed_sign_comparison)
12480                             << LHS->getType() << RHS->getType()
12481                             << LHS->getSourceRange() << RHS->getSourceRange());
12482 }
12483 
12484 /// Analyzes an attempt to assign the given value to a bitfield.
12485 ///
12486 /// Returns true if there was something fishy about the attempt.
12487 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12488                                       SourceLocation InitLoc) {
12489   assert(Bitfield->isBitField());
12490   if (Bitfield->isInvalidDecl())
12491     return false;
12492 
12493   // White-list bool bitfields.
12494   QualType BitfieldType = Bitfield->getType();
12495   if (BitfieldType->isBooleanType())
12496      return false;
12497 
12498   if (BitfieldType->isEnumeralType()) {
12499     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12500     // If the underlying enum type was not explicitly specified as an unsigned
12501     // type and the enum contain only positive values, MSVC++ will cause an
12502     // inconsistency by storing this as a signed type.
12503     if (S.getLangOpts().CPlusPlus11 &&
12504         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12505         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12506         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12507       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12508           << BitfieldEnumDecl;
12509     }
12510   }
12511 
12512   if (Bitfield->getType()->isBooleanType())
12513     return false;
12514 
12515   // Ignore value- or type-dependent expressions.
12516   if (Bitfield->getBitWidth()->isValueDependent() ||
12517       Bitfield->getBitWidth()->isTypeDependent() ||
12518       Init->isValueDependent() ||
12519       Init->isTypeDependent())
12520     return false;
12521 
12522   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12523   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12524 
12525   Expr::EvalResult Result;
12526   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12527                                    Expr::SE_AllowSideEffects)) {
12528     // The RHS is not constant.  If the RHS has an enum type, make sure the
12529     // bitfield is wide enough to hold all the values of the enum without
12530     // truncation.
12531     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12532       EnumDecl *ED = EnumTy->getDecl();
12533       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12534 
12535       // Enum types are implicitly signed on Windows, so check if there are any
12536       // negative enumerators to see if the enum was intended to be signed or
12537       // not.
12538       bool SignedEnum = ED->getNumNegativeBits() > 0;
12539 
12540       // Check for surprising sign changes when assigning enum values to a
12541       // bitfield of different signedness.  If the bitfield is signed and we
12542       // have exactly the right number of bits to store this unsigned enum,
12543       // suggest changing the enum to an unsigned type. This typically happens
12544       // on Windows where unfixed enums always use an underlying type of 'int'.
12545       unsigned DiagID = 0;
12546       if (SignedEnum && !SignedBitfield) {
12547         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12548       } else if (SignedBitfield && !SignedEnum &&
12549                  ED->getNumPositiveBits() == FieldWidth) {
12550         DiagID = diag::warn_signed_bitfield_enum_conversion;
12551       }
12552 
12553       if (DiagID) {
12554         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12555         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12556         SourceRange TypeRange =
12557             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12558         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12559             << SignedEnum << TypeRange;
12560       }
12561 
12562       // Compute the required bitwidth. If the enum has negative values, we need
12563       // one more bit than the normal number of positive bits to represent the
12564       // sign bit.
12565       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12566                                                   ED->getNumNegativeBits())
12567                                        : ED->getNumPositiveBits();
12568 
12569       // Check the bitwidth.
12570       if (BitsNeeded > FieldWidth) {
12571         Expr *WidthExpr = Bitfield->getBitWidth();
12572         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12573             << Bitfield << ED;
12574         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12575             << BitsNeeded << ED << WidthExpr->getSourceRange();
12576       }
12577     }
12578 
12579     return false;
12580   }
12581 
12582   llvm::APSInt Value = Result.Val.getInt();
12583 
12584   unsigned OriginalWidth = Value.getBitWidth();
12585 
12586   if (!Value.isSigned() || Value.isNegative())
12587     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12588       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12589         OriginalWidth = Value.getMinSignedBits();
12590 
12591   if (OriginalWidth <= FieldWidth)
12592     return false;
12593 
12594   // Compute the value which the bitfield will contain.
12595   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12596   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12597 
12598   // Check whether the stored value is equal to the original value.
12599   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12600   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12601     return false;
12602 
12603   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12604   // therefore don't strictly fit into a signed bitfield of width 1.
12605   if (FieldWidth == 1 && Value == 1)
12606     return false;
12607 
12608   std::string PrettyValue = toString(Value, 10);
12609   std::string PrettyTrunc = toString(TruncatedValue, 10);
12610 
12611   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12612     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12613     << Init->getSourceRange();
12614 
12615   return true;
12616 }
12617 
12618 /// Analyze the given simple or compound assignment for warning-worthy
12619 /// operations.
12620 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12621   // Just recurse on the LHS.
12622   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12623 
12624   // We want to recurse on the RHS as normal unless we're assigning to
12625   // a bitfield.
12626   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12627     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12628                                   E->getOperatorLoc())) {
12629       // Recurse, ignoring any implicit conversions on the RHS.
12630       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12631                                         E->getOperatorLoc());
12632     }
12633   }
12634 
12635   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12636 
12637   // Diagnose implicitly sequentially-consistent atomic assignment.
12638   if (E->getLHS()->getType()->isAtomicType())
12639     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12640 }
12641 
12642 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12643 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12644                             SourceLocation CContext, unsigned diag,
12645                             bool pruneControlFlow = false) {
12646   if (pruneControlFlow) {
12647     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12648                           S.PDiag(diag)
12649                               << SourceType << T << E->getSourceRange()
12650                               << SourceRange(CContext));
12651     return;
12652   }
12653   S.Diag(E->getExprLoc(), diag)
12654     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12655 }
12656 
12657 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12658 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12659                             SourceLocation CContext,
12660                             unsigned diag, bool pruneControlFlow = false) {
12661   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12662 }
12663 
12664 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12665   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12666       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12667 }
12668 
12669 static void adornObjCBoolConversionDiagWithTernaryFixit(
12670     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12671   Expr *Ignored = SourceExpr->IgnoreImplicit();
12672   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12673     Ignored = OVE->getSourceExpr();
12674   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12675                      isa<BinaryOperator>(Ignored) ||
12676                      isa<CXXOperatorCallExpr>(Ignored);
12677   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12678   if (NeedsParens)
12679     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12680             << FixItHint::CreateInsertion(EndLoc, ")");
12681   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12682 }
12683 
12684 /// Diagnose an implicit cast from a floating point value to an integer value.
12685 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12686                                     SourceLocation CContext) {
12687   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12688   const bool PruneWarnings = S.inTemplateInstantiation();
12689 
12690   Expr *InnerE = E->IgnoreParenImpCasts();
12691   // We also want to warn on, e.g., "int i = -1.234"
12692   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12693     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12694       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12695 
12696   const bool IsLiteral =
12697       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12698 
12699   llvm::APFloat Value(0.0);
12700   bool IsConstant =
12701     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12702   if (!IsConstant) {
12703     if (isObjCSignedCharBool(S, T)) {
12704       return adornObjCBoolConversionDiagWithTernaryFixit(
12705           S, E,
12706           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12707               << E->getType());
12708     }
12709 
12710     return DiagnoseImpCast(S, E, T, CContext,
12711                            diag::warn_impcast_float_integer, PruneWarnings);
12712   }
12713 
12714   bool isExact = false;
12715 
12716   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12717                             T->hasUnsignedIntegerRepresentation());
12718   llvm::APFloat::opStatus Result = Value.convertToInteger(
12719       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12720 
12721   // FIXME: Force the precision of the source value down so we don't print
12722   // digits which are usually useless (we don't really care here if we
12723   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12724   // would automatically print the shortest representation, but it's a bit
12725   // tricky to implement.
12726   SmallString<16> PrettySourceValue;
12727   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12728   precision = (precision * 59 + 195) / 196;
12729   Value.toString(PrettySourceValue, precision);
12730 
12731   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12732     return adornObjCBoolConversionDiagWithTernaryFixit(
12733         S, E,
12734         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12735             << PrettySourceValue);
12736   }
12737 
12738   if (Result == llvm::APFloat::opOK && isExact) {
12739     if (IsLiteral) return;
12740     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12741                            PruneWarnings);
12742   }
12743 
12744   // Conversion of a floating-point value to a non-bool integer where the
12745   // integral part cannot be represented by the integer type is undefined.
12746   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12747     return DiagnoseImpCast(
12748         S, E, T, CContext,
12749         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12750                   : diag::warn_impcast_float_to_integer_out_of_range,
12751         PruneWarnings);
12752 
12753   unsigned DiagID = 0;
12754   if (IsLiteral) {
12755     // Warn on floating point literal to integer.
12756     DiagID = diag::warn_impcast_literal_float_to_integer;
12757   } else if (IntegerValue == 0) {
12758     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12759       return DiagnoseImpCast(S, E, T, CContext,
12760                              diag::warn_impcast_float_integer, PruneWarnings);
12761     }
12762     // Warn on non-zero to zero conversion.
12763     DiagID = diag::warn_impcast_float_to_integer_zero;
12764   } else {
12765     if (IntegerValue.isUnsigned()) {
12766       if (!IntegerValue.isMaxValue()) {
12767         return DiagnoseImpCast(S, E, T, CContext,
12768                                diag::warn_impcast_float_integer, PruneWarnings);
12769       }
12770     } else {  // IntegerValue.isSigned()
12771       if (!IntegerValue.isMaxSignedValue() &&
12772           !IntegerValue.isMinSignedValue()) {
12773         return DiagnoseImpCast(S, E, T, CContext,
12774                                diag::warn_impcast_float_integer, PruneWarnings);
12775       }
12776     }
12777     // Warn on evaluatable floating point expression to integer conversion.
12778     DiagID = diag::warn_impcast_float_to_integer;
12779   }
12780 
12781   SmallString<16> PrettyTargetValue;
12782   if (IsBool)
12783     PrettyTargetValue = Value.isZero() ? "false" : "true";
12784   else
12785     IntegerValue.toString(PrettyTargetValue);
12786 
12787   if (PruneWarnings) {
12788     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12789                           S.PDiag(DiagID)
12790                               << E->getType() << T.getUnqualifiedType()
12791                               << PrettySourceValue << PrettyTargetValue
12792                               << E->getSourceRange() << SourceRange(CContext));
12793   } else {
12794     S.Diag(E->getExprLoc(), DiagID)
12795         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12796         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12797   }
12798 }
12799 
12800 /// Analyze the given compound assignment for the possible losing of
12801 /// floating-point precision.
12802 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12803   assert(isa<CompoundAssignOperator>(E) &&
12804          "Must be compound assignment operation");
12805   // Recurse on the LHS and RHS in here
12806   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12807   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12808 
12809   if (E->getLHS()->getType()->isAtomicType())
12810     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12811 
12812   // Now check the outermost expression
12813   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12814   const auto *RBT = cast<CompoundAssignOperator>(E)
12815                         ->getComputationResultType()
12816                         ->getAs<BuiltinType>();
12817 
12818   // The below checks assume source is floating point.
12819   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12820 
12821   // If source is floating point but target is an integer.
12822   if (ResultBT->isInteger())
12823     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12824                            E->getExprLoc(), diag::warn_impcast_float_integer);
12825 
12826   if (!ResultBT->isFloatingPoint())
12827     return;
12828 
12829   // If both source and target are floating points, warn about losing precision.
12830   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12831       QualType(ResultBT, 0), QualType(RBT, 0));
12832   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12833     // warn about dropping FP rank.
12834     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12835                     diag::warn_impcast_float_result_precision);
12836 }
12837 
12838 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12839                                       IntRange Range) {
12840   if (!Range.Width) return "0";
12841 
12842   llvm::APSInt ValueInRange = Value;
12843   ValueInRange.setIsSigned(!Range.NonNegative);
12844   ValueInRange = ValueInRange.trunc(Range.Width);
12845   return toString(ValueInRange, 10);
12846 }
12847 
12848 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12849   if (!isa<ImplicitCastExpr>(Ex))
12850     return false;
12851 
12852   Expr *InnerE = Ex->IgnoreParenImpCasts();
12853   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12854   const Type *Source =
12855     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12856   if (Target->isDependentType())
12857     return false;
12858 
12859   const BuiltinType *FloatCandidateBT =
12860     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12861   const Type *BoolCandidateType = ToBool ? Target : Source;
12862 
12863   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12864           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12865 }
12866 
12867 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12868                                              SourceLocation CC) {
12869   unsigned NumArgs = TheCall->getNumArgs();
12870   for (unsigned i = 0; i < NumArgs; ++i) {
12871     Expr *CurrA = TheCall->getArg(i);
12872     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12873       continue;
12874 
12875     bool IsSwapped = ((i > 0) &&
12876         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12877     IsSwapped |= ((i < (NumArgs - 1)) &&
12878         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12879     if (IsSwapped) {
12880       // Warn on this floating-point to bool conversion.
12881       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12882                       CurrA->getType(), CC,
12883                       diag::warn_impcast_floating_point_to_bool);
12884     }
12885   }
12886 }
12887 
12888 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12889                                    SourceLocation CC) {
12890   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12891                         E->getExprLoc()))
12892     return;
12893 
12894   // Don't warn on functions which have return type nullptr_t.
12895   if (isa<CallExpr>(E))
12896     return;
12897 
12898   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12899   const Expr::NullPointerConstantKind NullKind =
12900       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12901   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12902     return;
12903 
12904   // Return if target type is a safe conversion.
12905   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12906       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12907     return;
12908 
12909   SourceLocation Loc = E->getSourceRange().getBegin();
12910 
12911   // Venture through the macro stacks to get to the source of macro arguments.
12912   // The new location is a better location than the complete location that was
12913   // passed in.
12914   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12915   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12916 
12917   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12918   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12919     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12920         Loc, S.SourceMgr, S.getLangOpts());
12921     if (MacroName == "NULL")
12922       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12923   }
12924 
12925   // Only warn if the null and context location are in the same macro expansion.
12926   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12927     return;
12928 
12929   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12930       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12931       << FixItHint::CreateReplacement(Loc,
12932                                       S.getFixItZeroLiteralForType(T, Loc));
12933 }
12934 
12935 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12936                                   ObjCArrayLiteral *ArrayLiteral);
12937 
12938 static void
12939 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12940                            ObjCDictionaryLiteral *DictionaryLiteral);
12941 
12942 /// Check a single element within a collection literal against the
12943 /// target element type.
12944 static void checkObjCCollectionLiteralElement(Sema &S,
12945                                               QualType TargetElementType,
12946                                               Expr *Element,
12947                                               unsigned ElementKind) {
12948   // Skip a bitcast to 'id' or qualified 'id'.
12949   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12950     if (ICE->getCastKind() == CK_BitCast &&
12951         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12952       Element = ICE->getSubExpr();
12953   }
12954 
12955   QualType ElementType = Element->getType();
12956   ExprResult ElementResult(Element);
12957   if (ElementType->getAs<ObjCObjectPointerType>() &&
12958       S.CheckSingleAssignmentConstraints(TargetElementType,
12959                                          ElementResult,
12960                                          false, false)
12961         != Sema::Compatible) {
12962     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12963         << ElementType << ElementKind << TargetElementType
12964         << Element->getSourceRange();
12965   }
12966 
12967   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12968     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12969   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12970     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12971 }
12972 
12973 /// Check an Objective-C array literal being converted to the given
12974 /// target type.
12975 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12976                                   ObjCArrayLiteral *ArrayLiteral) {
12977   if (!S.NSArrayDecl)
12978     return;
12979 
12980   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12981   if (!TargetObjCPtr)
12982     return;
12983 
12984   if (TargetObjCPtr->isUnspecialized() ||
12985       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12986         != S.NSArrayDecl->getCanonicalDecl())
12987     return;
12988 
12989   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12990   if (TypeArgs.size() != 1)
12991     return;
12992 
12993   QualType TargetElementType = TypeArgs[0];
12994   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12995     checkObjCCollectionLiteralElement(S, TargetElementType,
12996                                       ArrayLiteral->getElement(I),
12997                                       0);
12998   }
12999 }
13000 
13001 /// Check an Objective-C dictionary literal being converted to the given
13002 /// target type.
13003 static void
13004 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
13005                            ObjCDictionaryLiteral *DictionaryLiteral) {
13006   if (!S.NSDictionaryDecl)
13007     return;
13008 
13009   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
13010   if (!TargetObjCPtr)
13011     return;
13012 
13013   if (TargetObjCPtr->isUnspecialized() ||
13014       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
13015         != S.NSDictionaryDecl->getCanonicalDecl())
13016     return;
13017 
13018   auto TypeArgs = TargetObjCPtr->getTypeArgs();
13019   if (TypeArgs.size() != 2)
13020     return;
13021 
13022   QualType TargetKeyType = TypeArgs[0];
13023   QualType TargetObjectType = TypeArgs[1];
13024   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
13025     auto Element = DictionaryLiteral->getKeyValueElement(I);
13026     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
13027     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
13028   }
13029 }
13030 
13031 // Helper function to filter out cases for constant width constant conversion.
13032 // Don't warn on char array initialization or for non-decimal values.
13033 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
13034                                           SourceLocation CC) {
13035   // If initializing from a constant, and the constant starts with '0',
13036   // then it is a binary, octal, or hexadecimal.  Allow these constants
13037   // to fill all the bits, even if there is a sign change.
13038   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
13039     const char FirstLiteralCharacter =
13040         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
13041     if (FirstLiteralCharacter == '0')
13042       return false;
13043   }
13044 
13045   // If the CC location points to a '{', and the type is char, then assume
13046   // assume it is an array initialization.
13047   if (CC.isValid() && T->isCharType()) {
13048     const char FirstContextCharacter =
13049         S.getSourceManager().getCharacterData(CC)[0];
13050     if (FirstContextCharacter == '{')
13051       return false;
13052   }
13053 
13054   return true;
13055 }
13056 
13057 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
13058   const auto *IL = dyn_cast<IntegerLiteral>(E);
13059   if (!IL) {
13060     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
13061       if (UO->getOpcode() == UO_Minus)
13062         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
13063     }
13064   }
13065 
13066   return IL;
13067 }
13068 
13069 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
13070   E = E->IgnoreParenImpCasts();
13071   SourceLocation ExprLoc = E->getExprLoc();
13072 
13073   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
13074     BinaryOperator::Opcode Opc = BO->getOpcode();
13075     Expr::EvalResult Result;
13076     // Do not diagnose unsigned shifts.
13077     if (Opc == BO_Shl) {
13078       const auto *LHS = getIntegerLiteral(BO->getLHS());
13079       const auto *RHS = getIntegerLiteral(BO->getRHS());
13080       if (LHS && LHS->getValue() == 0)
13081         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
13082       else if (!E->isValueDependent() && LHS && RHS &&
13083                RHS->getValue().isNonNegative() &&
13084                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
13085         S.Diag(ExprLoc, diag::warn_left_shift_always)
13086             << (Result.Val.getInt() != 0);
13087       else if (E->getType()->isSignedIntegerType())
13088         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
13089     }
13090   }
13091 
13092   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
13093     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
13094     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
13095     if (!LHS || !RHS)
13096       return;
13097     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13098         (RHS->getValue() == 0 || RHS->getValue() == 1))
13099       // Do not diagnose common idioms.
13100       return;
13101     if (LHS->getValue() != 0 && RHS->getValue() != 0)
13102       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
13103   }
13104 }
13105 
13106 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
13107                                     SourceLocation CC,
13108                                     bool *ICContext = nullptr,
13109                                     bool IsListInit = false) {
13110   if (E->isTypeDependent() || E->isValueDependent()) return;
13111 
13112   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
13113   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
13114   if (Source == Target) return;
13115   if (Target->isDependentType()) return;
13116 
13117   // If the conversion context location is invalid don't complain. We also
13118   // don't want to emit a warning if the issue occurs from the expansion of
13119   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13120   // delay this check as long as possible. Once we detect we are in that
13121   // scenario, we just return.
13122   if (CC.isInvalid())
13123     return;
13124 
13125   if (Source->isAtomicType())
13126     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
13127 
13128   // Diagnose implicit casts to bool.
13129   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
13130     if (isa<StringLiteral>(E))
13131       // Warn on string literal to bool.  Checks for string literals in logical
13132       // and expressions, for instance, assert(0 && "error here"), are
13133       // prevented by a check in AnalyzeImplicitConversions().
13134       return DiagnoseImpCast(S, E, T, CC,
13135                              diag::warn_impcast_string_literal_to_bool);
13136     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
13137         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
13138       // This covers the literal expressions that evaluate to Objective-C
13139       // objects.
13140       return DiagnoseImpCast(S, E, T, CC,
13141                              diag::warn_impcast_objective_c_literal_to_bool);
13142     }
13143     if (Source->isPointerType() || Source->canDecayToPointerType()) {
13144       // Warn on pointer to bool conversion that is always true.
13145       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
13146                                      SourceRange(CC));
13147     }
13148   }
13149 
13150   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13151   // is a typedef for signed char (macOS), then that constant value has to be 1
13152   // or 0.
13153   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
13154     Expr::EvalResult Result;
13155     if (E->EvaluateAsInt(Result, S.getASTContext(),
13156                          Expr::SE_AllowSideEffects)) {
13157       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13158         adornObjCBoolConversionDiagWithTernaryFixit(
13159             S, E,
13160             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13161                 << toString(Result.Val.getInt(), 10));
13162       }
13163       return;
13164     }
13165   }
13166 
13167   // Check implicit casts from Objective-C collection literals to specialized
13168   // collection types, e.g., NSArray<NSString *> *.
13169   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13170     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
13171   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13172     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
13173 
13174   // Strip vector types.
13175   if (isa<VectorType>(Source)) {
13176     if (Target->isVLSTBuiltinType() &&
13177         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
13178                                          QualType(Source, 0)) ||
13179          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
13180                                             QualType(Source, 0))))
13181       return;
13182 
13183     if (!isa<VectorType>(Target)) {
13184       if (S.SourceMgr.isInSystemMacro(CC))
13185         return;
13186       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
13187     }
13188 
13189     // If the vector cast is cast between two vectors of the same size, it is
13190     // a bitcast, not a conversion.
13191     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
13192       return;
13193 
13194     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13195     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13196   }
13197   if (auto VecTy = dyn_cast<VectorType>(Target))
13198     Target = VecTy->getElementType().getTypePtr();
13199 
13200   // Strip complex types.
13201   if (isa<ComplexType>(Source)) {
13202     if (!isa<ComplexType>(Target)) {
13203       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13204         return;
13205 
13206       return DiagnoseImpCast(S, E, T, CC,
13207                              S.getLangOpts().CPlusPlus
13208                                  ? diag::err_impcast_complex_scalar
13209                                  : diag::warn_impcast_complex_scalar);
13210     }
13211 
13212     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13213     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13214   }
13215 
13216   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13217   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13218 
13219   // If the source is floating point...
13220   if (SourceBT && SourceBT->isFloatingPoint()) {
13221     // ...and the target is floating point...
13222     if (TargetBT && TargetBT->isFloatingPoint()) {
13223       // ...then warn if we're dropping FP rank.
13224 
13225       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
13226           QualType(SourceBT, 0), QualType(TargetBT, 0));
13227       if (Order > 0) {
13228         // Don't warn about float constants that are precisely
13229         // representable in the target type.
13230         Expr::EvalResult result;
13231         if (E->EvaluateAsRValue(result, S.Context)) {
13232           // Value might be a float, a float vector, or a float complex.
13233           if (IsSameFloatAfterCast(result.Val,
13234                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13235                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13236             return;
13237         }
13238 
13239         if (S.SourceMgr.isInSystemMacro(CC))
13240           return;
13241 
13242         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
13243       }
13244       // ... or possibly if we're increasing rank, too
13245       else if (Order < 0) {
13246         if (S.SourceMgr.isInSystemMacro(CC))
13247           return;
13248 
13249         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
13250       }
13251       return;
13252     }
13253 
13254     // If the target is integral, always warn.
13255     if (TargetBT && TargetBT->isInteger()) {
13256       if (S.SourceMgr.isInSystemMacro(CC))
13257         return;
13258 
13259       DiagnoseFloatingImpCast(S, E, T, CC);
13260     }
13261 
13262     // Detect the case where a call result is converted from floating-point to
13263     // to bool, and the final argument to the call is converted from bool, to
13264     // discover this typo:
13265     //
13266     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
13267     //
13268     // FIXME: This is an incredibly special case; is there some more general
13269     // way to detect this class of misplaced-parentheses bug?
13270     if (Target->isBooleanType() && isa<CallExpr>(E)) {
13271       // Check last argument of function call to see if it is an
13272       // implicit cast from a type matching the type the result
13273       // is being cast to.
13274       CallExpr *CEx = cast<CallExpr>(E);
13275       if (unsigned NumArgs = CEx->getNumArgs()) {
13276         Expr *LastA = CEx->getArg(NumArgs - 1);
13277         Expr *InnerE = LastA->IgnoreParenImpCasts();
13278         if (isa<ImplicitCastExpr>(LastA) &&
13279             InnerE->getType()->isBooleanType()) {
13280           // Warn on this floating-point to bool conversion
13281           DiagnoseImpCast(S, E, T, CC,
13282                           diag::warn_impcast_floating_point_to_bool);
13283         }
13284       }
13285     }
13286     return;
13287   }
13288 
13289   // Valid casts involving fixed point types should be accounted for here.
13290   if (Source->isFixedPointType()) {
13291     if (Target->isUnsaturatedFixedPointType()) {
13292       Expr::EvalResult Result;
13293       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
13294                                   S.isConstantEvaluated())) {
13295         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13296         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
13297         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
13298         if (Value > MaxVal || Value < MinVal) {
13299           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13300                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13301                                     << Value.toString() << T
13302                                     << E->getSourceRange()
13303                                     << clang::SourceRange(CC));
13304           return;
13305         }
13306       }
13307     } else if (Target->isIntegerType()) {
13308       Expr::EvalResult Result;
13309       if (!S.isConstantEvaluated() &&
13310           E->EvaluateAsFixedPoint(Result, S.Context,
13311                                   Expr::SE_AllowSideEffects)) {
13312         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13313 
13314         bool Overflowed;
13315         llvm::APSInt IntResult = FXResult.convertToInt(
13316             S.Context.getIntWidth(T),
13317             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
13318 
13319         if (Overflowed) {
13320           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13321                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13322                                     << FXResult.toString() << T
13323                                     << E->getSourceRange()
13324                                     << clang::SourceRange(CC));
13325           return;
13326         }
13327       }
13328     }
13329   } else if (Target->isUnsaturatedFixedPointType()) {
13330     if (Source->isIntegerType()) {
13331       Expr::EvalResult Result;
13332       if (!S.isConstantEvaluated() &&
13333           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
13334         llvm::APSInt Value = Result.Val.getInt();
13335 
13336         bool Overflowed;
13337         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13338             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
13339 
13340         if (Overflowed) {
13341           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13342                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13343                                     << toString(Value, /*Radix=*/10) << T
13344                                     << E->getSourceRange()
13345                                     << clang::SourceRange(CC));
13346           return;
13347         }
13348       }
13349     }
13350   }
13351 
13352   // If we are casting an integer type to a floating point type without
13353   // initialization-list syntax, we might lose accuracy if the floating
13354   // point type has a narrower significand than the integer type.
13355   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13356       TargetBT->isFloatingType() && !IsListInit) {
13357     // Determine the number of precision bits in the source integer type.
13358     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
13359                                         /*Approximate*/ true);
13360     unsigned int SourcePrecision = SourceRange.Width;
13361 
13362     // Determine the number of precision bits in the
13363     // target floating point type.
13364     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13365         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13366 
13367     if (SourcePrecision > 0 && TargetPrecision > 0 &&
13368         SourcePrecision > TargetPrecision) {
13369 
13370       if (Optional<llvm::APSInt> SourceInt =
13371               E->getIntegerConstantExpr(S.Context)) {
13372         // If the source integer is a constant, convert it to the target
13373         // floating point type. Issue a warning if the value changes
13374         // during the whole conversion.
13375         llvm::APFloat TargetFloatValue(
13376             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13377         llvm::APFloat::opStatus ConversionStatus =
13378             TargetFloatValue.convertFromAPInt(
13379                 *SourceInt, SourceBT->isSignedInteger(),
13380                 llvm::APFloat::rmNearestTiesToEven);
13381 
13382         if (ConversionStatus != llvm::APFloat::opOK) {
13383           SmallString<32> PrettySourceValue;
13384           SourceInt->toString(PrettySourceValue, 10);
13385           SmallString<32> PrettyTargetValue;
13386           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13387 
13388           S.DiagRuntimeBehavior(
13389               E->getExprLoc(), E,
13390               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
13391                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
13392                   << E->getSourceRange() << clang::SourceRange(CC));
13393         }
13394       } else {
13395         // Otherwise, the implicit conversion may lose precision.
13396         DiagnoseImpCast(S, E, T, CC,
13397                         diag::warn_impcast_integer_float_precision);
13398       }
13399     }
13400   }
13401 
13402   DiagnoseNullConversion(S, E, T, CC);
13403 
13404   S.DiscardMisalignedMemberAddress(Target, E);
13405 
13406   if (Target->isBooleanType())
13407     DiagnoseIntInBoolContext(S, E);
13408 
13409   if (!Source->isIntegerType() || !Target->isIntegerType())
13410     return;
13411 
13412   // TODO: remove this early return once the false positives for constant->bool
13413   // in templates, macros, etc, are reduced or removed.
13414   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13415     return;
13416 
13417   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
13418       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13419     return adornObjCBoolConversionDiagWithTernaryFixit(
13420         S, E,
13421         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13422             << E->getType());
13423   }
13424 
13425   IntRange SourceTypeRange =
13426       IntRange::forTargetOfCanonicalType(S.Context, Source);
13427   IntRange LikelySourceRange =
13428       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
13429   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
13430 
13431   if (LikelySourceRange.Width > TargetRange.Width) {
13432     // If the source is a constant, use a default-on diagnostic.
13433     // TODO: this should happen for bitfield stores, too.
13434     Expr::EvalResult Result;
13435     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
13436                          S.isConstantEvaluated())) {
13437       llvm::APSInt Value(32);
13438       Value = Result.Val.getInt();
13439 
13440       if (S.SourceMgr.isInSystemMacro(CC))
13441         return;
13442 
13443       std::string PrettySourceValue = toString(Value, 10);
13444       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13445 
13446       S.DiagRuntimeBehavior(
13447           E->getExprLoc(), E,
13448           S.PDiag(diag::warn_impcast_integer_precision_constant)
13449               << PrettySourceValue << PrettyTargetValue << E->getType() << T
13450               << E->getSourceRange() << SourceRange(CC));
13451       return;
13452     }
13453 
13454     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13455     if (S.SourceMgr.isInSystemMacro(CC))
13456       return;
13457 
13458     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
13459       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
13460                              /* pruneControlFlow */ true);
13461     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
13462   }
13463 
13464   if (TargetRange.Width > SourceTypeRange.Width) {
13465     if (auto *UO = dyn_cast<UnaryOperator>(E))
13466       if (UO->getOpcode() == UO_Minus)
13467         if (Source->isUnsignedIntegerType()) {
13468           if (Target->isUnsignedIntegerType())
13469             return DiagnoseImpCast(S, E, T, CC,
13470                                    diag::warn_impcast_high_order_zero_bits);
13471           if (Target->isSignedIntegerType())
13472             return DiagnoseImpCast(S, E, T, CC,
13473                                    diag::warn_impcast_nonnegative_result);
13474         }
13475   }
13476 
13477   if (TargetRange.Width == LikelySourceRange.Width &&
13478       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13479       Source->isSignedIntegerType()) {
13480     // Warn when doing a signed to signed conversion, warn if the positive
13481     // source value is exactly the width of the target type, which will
13482     // cause a negative value to be stored.
13483 
13484     Expr::EvalResult Result;
13485     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
13486         !S.SourceMgr.isInSystemMacro(CC)) {
13487       llvm::APSInt Value = Result.Val.getInt();
13488       if (isSameWidthConstantConversion(S, E, T, CC)) {
13489         std::string PrettySourceValue = toString(Value, 10);
13490         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13491 
13492         S.DiagRuntimeBehavior(
13493             E->getExprLoc(), E,
13494             S.PDiag(diag::warn_impcast_integer_precision_constant)
13495                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13496                 << E->getSourceRange() << SourceRange(CC));
13497         return;
13498       }
13499     }
13500 
13501     // Fall through for non-constants to give a sign conversion warning.
13502   }
13503 
13504   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13505       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13506        LikelySourceRange.Width == TargetRange.Width)) {
13507     if (S.SourceMgr.isInSystemMacro(CC))
13508       return;
13509 
13510     unsigned DiagID = diag::warn_impcast_integer_sign;
13511 
13512     // Traditionally, gcc has warned about this under -Wsign-compare.
13513     // We also want to warn about it in -Wconversion.
13514     // So if -Wconversion is off, use a completely identical diagnostic
13515     // in the sign-compare group.
13516     // The conditional-checking code will
13517     if (ICContext) {
13518       DiagID = diag::warn_impcast_integer_sign_conditional;
13519       *ICContext = true;
13520     }
13521 
13522     return DiagnoseImpCast(S, E, T, CC, DiagID);
13523   }
13524 
13525   // Diagnose conversions between different enumeration types.
13526   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13527   // type, to give us better diagnostics.
13528   QualType SourceType = E->getType();
13529   if (!S.getLangOpts().CPlusPlus) {
13530     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13531       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13532         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13533         SourceType = S.Context.getTypeDeclType(Enum);
13534         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13535       }
13536   }
13537 
13538   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13539     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13540       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13541           TargetEnum->getDecl()->hasNameForLinkage() &&
13542           SourceEnum != TargetEnum) {
13543         if (S.SourceMgr.isInSystemMacro(CC))
13544           return;
13545 
13546         return DiagnoseImpCast(S, E, SourceType, T, CC,
13547                                diag::warn_impcast_different_enum_types);
13548       }
13549 }
13550 
13551 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13552                                      SourceLocation CC, QualType T);
13553 
13554 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13555                                     SourceLocation CC, bool &ICContext) {
13556   E = E->IgnoreParenImpCasts();
13557 
13558   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13559     return CheckConditionalOperator(S, CO, CC, T);
13560 
13561   AnalyzeImplicitConversions(S, E, CC);
13562   if (E->getType() != T)
13563     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13564 }
13565 
13566 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13567                                      SourceLocation CC, QualType T) {
13568   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13569 
13570   Expr *TrueExpr = E->getTrueExpr();
13571   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13572     TrueExpr = BCO->getCommon();
13573 
13574   bool Suspicious = false;
13575   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13576   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13577 
13578   if (T->isBooleanType())
13579     DiagnoseIntInBoolContext(S, E);
13580 
13581   // If -Wconversion would have warned about either of the candidates
13582   // for a signedness conversion to the context type...
13583   if (!Suspicious) return;
13584 
13585   // ...but it's currently ignored...
13586   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13587     return;
13588 
13589   // ...then check whether it would have warned about either of the
13590   // candidates for a signedness conversion to the condition type.
13591   if (E->getType() == T) return;
13592 
13593   Suspicious = false;
13594   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13595                           E->getType(), CC, &Suspicious);
13596   if (!Suspicious)
13597     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13598                             E->getType(), CC, &Suspicious);
13599 }
13600 
13601 /// Check conversion of given expression to boolean.
13602 /// Input argument E is a logical expression.
13603 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13604   if (S.getLangOpts().Bool)
13605     return;
13606   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13607     return;
13608   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13609 }
13610 
13611 namespace {
13612 struct AnalyzeImplicitConversionsWorkItem {
13613   Expr *E;
13614   SourceLocation CC;
13615   bool IsListInit;
13616 };
13617 }
13618 
13619 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13620 /// that should be visited are added to WorkList.
13621 static void AnalyzeImplicitConversions(
13622     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13623     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13624   Expr *OrigE = Item.E;
13625   SourceLocation CC = Item.CC;
13626 
13627   QualType T = OrigE->getType();
13628   Expr *E = OrigE->IgnoreParenImpCasts();
13629 
13630   // Propagate whether we are in a C++ list initialization expression.
13631   // If so, we do not issue warnings for implicit int-float conversion
13632   // precision loss, because C++11 narrowing already handles it.
13633   bool IsListInit = Item.IsListInit ||
13634                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13635 
13636   if (E->isTypeDependent() || E->isValueDependent())
13637     return;
13638 
13639   Expr *SourceExpr = E;
13640   // Examine, but don't traverse into the source expression of an
13641   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13642   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13643   // evaluate it in the context of checking the specific conversion to T though.
13644   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13645     if (auto *Src = OVE->getSourceExpr())
13646       SourceExpr = Src;
13647 
13648   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13649     if (UO->getOpcode() == UO_Not &&
13650         UO->getSubExpr()->isKnownToHaveBooleanValue())
13651       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13652           << OrigE->getSourceRange() << T->isBooleanType()
13653           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13654 
13655   if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
13656     if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13657         BO->getLHS()->isKnownToHaveBooleanValue() &&
13658         BO->getRHS()->isKnownToHaveBooleanValue() &&
13659         BO->getLHS()->HasSideEffects(S.Context) &&
13660         BO->getRHS()->HasSideEffects(S.Context)) {
13661       S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13662           << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange()
13663           << FixItHint::CreateReplacement(
13664                  BO->getOperatorLoc(),
13665                  (BO->getOpcode() == BO_And ? "&&" : "||"));
13666       S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13667     }
13668 
13669   // For conditional operators, we analyze the arguments as if they
13670   // were being fed directly into the output.
13671   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13672     CheckConditionalOperator(S, CO, CC, T);
13673     return;
13674   }
13675 
13676   // Check implicit argument conversions for function calls.
13677   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13678     CheckImplicitArgumentConversions(S, Call, CC);
13679 
13680   // Go ahead and check any implicit conversions we might have skipped.
13681   // The non-canonical typecheck is just an optimization;
13682   // CheckImplicitConversion will filter out dead implicit conversions.
13683   if (SourceExpr->getType() != T)
13684     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13685 
13686   // Now continue drilling into this expression.
13687 
13688   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13689     // The bound subexpressions in a PseudoObjectExpr are not reachable
13690     // as transitive children.
13691     // FIXME: Use a more uniform representation for this.
13692     for (auto *SE : POE->semantics())
13693       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13694         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13695   }
13696 
13697   // Skip past explicit casts.
13698   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13699     E = CE->getSubExpr()->IgnoreParenImpCasts();
13700     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13701       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13702     WorkList.push_back({E, CC, IsListInit});
13703     return;
13704   }
13705 
13706   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13707     // Do a somewhat different check with comparison operators.
13708     if (BO->isComparisonOp())
13709       return AnalyzeComparison(S, BO);
13710 
13711     // And with simple assignments.
13712     if (BO->getOpcode() == BO_Assign)
13713       return AnalyzeAssignment(S, BO);
13714     // And with compound assignments.
13715     if (BO->isAssignmentOp())
13716       return AnalyzeCompoundAssignment(S, BO);
13717   }
13718 
13719   // These break the otherwise-useful invariant below.  Fortunately,
13720   // we don't really need to recurse into them, because any internal
13721   // expressions should have been analyzed already when they were
13722   // built into statements.
13723   if (isa<StmtExpr>(E)) return;
13724 
13725   // Don't descend into unevaluated contexts.
13726   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13727 
13728   // Now just recurse over the expression's children.
13729   CC = E->getExprLoc();
13730   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13731   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13732   for (Stmt *SubStmt : E->children()) {
13733     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13734     if (!ChildExpr)
13735       continue;
13736 
13737     if (IsLogicalAndOperator &&
13738         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13739       // Ignore checking string literals that are in logical and operators.
13740       // This is a common pattern for asserts.
13741       continue;
13742     WorkList.push_back({ChildExpr, CC, IsListInit});
13743   }
13744 
13745   if (BO && BO->isLogicalOp()) {
13746     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13747     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13748       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13749 
13750     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13751     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13752       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13753   }
13754 
13755   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13756     if (U->getOpcode() == UO_LNot) {
13757       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13758     } else if (U->getOpcode() != UO_AddrOf) {
13759       if (U->getSubExpr()->getType()->isAtomicType())
13760         S.Diag(U->getSubExpr()->getBeginLoc(),
13761                diag::warn_atomic_implicit_seq_cst);
13762     }
13763   }
13764 }
13765 
13766 /// AnalyzeImplicitConversions - Find and report any interesting
13767 /// implicit conversions in the given expression.  There are a couple
13768 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13769 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13770                                        bool IsListInit/*= false*/) {
13771   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13772   WorkList.push_back({OrigE, CC, IsListInit});
13773   while (!WorkList.empty())
13774     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13775 }
13776 
13777 /// Diagnose integer type and any valid implicit conversion to it.
13778 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13779   // Taking into account implicit conversions,
13780   // allow any integer.
13781   if (!E->getType()->isIntegerType()) {
13782     S.Diag(E->getBeginLoc(),
13783            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13784     return true;
13785   }
13786   // Potentially emit standard warnings for implicit conversions if enabled
13787   // using -Wconversion.
13788   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13789   return false;
13790 }
13791 
13792 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13793 // Returns true when emitting a warning about taking the address of a reference.
13794 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13795                               const PartialDiagnostic &PD) {
13796   E = E->IgnoreParenImpCasts();
13797 
13798   const FunctionDecl *FD = nullptr;
13799 
13800   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13801     if (!DRE->getDecl()->getType()->isReferenceType())
13802       return false;
13803   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13804     if (!M->getMemberDecl()->getType()->isReferenceType())
13805       return false;
13806   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13807     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13808       return false;
13809     FD = Call->getDirectCallee();
13810   } else {
13811     return false;
13812   }
13813 
13814   SemaRef.Diag(E->getExprLoc(), PD);
13815 
13816   // If possible, point to location of function.
13817   if (FD) {
13818     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13819   }
13820 
13821   return true;
13822 }
13823 
13824 // Returns true if the SourceLocation is expanded from any macro body.
13825 // Returns false if the SourceLocation is invalid, is from not in a macro
13826 // expansion, or is from expanded from a top-level macro argument.
13827 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13828   if (Loc.isInvalid())
13829     return false;
13830 
13831   while (Loc.isMacroID()) {
13832     if (SM.isMacroBodyExpansion(Loc))
13833       return true;
13834     Loc = SM.getImmediateMacroCallerLoc(Loc);
13835   }
13836 
13837   return false;
13838 }
13839 
13840 /// Diagnose pointers that are always non-null.
13841 /// \param E the expression containing the pointer
13842 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13843 /// compared to a null pointer
13844 /// \param IsEqual True when the comparison is equal to a null pointer
13845 /// \param Range Extra SourceRange to highlight in the diagnostic
13846 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13847                                         Expr::NullPointerConstantKind NullKind,
13848                                         bool IsEqual, SourceRange Range) {
13849   if (!E)
13850     return;
13851 
13852   // Don't warn inside macros.
13853   if (E->getExprLoc().isMacroID()) {
13854     const SourceManager &SM = getSourceManager();
13855     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13856         IsInAnyMacroBody(SM, Range.getBegin()))
13857       return;
13858   }
13859   E = E->IgnoreImpCasts();
13860 
13861   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13862 
13863   if (isa<CXXThisExpr>(E)) {
13864     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13865                                 : diag::warn_this_bool_conversion;
13866     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13867     return;
13868   }
13869 
13870   bool IsAddressOf = false;
13871 
13872   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13873     if (UO->getOpcode() != UO_AddrOf)
13874       return;
13875     IsAddressOf = true;
13876     E = UO->getSubExpr();
13877   }
13878 
13879   if (IsAddressOf) {
13880     unsigned DiagID = IsCompare
13881                           ? diag::warn_address_of_reference_null_compare
13882                           : diag::warn_address_of_reference_bool_conversion;
13883     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13884                                          << IsEqual;
13885     if (CheckForReference(*this, E, PD)) {
13886       return;
13887     }
13888   }
13889 
13890   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13891     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13892     std::string Str;
13893     llvm::raw_string_ostream S(Str);
13894     E->printPretty(S, nullptr, getPrintingPolicy());
13895     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13896                                 : diag::warn_cast_nonnull_to_bool;
13897     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13898       << E->getSourceRange() << Range << IsEqual;
13899     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13900   };
13901 
13902   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13903   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13904     if (auto *Callee = Call->getDirectCallee()) {
13905       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13906         ComplainAboutNonnullParamOrCall(A);
13907         return;
13908       }
13909     }
13910   }
13911 
13912   // Expect to find a single Decl.  Skip anything more complicated.
13913   ValueDecl *D = nullptr;
13914   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13915     D = R->getDecl();
13916   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13917     D = M->getMemberDecl();
13918   }
13919 
13920   // Weak Decls can be null.
13921   if (!D || D->isWeak())
13922     return;
13923 
13924   // Check for parameter decl with nonnull attribute
13925   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13926     if (getCurFunction() &&
13927         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13928       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13929         ComplainAboutNonnullParamOrCall(A);
13930         return;
13931       }
13932 
13933       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13934         // Skip function template not specialized yet.
13935         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13936           return;
13937         auto ParamIter = llvm::find(FD->parameters(), PV);
13938         assert(ParamIter != FD->param_end());
13939         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13940 
13941         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13942           if (!NonNull->args_size()) {
13943               ComplainAboutNonnullParamOrCall(NonNull);
13944               return;
13945           }
13946 
13947           for (const ParamIdx &ArgNo : NonNull->args()) {
13948             if (ArgNo.getASTIndex() == ParamNo) {
13949               ComplainAboutNonnullParamOrCall(NonNull);
13950               return;
13951             }
13952           }
13953         }
13954       }
13955     }
13956   }
13957 
13958   QualType T = D->getType();
13959   const bool IsArray = T->isArrayType();
13960   const bool IsFunction = T->isFunctionType();
13961 
13962   // Address of function is used to silence the function warning.
13963   if (IsAddressOf && IsFunction) {
13964     return;
13965   }
13966 
13967   // Found nothing.
13968   if (!IsAddressOf && !IsFunction && !IsArray)
13969     return;
13970 
13971   // Pretty print the expression for the diagnostic.
13972   std::string Str;
13973   llvm::raw_string_ostream S(Str);
13974   E->printPretty(S, nullptr, getPrintingPolicy());
13975 
13976   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13977                               : diag::warn_impcast_pointer_to_bool;
13978   enum {
13979     AddressOf,
13980     FunctionPointer,
13981     ArrayPointer
13982   } DiagType;
13983   if (IsAddressOf)
13984     DiagType = AddressOf;
13985   else if (IsFunction)
13986     DiagType = FunctionPointer;
13987   else if (IsArray)
13988     DiagType = ArrayPointer;
13989   else
13990     llvm_unreachable("Could not determine diagnostic.");
13991   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13992                                 << Range << IsEqual;
13993 
13994   if (!IsFunction)
13995     return;
13996 
13997   // Suggest '&' to silence the function warning.
13998   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13999       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
14000 
14001   // Check to see if '()' fixit should be emitted.
14002   QualType ReturnType;
14003   UnresolvedSet<4> NonTemplateOverloads;
14004   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
14005   if (ReturnType.isNull())
14006     return;
14007 
14008   if (IsCompare) {
14009     // There are two cases here.  If there is null constant, the only suggest
14010     // for a pointer return type.  If the null is 0, then suggest if the return
14011     // type is a pointer or an integer type.
14012     if (!ReturnType->isPointerType()) {
14013       if (NullKind == Expr::NPCK_ZeroExpression ||
14014           NullKind == Expr::NPCK_ZeroLiteral) {
14015         if (!ReturnType->isIntegerType())
14016           return;
14017       } else {
14018         return;
14019       }
14020     }
14021   } else { // !IsCompare
14022     // For function to bool, only suggest if the function pointer has bool
14023     // return type.
14024     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
14025       return;
14026   }
14027   Diag(E->getExprLoc(), diag::note_function_to_function_call)
14028       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
14029 }
14030 
14031 /// Diagnoses "dangerous" implicit conversions within the given
14032 /// expression (which is a full expression).  Implements -Wconversion
14033 /// and -Wsign-compare.
14034 ///
14035 /// \param CC the "context" location of the implicit conversion, i.e.
14036 ///   the most location of the syntactic entity requiring the implicit
14037 ///   conversion
14038 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14039   // Don't diagnose in unevaluated contexts.
14040   if (isUnevaluatedContext())
14041     return;
14042 
14043   // Don't diagnose for value- or type-dependent expressions.
14044   if (E->isTypeDependent() || E->isValueDependent())
14045     return;
14046 
14047   // Check for array bounds violations in cases where the check isn't triggered
14048   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14049   // ArraySubscriptExpr is on the RHS of a variable initialization.
14050   CheckArrayAccess(E);
14051 
14052   // This is not the right CC for (e.g.) a variable initialization.
14053   AnalyzeImplicitConversions(*this, E, CC);
14054 }
14055 
14056 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
14057 /// Input argument E is a logical expression.
14058 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14059   ::CheckBoolLikeConversion(*this, E, CC);
14060 }
14061 
14062 /// Diagnose when expression is an integer constant expression and its evaluation
14063 /// results in integer overflow
14064 void Sema::CheckForIntOverflow (Expr *E) {
14065   // Use a work list to deal with nested struct initializers.
14066   SmallVector<Expr *, 2> Exprs(1, E);
14067 
14068   do {
14069     Expr *OriginalE = Exprs.pop_back_val();
14070     Expr *E = OriginalE->IgnoreParenCasts();
14071 
14072     if (isa<BinaryOperator>(E)) {
14073       E->EvaluateForOverflow(Context);
14074       continue;
14075     }
14076 
14077     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
14078       Exprs.append(InitList->inits().begin(), InitList->inits().end());
14079     else if (isa<ObjCBoxedExpr>(OriginalE))
14080       E->EvaluateForOverflow(Context);
14081     else if (auto Call = dyn_cast<CallExpr>(E))
14082       Exprs.append(Call->arg_begin(), Call->arg_end());
14083     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
14084       Exprs.append(Message->arg_begin(), Message->arg_end());
14085   } while (!Exprs.empty());
14086 }
14087 
14088 namespace {
14089 
14090 /// Visitor for expressions which looks for unsequenced operations on the
14091 /// same object.
14092 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14093   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14094 
14095   /// A tree of sequenced regions within an expression. Two regions are
14096   /// unsequenced if one is an ancestor or a descendent of the other. When we
14097   /// finish processing an expression with sequencing, such as a comma
14098   /// expression, we fold its tree nodes into its parent, since they are
14099   /// unsequenced with respect to nodes we will visit later.
14100   class SequenceTree {
14101     struct Value {
14102       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14103       unsigned Parent : 31;
14104       unsigned Merged : 1;
14105     };
14106     SmallVector<Value, 8> Values;
14107 
14108   public:
14109     /// A region within an expression which may be sequenced with respect
14110     /// to some other region.
14111     class Seq {
14112       friend class SequenceTree;
14113 
14114       unsigned Index;
14115 
14116       explicit Seq(unsigned N) : Index(N) {}
14117 
14118     public:
14119       Seq() : Index(0) {}
14120     };
14121 
14122     SequenceTree() { Values.push_back(Value(0)); }
14123     Seq root() const { return Seq(0); }
14124 
14125     /// Create a new sequence of operations, which is an unsequenced
14126     /// subset of \p Parent. This sequence of operations is sequenced with
14127     /// respect to other children of \p Parent.
14128     Seq allocate(Seq Parent) {
14129       Values.push_back(Value(Parent.Index));
14130       return Seq(Values.size() - 1);
14131     }
14132 
14133     /// Merge a sequence of operations into its parent.
14134     void merge(Seq S) {
14135       Values[S.Index].Merged = true;
14136     }
14137 
14138     /// Determine whether two operations are unsequenced. This operation
14139     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14140     /// should have been merged into its parent as appropriate.
14141     bool isUnsequenced(Seq Cur, Seq Old) {
14142       unsigned C = representative(Cur.Index);
14143       unsigned Target = representative(Old.Index);
14144       while (C >= Target) {
14145         if (C == Target)
14146           return true;
14147         C = Values[C].Parent;
14148       }
14149       return false;
14150     }
14151 
14152   private:
14153     /// Pick a representative for a sequence.
14154     unsigned representative(unsigned K) {
14155       if (Values[K].Merged)
14156         // Perform path compression as we go.
14157         return Values[K].Parent = representative(Values[K].Parent);
14158       return K;
14159     }
14160   };
14161 
14162   /// An object for which we can track unsequenced uses.
14163   using Object = const NamedDecl *;
14164 
14165   /// Different flavors of object usage which we track. We only track the
14166   /// least-sequenced usage of each kind.
14167   enum UsageKind {
14168     /// A read of an object. Multiple unsequenced reads are OK.
14169     UK_Use,
14170 
14171     /// A modification of an object which is sequenced before the value
14172     /// computation of the expression, such as ++n in C++.
14173     UK_ModAsValue,
14174 
14175     /// A modification of an object which is not sequenced before the value
14176     /// computation of the expression, such as n++.
14177     UK_ModAsSideEffect,
14178 
14179     UK_Count = UK_ModAsSideEffect + 1
14180   };
14181 
14182   /// Bundle together a sequencing region and the expression corresponding
14183   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14184   struct Usage {
14185     const Expr *UsageExpr;
14186     SequenceTree::Seq Seq;
14187 
14188     Usage() : UsageExpr(nullptr) {}
14189   };
14190 
14191   struct UsageInfo {
14192     Usage Uses[UK_Count];
14193 
14194     /// Have we issued a diagnostic for this object already?
14195     bool Diagnosed;
14196 
14197     UsageInfo() : Diagnosed(false) {}
14198   };
14199   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14200 
14201   Sema &SemaRef;
14202 
14203   /// Sequenced regions within the expression.
14204   SequenceTree Tree;
14205 
14206   /// Declaration modifications and references which we have seen.
14207   UsageInfoMap UsageMap;
14208 
14209   /// The region we are currently within.
14210   SequenceTree::Seq Region;
14211 
14212   /// Filled in with declarations which were modified as a side-effect
14213   /// (that is, post-increment operations).
14214   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14215 
14216   /// Expressions to check later. We defer checking these to reduce
14217   /// stack usage.
14218   SmallVectorImpl<const Expr *> &WorkList;
14219 
14220   /// RAII object wrapping the visitation of a sequenced subexpression of an
14221   /// expression. At the end of this process, the side-effects of the evaluation
14222   /// become sequenced with respect to the value computation of the result, so
14223   /// we downgrade any UK_ModAsSideEffect within the evaluation to
14224   /// UK_ModAsValue.
14225   struct SequencedSubexpression {
14226     SequencedSubexpression(SequenceChecker &Self)
14227       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14228       Self.ModAsSideEffect = &ModAsSideEffect;
14229     }
14230 
14231     ~SequencedSubexpression() {
14232       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14233         // Add a new usage with usage kind UK_ModAsValue, and then restore
14234         // the previous usage with UK_ModAsSideEffect (thus clearing it if
14235         // the previous one was empty).
14236         UsageInfo &UI = Self.UsageMap[M.first];
14237         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14238         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14239         SideEffectUsage = M.second;
14240       }
14241       Self.ModAsSideEffect = OldModAsSideEffect;
14242     }
14243 
14244     SequenceChecker &Self;
14245     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14246     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14247   };
14248 
14249   /// RAII object wrapping the visitation of a subexpression which we might
14250   /// choose to evaluate as a constant. If any subexpression is evaluated and
14251   /// found to be non-constant, this allows us to suppress the evaluation of
14252   /// the outer expression.
14253   class EvaluationTracker {
14254   public:
14255     EvaluationTracker(SequenceChecker &Self)
14256         : Self(Self), Prev(Self.EvalTracker) {
14257       Self.EvalTracker = this;
14258     }
14259 
14260     ~EvaluationTracker() {
14261       Self.EvalTracker = Prev;
14262       if (Prev)
14263         Prev->EvalOK &= EvalOK;
14264     }
14265 
14266     bool evaluate(const Expr *E, bool &Result) {
14267       if (!EvalOK || E->isValueDependent())
14268         return false;
14269       EvalOK = E->EvaluateAsBooleanCondition(
14270           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
14271       return EvalOK;
14272     }
14273 
14274   private:
14275     SequenceChecker &Self;
14276     EvaluationTracker *Prev;
14277     bool EvalOK = true;
14278   } *EvalTracker = nullptr;
14279 
14280   /// Find the object which is produced by the specified expression,
14281   /// if any.
14282   Object getObject(const Expr *E, bool Mod) const {
14283     E = E->IgnoreParenCasts();
14284     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14285       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14286         return getObject(UO->getSubExpr(), Mod);
14287     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14288       if (BO->getOpcode() == BO_Comma)
14289         return getObject(BO->getRHS(), Mod);
14290       if (Mod && BO->isAssignmentOp())
14291         return getObject(BO->getLHS(), Mod);
14292     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14293       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14294       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14295         return ME->getMemberDecl();
14296     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14297       // FIXME: If this is a reference, map through to its value.
14298       return DRE->getDecl();
14299     return nullptr;
14300   }
14301 
14302   /// Note that an object \p O was modified or used by an expression
14303   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14304   /// the object \p O as obtained via the \p UsageMap.
14305   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14306     // Get the old usage for the given object and usage kind.
14307     Usage &U = UI.Uses[UK];
14308     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14309       // If we have a modification as side effect and are in a sequenced
14310       // subexpression, save the old Usage so that we can restore it later
14311       // in SequencedSubexpression::~SequencedSubexpression.
14312       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14313         ModAsSideEffect->push_back(std::make_pair(O, U));
14314       // Then record the new usage with the current sequencing region.
14315       U.UsageExpr = UsageExpr;
14316       U.Seq = Region;
14317     }
14318   }
14319 
14320   /// Check whether a modification or use of an object \p O in an expression
14321   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14322   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14323   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14324   /// usage and false we are checking for a mod-use unsequenced usage.
14325   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14326                   UsageKind OtherKind, bool IsModMod) {
14327     if (UI.Diagnosed)
14328       return;
14329 
14330     const Usage &U = UI.Uses[OtherKind];
14331     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14332       return;
14333 
14334     const Expr *Mod = U.UsageExpr;
14335     const Expr *ModOrUse = UsageExpr;
14336     if (OtherKind == UK_Use)
14337       std::swap(Mod, ModOrUse);
14338 
14339     SemaRef.DiagRuntimeBehavior(
14340         Mod->getExprLoc(), {Mod, ModOrUse},
14341         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14342                                : diag::warn_unsequenced_mod_use)
14343             << O << SourceRange(ModOrUse->getExprLoc()));
14344     UI.Diagnosed = true;
14345   }
14346 
14347   // A note on note{Pre, Post}{Use, Mod}:
14348   //
14349   // (It helps to follow the algorithm with an expression such as
14350   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14351   //  operations before C++17 and both are well-defined in C++17).
14352   //
14353   // When visiting a node which uses/modify an object we first call notePreUse
14354   // or notePreMod before visiting its sub-expression(s). At this point the
14355   // children of the current node have not yet been visited and so the eventual
14356   // uses/modifications resulting from the children of the current node have not
14357   // been recorded yet.
14358   //
14359   // We then visit the children of the current node. After that notePostUse or
14360   // notePostMod is called. These will 1) detect an unsequenced modification
14361   // as side effect (as in "k++ + k") and 2) add a new usage with the
14362   // appropriate usage kind.
14363   //
14364   // We also have to be careful that some operation sequences modification as
14365   // side effect as well (for example: || or ,). To account for this we wrap
14366   // the visitation of such a sub-expression (for example: the LHS of || or ,)
14367   // with SequencedSubexpression. SequencedSubexpression is an RAII object
14368   // which record usages which are modifications as side effect, and then
14369   // downgrade them (or more accurately restore the previous usage which was a
14370   // modification as side effect) when exiting the scope of the sequenced
14371   // subexpression.
14372 
14373   void notePreUse(Object O, const Expr *UseExpr) {
14374     UsageInfo &UI = UsageMap[O];
14375     // Uses conflict with other modifications.
14376     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14377   }
14378 
14379   void notePostUse(Object O, const Expr *UseExpr) {
14380     UsageInfo &UI = UsageMap[O];
14381     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14382                /*IsModMod=*/false);
14383     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14384   }
14385 
14386   void notePreMod(Object O, const Expr *ModExpr) {
14387     UsageInfo &UI = UsageMap[O];
14388     // Modifications conflict with other modifications and with uses.
14389     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14390     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14391   }
14392 
14393   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14394     UsageInfo &UI = UsageMap[O];
14395     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14396                /*IsModMod=*/true);
14397     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14398   }
14399 
14400 public:
14401   SequenceChecker(Sema &S, const Expr *E,
14402                   SmallVectorImpl<const Expr *> &WorkList)
14403       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14404     Visit(E);
14405     // Silence a -Wunused-private-field since WorkList is now unused.
14406     // TODO: Evaluate if it can be used, and if not remove it.
14407     (void)this->WorkList;
14408   }
14409 
14410   void VisitStmt(const Stmt *S) {
14411     // Skip all statements which aren't expressions for now.
14412   }
14413 
14414   void VisitExpr(const Expr *E) {
14415     // By default, just recurse to evaluated subexpressions.
14416     Base::VisitStmt(E);
14417   }
14418 
14419   void VisitCastExpr(const CastExpr *E) {
14420     Object O = Object();
14421     if (E->getCastKind() == CK_LValueToRValue)
14422       O = getObject(E->getSubExpr(), false);
14423 
14424     if (O)
14425       notePreUse(O, E);
14426     VisitExpr(E);
14427     if (O)
14428       notePostUse(O, E);
14429   }
14430 
14431   void VisitSequencedExpressions(const Expr *SequencedBefore,
14432                                  const Expr *SequencedAfter) {
14433     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14434     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14435     SequenceTree::Seq OldRegion = Region;
14436 
14437     {
14438       SequencedSubexpression SeqBefore(*this);
14439       Region = BeforeRegion;
14440       Visit(SequencedBefore);
14441     }
14442 
14443     Region = AfterRegion;
14444     Visit(SequencedAfter);
14445 
14446     Region = OldRegion;
14447 
14448     Tree.merge(BeforeRegion);
14449     Tree.merge(AfterRegion);
14450   }
14451 
14452   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14453     // C++17 [expr.sub]p1:
14454     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14455     //   expression E1 is sequenced before the expression E2.
14456     if (SemaRef.getLangOpts().CPlusPlus17)
14457       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14458     else {
14459       Visit(ASE->getLHS());
14460       Visit(ASE->getRHS());
14461     }
14462   }
14463 
14464   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14465   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14466   void VisitBinPtrMem(const BinaryOperator *BO) {
14467     // C++17 [expr.mptr.oper]p4:
14468     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14469     //  the expression E1 is sequenced before the expression E2.
14470     if (SemaRef.getLangOpts().CPlusPlus17)
14471       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14472     else {
14473       Visit(BO->getLHS());
14474       Visit(BO->getRHS());
14475     }
14476   }
14477 
14478   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14479   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14480   void VisitBinShlShr(const BinaryOperator *BO) {
14481     // C++17 [expr.shift]p4:
14482     //  The expression E1 is sequenced before the expression E2.
14483     if (SemaRef.getLangOpts().CPlusPlus17)
14484       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14485     else {
14486       Visit(BO->getLHS());
14487       Visit(BO->getRHS());
14488     }
14489   }
14490 
14491   void VisitBinComma(const BinaryOperator *BO) {
14492     // C++11 [expr.comma]p1:
14493     //   Every value computation and side effect associated with the left
14494     //   expression is sequenced before every value computation and side
14495     //   effect associated with the right expression.
14496     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14497   }
14498 
14499   void VisitBinAssign(const BinaryOperator *BO) {
14500     SequenceTree::Seq RHSRegion;
14501     SequenceTree::Seq LHSRegion;
14502     if (SemaRef.getLangOpts().CPlusPlus17) {
14503       RHSRegion = Tree.allocate(Region);
14504       LHSRegion = Tree.allocate(Region);
14505     } else {
14506       RHSRegion = Region;
14507       LHSRegion = Region;
14508     }
14509     SequenceTree::Seq OldRegion = Region;
14510 
14511     // C++11 [expr.ass]p1:
14512     //  [...] the assignment is sequenced after the value computation
14513     //  of the right and left operands, [...]
14514     //
14515     // so check it before inspecting the operands and update the
14516     // map afterwards.
14517     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14518     if (O)
14519       notePreMod(O, BO);
14520 
14521     if (SemaRef.getLangOpts().CPlusPlus17) {
14522       // C++17 [expr.ass]p1:
14523       //  [...] The right operand is sequenced before the left operand. [...]
14524       {
14525         SequencedSubexpression SeqBefore(*this);
14526         Region = RHSRegion;
14527         Visit(BO->getRHS());
14528       }
14529 
14530       Region = LHSRegion;
14531       Visit(BO->getLHS());
14532 
14533       if (O && isa<CompoundAssignOperator>(BO))
14534         notePostUse(O, BO);
14535 
14536     } else {
14537       // C++11 does not specify any sequencing between the LHS and RHS.
14538       Region = LHSRegion;
14539       Visit(BO->getLHS());
14540 
14541       if (O && isa<CompoundAssignOperator>(BO))
14542         notePostUse(O, BO);
14543 
14544       Region = RHSRegion;
14545       Visit(BO->getRHS());
14546     }
14547 
14548     // C++11 [expr.ass]p1:
14549     //  the assignment is sequenced [...] before the value computation of the
14550     //  assignment expression.
14551     // C11 6.5.16/3 has no such rule.
14552     Region = OldRegion;
14553     if (O)
14554       notePostMod(O, BO,
14555                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14556                                                   : UK_ModAsSideEffect);
14557     if (SemaRef.getLangOpts().CPlusPlus17) {
14558       Tree.merge(RHSRegion);
14559       Tree.merge(LHSRegion);
14560     }
14561   }
14562 
14563   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14564     VisitBinAssign(CAO);
14565   }
14566 
14567   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14568   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14569   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14570     Object O = getObject(UO->getSubExpr(), true);
14571     if (!O)
14572       return VisitExpr(UO);
14573 
14574     notePreMod(O, UO);
14575     Visit(UO->getSubExpr());
14576     // C++11 [expr.pre.incr]p1:
14577     //   the expression ++x is equivalent to x+=1
14578     notePostMod(O, UO,
14579                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14580                                                 : UK_ModAsSideEffect);
14581   }
14582 
14583   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14584   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14585   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14586     Object O = getObject(UO->getSubExpr(), true);
14587     if (!O)
14588       return VisitExpr(UO);
14589 
14590     notePreMod(O, UO);
14591     Visit(UO->getSubExpr());
14592     notePostMod(O, UO, UK_ModAsSideEffect);
14593   }
14594 
14595   void VisitBinLOr(const BinaryOperator *BO) {
14596     // C++11 [expr.log.or]p2:
14597     //  If the second expression is evaluated, every value computation and
14598     //  side effect associated with the first expression is sequenced before
14599     //  every value computation and side effect associated with the
14600     //  second expression.
14601     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14602     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14603     SequenceTree::Seq OldRegion = Region;
14604 
14605     EvaluationTracker Eval(*this);
14606     {
14607       SequencedSubexpression Sequenced(*this);
14608       Region = LHSRegion;
14609       Visit(BO->getLHS());
14610     }
14611 
14612     // C++11 [expr.log.or]p1:
14613     //  [...] the second operand is not evaluated if the first operand
14614     //  evaluates to true.
14615     bool EvalResult = false;
14616     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14617     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14618     if (ShouldVisitRHS) {
14619       Region = RHSRegion;
14620       Visit(BO->getRHS());
14621     }
14622 
14623     Region = OldRegion;
14624     Tree.merge(LHSRegion);
14625     Tree.merge(RHSRegion);
14626   }
14627 
14628   void VisitBinLAnd(const BinaryOperator *BO) {
14629     // C++11 [expr.log.and]p2:
14630     //  If the second expression is evaluated, every value computation and
14631     //  side effect associated with the first expression is sequenced before
14632     //  every value computation and side effect associated with the
14633     //  second expression.
14634     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14635     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14636     SequenceTree::Seq OldRegion = Region;
14637 
14638     EvaluationTracker Eval(*this);
14639     {
14640       SequencedSubexpression Sequenced(*this);
14641       Region = LHSRegion;
14642       Visit(BO->getLHS());
14643     }
14644 
14645     // C++11 [expr.log.and]p1:
14646     //  [...] the second operand is not evaluated if the first operand is false.
14647     bool EvalResult = false;
14648     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14649     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14650     if (ShouldVisitRHS) {
14651       Region = RHSRegion;
14652       Visit(BO->getRHS());
14653     }
14654 
14655     Region = OldRegion;
14656     Tree.merge(LHSRegion);
14657     Tree.merge(RHSRegion);
14658   }
14659 
14660   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14661     // C++11 [expr.cond]p1:
14662     //  [...] Every value computation and side effect associated with the first
14663     //  expression is sequenced before every value computation and side effect
14664     //  associated with the second or third expression.
14665     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14666 
14667     // No sequencing is specified between the true and false expression.
14668     // However since exactly one of both is going to be evaluated we can
14669     // consider them to be sequenced. This is needed to avoid warning on
14670     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14671     // both the true and false expressions because we can't evaluate x.
14672     // This will still allow us to detect an expression like (pre C++17)
14673     // "(x ? y += 1 : y += 2) = y".
14674     //
14675     // We don't wrap the visitation of the true and false expression with
14676     // SequencedSubexpression because we don't want to downgrade modifications
14677     // as side effect in the true and false expressions after the visition
14678     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14679     // not warn between the two "y++", but we should warn between the "y++"
14680     // and the "y".
14681     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14682     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14683     SequenceTree::Seq OldRegion = Region;
14684 
14685     EvaluationTracker Eval(*this);
14686     {
14687       SequencedSubexpression Sequenced(*this);
14688       Region = ConditionRegion;
14689       Visit(CO->getCond());
14690     }
14691 
14692     // C++11 [expr.cond]p1:
14693     // [...] The first expression is contextually converted to bool (Clause 4).
14694     // It is evaluated and if it is true, the result of the conditional
14695     // expression is the value of the second expression, otherwise that of the
14696     // third expression. Only one of the second and third expressions is
14697     // evaluated. [...]
14698     bool EvalResult = false;
14699     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14700     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14701     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14702     if (ShouldVisitTrueExpr) {
14703       Region = TrueRegion;
14704       Visit(CO->getTrueExpr());
14705     }
14706     if (ShouldVisitFalseExpr) {
14707       Region = FalseRegion;
14708       Visit(CO->getFalseExpr());
14709     }
14710 
14711     Region = OldRegion;
14712     Tree.merge(ConditionRegion);
14713     Tree.merge(TrueRegion);
14714     Tree.merge(FalseRegion);
14715   }
14716 
14717   void VisitCallExpr(const CallExpr *CE) {
14718     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14719 
14720     if (CE->isUnevaluatedBuiltinCall(Context))
14721       return;
14722 
14723     // C++11 [intro.execution]p15:
14724     //   When calling a function [...], every value computation and side effect
14725     //   associated with any argument expression, or with the postfix expression
14726     //   designating the called function, is sequenced before execution of every
14727     //   expression or statement in the body of the function [and thus before
14728     //   the value computation of its result].
14729     SequencedSubexpression Sequenced(*this);
14730     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14731       // C++17 [expr.call]p5
14732       //   The postfix-expression is sequenced before each expression in the
14733       //   expression-list and any default argument. [...]
14734       SequenceTree::Seq CalleeRegion;
14735       SequenceTree::Seq OtherRegion;
14736       if (SemaRef.getLangOpts().CPlusPlus17) {
14737         CalleeRegion = Tree.allocate(Region);
14738         OtherRegion = Tree.allocate(Region);
14739       } else {
14740         CalleeRegion = Region;
14741         OtherRegion = Region;
14742       }
14743       SequenceTree::Seq OldRegion = Region;
14744 
14745       // Visit the callee expression first.
14746       Region = CalleeRegion;
14747       if (SemaRef.getLangOpts().CPlusPlus17) {
14748         SequencedSubexpression Sequenced(*this);
14749         Visit(CE->getCallee());
14750       } else {
14751         Visit(CE->getCallee());
14752       }
14753 
14754       // Then visit the argument expressions.
14755       Region = OtherRegion;
14756       for (const Expr *Argument : CE->arguments())
14757         Visit(Argument);
14758 
14759       Region = OldRegion;
14760       if (SemaRef.getLangOpts().CPlusPlus17) {
14761         Tree.merge(CalleeRegion);
14762         Tree.merge(OtherRegion);
14763       }
14764     });
14765   }
14766 
14767   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14768     // C++17 [over.match.oper]p2:
14769     //   [...] the operator notation is first transformed to the equivalent
14770     //   function-call notation as summarized in Table 12 (where @ denotes one
14771     //   of the operators covered in the specified subclause). However, the
14772     //   operands are sequenced in the order prescribed for the built-in
14773     //   operator (Clause 8).
14774     //
14775     // From the above only overloaded binary operators and overloaded call
14776     // operators have sequencing rules in C++17 that we need to handle
14777     // separately.
14778     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14779         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14780       return VisitCallExpr(CXXOCE);
14781 
14782     enum {
14783       NoSequencing,
14784       LHSBeforeRHS,
14785       RHSBeforeLHS,
14786       LHSBeforeRest
14787     } SequencingKind;
14788     switch (CXXOCE->getOperator()) {
14789     case OO_Equal:
14790     case OO_PlusEqual:
14791     case OO_MinusEqual:
14792     case OO_StarEqual:
14793     case OO_SlashEqual:
14794     case OO_PercentEqual:
14795     case OO_CaretEqual:
14796     case OO_AmpEqual:
14797     case OO_PipeEqual:
14798     case OO_LessLessEqual:
14799     case OO_GreaterGreaterEqual:
14800       SequencingKind = RHSBeforeLHS;
14801       break;
14802 
14803     case OO_LessLess:
14804     case OO_GreaterGreater:
14805     case OO_AmpAmp:
14806     case OO_PipePipe:
14807     case OO_Comma:
14808     case OO_ArrowStar:
14809     case OO_Subscript:
14810       SequencingKind = LHSBeforeRHS;
14811       break;
14812 
14813     case OO_Call:
14814       SequencingKind = LHSBeforeRest;
14815       break;
14816 
14817     default:
14818       SequencingKind = NoSequencing;
14819       break;
14820     }
14821 
14822     if (SequencingKind == NoSequencing)
14823       return VisitCallExpr(CXXOCE);
14824 
14825     // This is a call, so all subexpressions are sequenced before the result.
14826     SequencedSubexpression Sequenced(*this);
14827 
14828     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14829       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14830              "Should only get there with C++17 and above!");
14831       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14832              "Should only get there with an overloaded binary operator"
14833              " or an overloaded call operator!");
14834 
14835       if (SequencingKind == LHSBeforeRest) {
14836         assert(CXXOCE->getOperator() == OO_Call &&
14837                "We should only have an overloaded call operator here!");
14838 
14839         // This is very similar to VisitCallExpr, except that we only have the
14840         // C++17 case. The postfix-expression is the first argument of the
14841         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14842         // are in the following arguments.
14843         //
14844         // Note that we intentionally do not visit the callee expression since
14845         // it is just a decayed reference to a function.
14846         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14847         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14848         SequenceTree::Seq OldRegion = Region;
14849 
14850         assert(CXXOCE->getNumArgs() >= 1 &&
14851                "An overloaded call operator must have at least one argument"
14852                " for the postfix-expression!");
14853         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14854         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14855                                           CXXOCE->getNumArgs() - 1);
14856 
14857         // Visit the postfix-expression first.
14858         {
14859           Region = PostfixExprRegion;
14860           SequencedSubexpression Sequenced(*this);
14861           Visit(PostfixExpr);
14862         }
14863 
14864         // Then visit the argument expressions.
14865         Region = ArgsRegion;
14866         for (const Expr *Arg : Args)
14867           Visit(Arg);
14868 
14869         Region = OldRegion;
14870         Tree.merge(PostfixExprRegion);
14871         Tree.merge(ArgsRegion);
14872       } else {
14873         assert(CXXOCE->getNumArgs() == 2 &&
14874                "Should only have two arguments here!");
14875         assert((SequencingKind == LHSBeforeRHS ||
14876                 SequencingKind == RHSBeforeLHS) &&
14877                "Unexpected sequencing kind!");
14878 
14879         // We do not visit the callee expression since it is just a decayed
14880         // reference to a function.
14881         const Expr *E1 = CXXOCE->getArg(0);
14882         const Expr *E2 = CXXOCE->getArg(1);
14883         if (SequencingKind == RHSBeforeLHS)
14884           std::swap(E1, E2);
14885 
14886         return VisitSequencedExpressions(E1, E2);
14887       }
14888     });
14889   }
14890 
14891   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14892     // This is a call, so all subexpressions are sequenced before the result.
14893     SequencedSubexpression Sequenced(*this);
14894 
14895     if (!CCE->isListInitialization())
14896       return VisitExpr(CCE);
14897 
14898     // In C++11, list initializations are sequenced.
14899     SmallVector<SequenceTree::Seq, 32> Elts;
14900     SequenceTree::Seq Parent = Region;
14901     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14902                                               E = CCE->arg_end();
14903          I != E; ++I) {
14904       Region = Tree.allocate(Parent);
14905       Elts.push_back(Region);
14906       Visit(*I);
14907     }
14908 
14909     // Forget that the initializers are sequenced.
14910     Region = Parent;
14911     for (unsigned I = 0; I < Elts.size(); ++I)
14912       Tree.merge(Elts[I]);
14913   }
14914 
14915   void VisitInitListExpr(const InitListExpr *ILE) {
14916     if (!SemaRef.getLangOpts().CPlusPlus11)
14917       return VisitExpr(ILE);
14918 
14919     // In C++11, list initializations are sequenced.
14920     SmallVector<SequenceTree::Seq, 32> Elts;
14921     SequenceTree::Seq Parent = Region;
14922     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14923       const Expr *E = ILE->getInit(I);
14924       if (!E)
14925         continue;
14926       Region = Tree.allocate(Parent);
14927       Elts.push_back(Region);
14928       Visit(E);
14929     }
14930 
14931     // Forget that the initializers are sequenced.
14932     Region = Parent;
14933     for (unsigned I = 0; I < Elts.size(); ++I)
14934       Tree.merge(Elts[I]);
14935   }
14936 };
14937 
14938 } // namespace
14939 
14940 void Sema::CheckUnsequencedOperations(const Expr *E) {
14941   SmallVector<const Expr *, 8> WorkList;
14942   WorkList.push_back(E);
14943   while (!WorkList.empty()) {
14944     const Expr *Item = WorkList.pop_back_val();
14945     SequenceChecker(*this, Item, WorkList);
14946   }
14947 }
14948 
14949 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14950                               bool IsConstexpr) {
14951   llvm::SaveAndRestore<bool> ConstantContext(
14952       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14953   CheckImplicitConversions(E, CheckLoc);
14954   if (!E->isInstantiationDependent())
14955     CheckUnsequencedOperations(E);
14956   if (!IsConstexpr && !E->isValueDependent())
14957     CheckForIntOverflow(E);
14958   DiagnoseMisalignedMembers();
14959 }
14960 
14961 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14962                                        FieldDecl *BitField,
14963                                        Expr *Init) {
14964   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14965 }
14966 
14967 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14968                                          SourceLocation Loc) {
14969   if (!PType->isVariablyModifiedType())
14970     return;
14971   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14972     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14973     return;
14974   }
14975   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14976     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14977     return;
14978   }
14979   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14980     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14981     return;
14982   }
14983 
14984   const ArrayType *AT = S.Context.getAsArrayType(PType);
14985   if (!AT)
14986     return;
14987 
14988   if (AT->getSizeModifier() != ArrayType::Star) {
14989     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14990     return;
14991   }
14992 
14993   S.Diag(Loc, diag::err_array_star_in_function_definition);
14994 }
14995 
14996 /// CheckParmsForFunctionDef - Check that the parameters of the given
14997 /// function are appropriate for the definition of a function. This
14998 /// takes care of any checks that cannot be performed on the
14999 /// declaration itself, e.g., that the types of each of the function
15000 /// parameters are complete.
15001 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
15002                                     bool CheckParameterNames) {
15003   bool HasInvalidParm = false;
15004   for (ParmVarDecl *Param : Parameters) {
15005     // C99 6.7.5.3p4: the parameters in a parameter type list in a
15006     // function declarator that is part of a function definition of
15007     // that function shall not have incomplete type.
15008     //
15009     // This is also C++ [dcl.fct]p6.
15010     if (!Param->isInvalidDecl() &&
15011         RequireCompleteType(Param->getLocation(), Param->getType(),
15012                             diag::err_typecheck_decl_incomplete_type)) {
15013       Param->setInvalidDecl();
15014       HasInvalidParm = true;
15015     }
15016 
15017     // C99 6.9.1p5: If the declarator includes a parameter type list, the
15018     // declaration of each parameter shall include an identifier.
15019     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15020         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15021       // Diagnose this as an extension in C17 and earlier.
15022       if (!getLangOpts().C2x)
15023         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15024     }
15025 
15026     // C99 6.7.5.3p12:
15027     //   If the function declarator is not part of a definition of that
15028     //   function, parameters may have incomplete type and may use the [*]
15029     //   notation in their sequences of declarator specifiers to specify
15030     //   variable length array types.
15031     QualType PType = Param->getOriginalType();
15032     // FIXME: This diagnostic should point the '[*]' if source-location
15033     // information is added for it.
15034     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
15035 
15036     // If the parameter is a c++ class type and it has to be destructed in the
15037     // callee function, declare the destructor so that it can be called by the
15038     // callee function. Do not perform any direct access check on the dtor here.
15039     if (!Param->isInvalidDecl()) {
15040       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15041         if (!ClassDecl->isInvalidDecl() &&
15042             !ClassDecl->hasIrrelevantDestructor() &&
15043             !ClassDecl->isDependentContext() &&
15044             ClassDecl->isParamDestroyedInCallee()) {
15045           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15046           MarkFunctionReferenced(Param->getLocation(), Destructor);
15047           DiagnoseUseOfDecl(Destructor, Param->getLocation());
15048         }
15049       }
15050     }
15051 
15052     // Parameters with the pass_object_size attribute only need to be marked
15053     // constant at function definitions. Because we lack information about
15054     // whether we're on a declaration or definition when we're instantiating the
15055     // attribute, we need to check for constness here.
15056     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15057       if (!Param->getType().isConstQualified())
15058         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
15059             << Attr->getSpelling() << 1;
15060 
15061     // Check for parameter names shadowing fields from the class.
15062     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15063       // The owning context for the parameter should be the function, but we
15064       // want to see if this function's declaration context is a record.
15065       DeclContext *DC = Param->getDeclContext();
15066       if (DC && DC->isFunctionOrMethod()) {
15067         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
15068           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
15069                                      RD, /*DeclIsField*/ false);
15070       }
15071     }
15072   }
15073 
15074   return HasInvalidParm;
15075 }
15076 
15077 Optional<std::pair<CharUnits, CharUnits>>
15078 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
15079 
15080 /// Compute the alignment and offset of the base class object given the
15081 /// derived-to-base cast expression and the alignment and offset of the derived
15082 /// class object.
15083 static std::pair<CharUnits, CharUnits>
15084 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
15085                                    CharUnits BaseAlignment, CharUnits Offset,
15086                                    ASTContext &Ctx) {
15087   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15088        ++PathI) {
15089     const CXXBaseSpecifier *Base = *PathI;
15090     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15091     if (Base->isVirtual()) {
15092       // The complete object may have a lower alignment than the non-virtual
15093       // alignment of the base, in which case the base may be misaligned. Choose
15094       // the smaller of the non-virtual alignment and BaseAlignment, which is a
15095       // conservative lower bound of the complete object alignment.
15096       CharUnits NonVirtualAlignment =
15097           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
15098       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15099       Offset = CharUnits::Zero();
15100     } else {
15101       const ASTRecordLayout &RL =
15102           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
15103       Offset += RL.getBaseClassOffset(BaseDecl);
15104     }
15105     DerivedType = Base->getType();
15106   }
15107 
15108   return std::make_pair(BaseAlignment, Offset);
15109 }
15110 
15111 /// Compute the alignment and offset of a binary additive operator.
15112 static Optional<std::pair<CharUnits, CharUnits>>
15113 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
15114                                      bool IsSub, ASTContext &Ctx) {
15115   QualType PointeeType = PtrE->getType()->getPointeeType();
15116 
15117   if (!PointeeType->isConstantSizeType())
15118     return llvm::None;
15119 
15120   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
15121 
15122   if (!P)
15123     return llvm::None;
15124 
15125   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
15126   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15127     CharUnits Offset = EltSize * IdxRes->getExtValue();
15128     if (IsSub)
15129       Offset = -Offset;
15130     return std::make_pair(P->first, P->second + Offset);
15131   }
15132 
15133   // If the integer expression isn't a constant expression, compute the lower
15134   // bound of the alignment using the alignment and offset of the pointer
15135   // expression and the element size.
15136   return std::make_pair(
15137       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15138       CharUnits::Zero());
15139 }
15140 
15141 /// This helper function takes an lvalue expression and returns the alignment of
15142 /// a VarDecl and a constant offset from the VarDecl.
15143 Optional<std::pair<CharUnits, CharUnits>>
15144 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
15145   E = E->IgnoreParens();
15146   switch (E->getStmtClass()) {
15147   default:
15148     break;
15149   case Stmt::CStyleCastExprClass:
15150   case Stmt::CXXStaticCastExprClass:
15151   case Stmt::ImplicitCastExprClass: {
15152     auto *CE = cast<CastExpr>(E);
15153     const Expr *From = CE->getSubExpr();
15154     switch (CE->getCastKind()) {
15155     default:
15156       break;
15157     case CK_NoOp:
15158       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15159     case CK_UncheckedDerivedToBase:
15160     case CK_DerivedToBase: {
15161       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15162       if (!P)
15163         break;
15164       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15165                                                 P->second, Ctx);
15166     }
15167     }
15168     break;
15169   }
15170   case Stmt::ArraySubscriptExprClass: {
15171     auto *ASE = cast<ArraySubscriptExpr>(E);
15172     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
15173                                                 false, Ctx);
15174   }
15175   case Stmt::DeclRefExprClass: {
15176     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15177       // FIXME: If VD is captured by copy or is an escaping __block variable,
15178       // use the alignment of VD's type.
15179       if (!VD->getType()->isReferenceType())
15180         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15181       if (VD->hasInit())
15182         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15183     }
15184     break;
15185   }
15186   case Stmt::MemberExprClass: {
15187     auto *ME = cast<MemberExpr>(E);
15188     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15189     if (!FD || FD->getType()->isReferenceType() ||
15190         FD->getParent()->isInvalidDecl())
15191       break;
15192     Optional<std::pair<CharUnits, CharUnits>> P;
15193     if (ME->isArrow())
15194       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15195     else
15196       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15197     if (!P)
15198       break;
15199     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15200     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15201     return std::make_pair(P->first,
15202                           P->second + CharUnits::fromQuantity(Offset));
15203   }
15204   case Stmt::UnaryOperatorClass: {
15205     auto *UO = cast<UnaryOperator>(E);
15206     switch (UO->getOpcode()) {
15207     default:
15208       break;
15209     case UO_Deref:
15210       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
15211     }
15212     break;
15213   }
15214   case Stmt::BinaryOperatorClass: {
15215     auto *BO = cast<BinaryOperator>(E);
15216     auto Opcode = BO->getOpcode();
15217     switch (Opcode) {
15218     default:
15219       break;
15220     case BO_Comma:
15221       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
15222     }
15223     break;
15224   }
15225   }
15226   return llvm::None;
15227 }
15228 
15229 /// This helper function takes a pointer expression and returns the alignment of
15230 /// a VarDecl and a constant offset from the VarDecl.
15231 Optional<std::pair<CharUnits, CharUnits>>
15232 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
15233   E = E->IgnoreParens();
15234   switch (E->getStmtClass()) {
15235   default:
15236     break;
15237   case Stmt::CStyleCastExprClass:
15238   case Stmt::CXXStaticCastExprClass:
15239   case Stmt::ImplicitCastExprClass: {
15240     auto *CE = cast<CastExpr>(E);
15241     const Expr *From = CE->getSubExpr();
15242     switch (CE->getCastKind()) {
15243     default:
15244       break;
15245     case CK_NoOp:
15246       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15247     case CK_ArrayToPointerDecay:
15248       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15249     case CK_UncheckedDerivedToBase:
15250     case CK_DerivedToBase: {
15251       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15252       if (!P)
15253         break;
15254       return getDerivedToBaseAlignmentAndOffset(
15255           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15256     }
15257     }
15258     break;
15259   }
15260   case Stmt::CXXThisExprClass: {
15261     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15262     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
15263     return std::make_pair(Alignment, CharUnits::Zero());
15264   }
15265   case Stmt::UnaryOperatorClass: {
15266     auto *UO = cast<UnaryOperator>(E);
15267     if (UO->getOpcode() == UO_AddrOf)
15268       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
15269     break;
15270   }
15271   case Stmt::BinaryOperatorClass: {
15272     auto *BO = cast<BinaryOperator>(E);
15273     auto Opcode = BO->getOpcode();
15274     switch (Opcode) {
15275     default:
15276       break;
15277     case BO_Add:
15278     case BO_Sub: {
15279       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15280       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15281         std::swap(LHS, RHS);
15282       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15283                                                   Ctx);
15284     }
15285     case BO_Comma:
15286       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15287     }
15288     break;
15289   }
15290   }
15291   return llvm::None;
15292 }
15293 
15294 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
15295   // See if we can compute the alignment of a VarDecl and an offset from it.
15296   Optional<std::pair<CharUnits, CharUnits>> P =
15297       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
15298 
15299   if (P)
15300     return P->first.alignmentAtOffset(P->second);
15301 
15302   // If that failed, return the type's alignment.
15303   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
15304 }
15305 
15306 /// CheckCastAlign - Implements -Wcast-align, which warns when a
15307 /// pointer cast increases the alignment requirements.
15308 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
15309   // This is actually a lot of work to potentially be doing on every
15310   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15311   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15312     return;
15313 
15314   // Ignore dependent types.
15315   if (T->isDependentType() || Op->getType()->isDependentType())
15316     return;
15317 
15318   // Require that the destination be a pointer type.
15319   const PointerType *DestPtr = T->getAs<PointerType>();
15320   if (!DestPtr) return;
15321 
15322   // If the destination has alignment 1, we're done.
15323   QualType DestPointee = DestPtr->getPointeeType();
15324   if (DestPointee->isIncompleteType()) return;
15325   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15326   if (DestAlign.isOne()) return;
15327 
15328   // Require that the source be a pointer type.
15329   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15330   if (!SrcPtr) return;
15331   QualType SrcPointee = SrcPtr->getPointeeType();
15332 
15333   // Explicitly allow casts from cv void*.  We already implicitly
15334   // allowed casts to cv void*, since they have alignment 1.
15335   // Also allow casts involving incomplete types, which implicitly
15336   // includes 'void'.
15337   if (SrcPointee->isIncompleteType()) return;
15338 
15339   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15340 
15341   if (SrcAlign >= DestAlign) return;
15342 
15343   Diag(TRange.getBegin(), diag::warn_cast_align)
15344     << Op->getType() << T
15345     << static_cast<unsigned>(SrcAlign.getQuantity())
15346     << static_cast<unsigned>(DestAlign.getQuantity())
15347     << TRange << Op->getSourceRange();
15348 }
15349 
15350 /// Check whether this array fits the idiom of a size-one tail padded
15351 /// array member of a struct.
15352 ///
15353 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
15354 /// commonly used to emulate flexible arrays in C89 code.
15355 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
15356                                     const NamedDecl *ND) {
15357   if (Size != 1 || !ND) return false;
15358 
15359   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
15360   if (!FD) return false;
15361 
15362   // Don't consider sizes resulting from macro expansions or template argument
15363   // substitution to form C89 tail-padded arrays.
15364 
15365   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
15366   while (TInfo) {
15367     TypeLoc TL = TInfo->getTypeLoc();
15368     // Look through typedefs.
15369     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
15370       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
15371       TInfo = TDL->getTypeSourceInfo();
15372       continue;
15373     }
15374     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
15375       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
15376       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
15377         return false;
15378     }
15379     break;
15380   }
15381 
15382   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
15383   if (!RD) return false;
15384   if (RD->isUnion()) return false;
15385   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15386     if (!CRD->isStandardLayout()) return false;
15387   }
15388 
15389   // See if this is the last field decl in the record.
15390   const Decl *D = FD;
15391   while ((D = D->getNextDeclInContext()))
15392     if (isa<FieldDecl>(D))
15393       return false;
15394   return true;
15395 }
15396 
15397 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15398                             const ArraySubscriptExpr *ASE,
15399                             bool AllowOnePastEnd, bool IndexNegated) {
15400   // Already diagnosed by the constant evaluator.
15401   if (isConstantEvaluated())
15402     return;
15403 
15404   IndexExpr = IndexExpr->IgnoreParenImpCasts();
15405   if (IndexExpr->isValueDependent())
15406     return;
15407 
15408   const Type *EffectiveType =
15409       BaseExpr->getType()->getPointeeOrArrayElementType();
15410   BaseExpr = BaseExpr->IgnoreParenCasts();
15411   const ConstantArrayType *ArrayTy =
15412       Context.getAsConstantArrayType(BaseExpr->getType());
15413 
15414   const Type *BaseType =
15415       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15416   bool IsUnboundedArray = (BaseType == nullptr);
15417   if (EffectiveType->isDependentType() ||
15418       (!IsUnboundedArray && BaseType->isDependentType()))
15419     return;
15420 
15421   Expr::EvalResult Result;
15422   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15423     return;
15424 
15425   llvm::APSInt index = Result.Val.getInt();
15426   if (IndexNegated) {
15427     index.setIsUnsigned(false);
15428     index = -index;
15429   }
15430 
15431   const NamedDecl *ND = nullptr;
15432   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15433     ND = DRE->getDecl();
15434   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
15435     ND = ME->getMemberDecl();
15436 
15437   if (IsUnboundedArray) {
15438     if (index.isUnsigned() || !index.isNegative()) {
15439       const auto &ASTC = getASTContext();
15440       unsigned AddrBits =
15441           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
15442               EffectiveType->getCanonicalTypeInternal()));
15443       if (index.getBitWidth() < AddrBits)
15444         index = index.zext(AddrBits);
15445       Optional<CharUnits> ElemCharUnits =
15446           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15447       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15448       // pointer) bounds-checking isn't meaningful.
15449       if (!ElemCharUnits)
15450         return;
15451       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15452       // If index has more active bits than address space, we already know
15453       // we have a bounds violation to warn about.  Otherwise, compute
15454       // address of (index + 1)th element, and warn about bounds violation
15455       // only if that address exceeds address space.
15456       if (index.getActiveBits() <= AddrBits) {
15457         bool Overflow;
15458         llvm::APInt Product(index);
15459         Product += 1;
15460         Product = Product.umul_ov(ElemBytes, Overflow);
15461         if (!Overflow && Product.getActiveBits() <= AddrBits)
15462           return;
15463       }
15464 
15465       // Need to compute max possible elements in address space, since that
15466       // is included in diag message.
15467       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15468       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15469       MaxElems += 1;
15470       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15471       MaxElems = MaxElems.udiv(ElemBytes);
15472 
15473       unsigned DiagID =
15474           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15475               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15476 
15477       // Diag message shows element size in bits and in "bytes" (platform-
15478       // dependent CharUnits)
15479       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15480                           PDiag(DiagID)
15481                               << toString(index, 10, true) << AddrBits
15482                               << (unsigned)ASTC.toBits(*ElemCharUnits)
15483                               << toString(ElemBytes, 10, false)
15484                               << toString(MaxElems, 10, false)
15485                               << (unsigned)MaxElems.getLimitedValue(~0U)
15486                               << IndexExpr->getSourceRange());
15487 
15488       if (!ND) {
15489         // Try harder to find a NamedDecl to point at in the note.
15490         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15491           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15492         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15493           ND = DRE->getDecl();
15494         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15495           ND = ME->getMemberDecl();
15496       }
15497 
15498       if (ND)
15499         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15500                             PDiag(diag::note_array_declared_here) << ND);
15501     }
15502     return;
15503   }
15504 
15505   if (index.isUnsigned() || !index.isNegative()) {
15506     // It is possible that the type of the base expression after
15507     // IgnoreParenCasts is incomplete, even though the type of the base
15508     // expression before IgnoreParenCasts is complete (see PR39746 for an
15509     // example). In this case we have no information about whether the array
15510     // access exceeds the array bounds. However we can still diagnose an array
15511     // access which precedes the array bounds.
15512     if (BaseType->isIncompleteType())
15513       return;
15514 
15515     llvm::APInt size = ArrayTy->getSize();
15516     if (!size.isStrictlyPositive())
15517       return;
15518 
15519     if (BaseType != EffectiveType) {
15520       // Make sure we're comparing apples to apples when comparing index to size
15521       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15522       uint64_t array_typesize = Context.getTypeSize(BaseType);
15523       // Handle ptrarith_typesize being zero, such as when casting to void*
15524       if (!ptrarith_typesize) ptrarith_typesize = 1;
15525       if (ptrarith_typesize != array_typesize) {
15526         // There's a cast to a different size type involved
15527         uint64_t ratio = array_typesize / ptrarith_typesize;
15528         // TODO: Be smarter about handling cases where array_typesize is not a
15529         // multiple of ptrarith_typesize
15530         if (ptrarith_typesize * ratio == array_typesize)
15531           size *= llvm::APInt(size.getBitWidth(), ratio);
15532       }
15533     }
15534 
15535     if (size.getBitWidth() > index.getBitWidth())
15536       index = index.zext(size.getBitWidth());
15537     else if (size.getBitWidth() < index.getBitWidth())
15538       size = size.zext(index.getBitWidth());
15539 
15540     // For array subscripting the index must be less than size, but for pointer
15541     // arithmetic also allow the index (offset) to be equal to size since
15542     // computing the next address after the end of the array is legal and
15543     // commonly done e.g. in C++ iterators and range-based for loops.
15544     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15545       return;
15546 
15547     // Also don't warn for arrays of size 1 which are members of some
15548     // structure. These are often used to approximate flexible arrays in C89
15549     // code.
15550     if (IsTailPaddedMemberArray(*this, size, ND))
15551       return;
15552 
15553     // Suppress the warning if the subscript expression (as identified by the
15554     // ']' location) and the index expression are both from macro expansions
15555     // within a system header.
15556     if (ASE) {
15557       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15558           ASE->getRBracketLoc());
15559       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15560         SourceLocation IndexLoc =
15561             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15562         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15563           return;
15564       }
15565     }
15566 
15567     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15568                           : diag::warn_ptr_arith_exceeds_bounds;
15569 
15570     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15571                         PDiag(DiagID) << toString(index, 10, true)
15572                                       << toString(size, 10, true)
15573                                       << (unsigned)size.getLimitedValue(~0U)
15574                                       << IndexExpr->getSourceRange());
15575   } else {
15576     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15577     if (!ASE) {
15578       DiagID = diag::warn_ptr_arith_precedes_bounds;
15579       if (index.isNegative()) index = -index;
15580     }
15581 
15582     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15583                         PDiag(DiagID) << toString(index, 10, true)
15584                                       << IndexExpr->getSourceRange());
15585   }
15586 
15587   if (!ND) {
15588     // Try harder to find a NamedDecl to point at in the note.
15589     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15590       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15591     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15592       ND = DRE->getDecl();
15593     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15594       ND = ME->getMemberDecl();
15595   }
15596 
15597   if (ND)
15598     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15599                         PDiag(diag::note_array_declared_here) << ND);
15600 }
15601 
15602 void Sema::CheckArrayAccess(const Expr *expr) {
15603   int AllowOnePastEnd = 0;
15604   while (expr) {
15605     expr = expr->IgnoreParenImpCasts();
15606     switch (expr->getStmtClass()) {
15607       case Stmt::ArraySubscriptExprClass: {
15608         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15609         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15610                          AllowOnePastEnd > 0);
15611         expr = ASE->getBase();
15612         break;
15613       }
15614       case Stmt::MemberExprClass: {
15615         expr = cast<MemberExpr>(expr)->getBase();
15616         break;
15617       }
15618       case Stmt::OMPArraySectionExprClass: {
15619         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15620         if (ASE->getLowerBound())
15621           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15622                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15623         return;
15624       }
15625       case Stmt::UnaryOperatorClass: {
15626         // Only unwrap the * and & unary operators
15627         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15628         expr = UO->getSubExpr();
15629         switch (UO->getOpcode()) {
15630           case UO_AddrOf:
15631             AllowOnePastEnd++;
15632             break;
15633           case UO_Deref:
15634             AllowOnePastEnd--;
15635             break;
15636           default:
15637             return;
15638         }
15639         break;
15640       }
15641       case Stmt::ConditionalOperatorClass: {
15642         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15643         if (const Expr *lhs = cond->getLHS())
15644           CheckArrayAccess(lhs);
15645         if (const Expr *rhs = cond->getRHS())
15646           CheckArrayAccess(rhs);
15647         return;
15648       }
15649       case Stmt::CXXOperatorCallExprClass: {
15650         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15651         for (const auto *Arg : OCE->arguments())
15652           CheckArrayAccess(Arg);
15653         return;
15654       }
15655       default:
15656         return;
15657     }
15658   }
15659 }
15660 
15661 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15662 
15663 namespace {
15664 
15665 struct RetainCycleOwner {
15666   VarDecl *Variable = nullptr;
15667   SourceRange Range;
15668   SourceLocation Loc;
15669   bool Indirect = false;
15670 
15671   RetainCycleOwner() = default;
15672 
15673   void setLocsFrom(Expr *e) {
15674     Loc = e->getExprLoc();
15675     Range = e->getSourceRange();
15676   }
15677 };
15678 
15679 } // namespace
15680 
15681 /// Consider whether capturing the given variable can possibly lead to
15682 /// a retain cycle.
15683 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15684   // In ARC, it's captured strongly iff the variable has __strong
15685   // lifetime.  In MRR, it's captured strongly if the variable is
15686   // __block and has an appropriate type.
15687   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15688     return false;
15689 
15690   owner.Variable = var;
15691   if (ref)
15692     owner.setLocsFrom(ref);
15693   return true;
15694 }
15695 
15696 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15697   while (true) {
15698     e = e->IgnoreParens();
15699     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15700       switch (cast->getCastKind()) {
15701       case CK_BitCast:
15702       case CK_LValueBitCast:
15703       case CK_LValueToRValue:
15704       case CK_ARCReclaimReturnedObject:
15705         e = cast->getSubExpr();
15706         continue;
15707 
15708       default:
15709         return false;
15710       }
15711     }
15712 
15713     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15714       ObjCIvarDecl *ivar = ref->getDecl();
15715       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15716         return false;
15717 
15718       // Try to find a retain cycle in the base.
15719       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15720         return false;
15721 
15722       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15723       owner.Indirect = true;
15724       return true;
15725     }
15726 
15727     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15728       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15729       if (!var) return false;
15730       return considerVariable(var, ref, owner);
15731     }
15732 
15733     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15734       if (member->isArrow()) return false;
15735 
15736       // Don't count this as an indirect ownership.
15737       e = member->getBase();
15738       continue;
15739     }
15740 
15741     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15742       // Only pay attention to pseudo-objects on property references.
15743       ObjCPropertyRefExpr *pre
15744         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15745                                               ->IgnoreParens());
15746       if (!pre) return false;
15747       if (pre->isImplicitProperty()) return false;
15748       ObjCPropertyDecl *property = pre->getExplicitProperty();
15749       if (!property->isRetaining() &&
15750           !(property->getPropertyIvarDecl() &&
15751             property->getPropertyIvarDecl()->getType()
15752               .getObjCLifetime() == Qualifiers::OCL_Strong))
15753           return false;
15754 
15755       owner.Indirect = true;
15756       if (pre->isSuperReceiver()) {
15757         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15758         if (!owner.Variable)
15759           return false;
15760         owner.Loc = pre->getLocation();
15761         owner.Range = pre->getSourceRange();
15762         return true;
15763       }
15764       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15765                               ->getSourceExpr());
15766       continue;
15767     }
15768 
15769     // Array ivars?
15770 
15771     return false;
15772   }
15773 }
15774 
15775 namespace {
15776 
15777   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15778     ASTContext &Context;
15779     VarDecl *Variable;
15780     Expr *Capturer = nullptr;
15781     bool VarWillBeReased = false;
15782 
15783     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15784         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15785           Context(Context), Variable(variable) {}
15786 
15787     void VisitDeclRefExpr(DeclRefExpr *ref) {
15788       if (ref->getDecl() == Variable && !Capturer)
15789         Capturer = ref;
15790     }
15791 
15792     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15793       if (Capturer) return;
15794       Visit(ref->getBase());
15795       if (Capturer && ref->isFreeIvar())
15796         Capturer = ref;
15797     }
15798 
15799     void VisitBlockExpr(BlockExpr *block) {
15800       // Look inside nested blocks
15801       if (block->getBlockDecl()->capturesVariable(Variable))
15802         Visit(block->getBlockDecl()->getBody());
15803     }
15804 
15805     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15806       if (Capturer) return;
15807       if (OVE->getSourceExpr())
15808         Visit(OVE->getSourceExpr());
15809     }
15810 
15811     void VisitBinaryOperator(BinaryOperator *BinOp) {
15812       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15813         return;
15814       Expr *LHS = BinOp->getLHS();
15815       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15816         if (DRE->getDecl() != Variable)
15817           return;
15818         if (Expr *RHS = BinOp->getRHS()) {
15819           RHS = RHS->IgnoreParenCasts();
15820           Optional<llvm::APSInt> Value;
15821           VarWillBeReased =
15822               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15823                *Value == 0);
15824         }
15825       }
15826     }
15827   };
15828 
15829 } // namespace
15830 
15831 /// Check whether the given argument is a block which captures a
15832 /// variable.
15833 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15834   assert(owner.Variable && owner.Loc.isValid());
15835 
15836   e = e->IgnoreParenCasts();
15837 
15838   // Look through [^{...} copy] and Block_copy(^{...}).
15839   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15840     Selector Cmd = ME->getSelector();
15841     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15842       e = ME->getInstanceReceiver();
15843       if (!e)
15844         return nullptr;
15845       e = e->IgnoreParenCasts();
15846     }
15847   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15848     if (CE->getNumArgs() == 1) {
15849       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15850       if (Fn) {
15851         const IdentifierInfo *FnI = Fn->getIdentifier();
15852         if (FnI && FnI->isStr("_Block_copy")) {
15853           e = CE->getArg(0)->IgnoreParenCasts();
15854         }
15855       }
15856     }
15857   }
15858 
15859   BlockExpr *block = dyn_cast<BlockExpr>(e);
15860   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15861     return nullptr;
15862 
15863   FindCaptureVisitor visitor(S.Context, owner.Variable);
15864   visitor.Visit(block->getBlockDecl()->getBody());
15865   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15866 }
15867 
15868 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15869                                 RetainCycleOwner &owner) {
15870   assert(capturer);
15871   assert(owner.Variable && owner.Loc.isValid());
15872 
15873   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15874     << owner.Variable << capturer->getSourceRange();
15875   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15876     << owner.Indirect << owner.Range;
15877 }
15878 
15879 /// Check for a keyword selector that starts with the word 'add' or
15880 /// 'set'.
15881 static bool isSetterLikeSelector(Selector sel) {
15882   if (sel.isUnarySelector()) return false;
15883 
15884   StringRef str = sel.getNameForSlot(0);
15885   while (!str.empty() && str.front() == '_') str = str.substr(1);
15886   if (str.startswith("set"))
15887     str = str.substr(3);
15888   else if (str.startswith("add")) {
15889     // Specially allow 'addOperationWithBlock:'.
15890     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15891       return false;
15892     str = str.substr(3);
15893   }
15894   else
15895     return false;
15896 
15897   if (str.empty()) return true;
15898   return !isLowercase(str.front());
15899 }
15900 
15901 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15902                                                     ObjCMessageExpr *Message) {
15903   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15904                                                 Message->getReceiverInterface(),
15905                                                 NSAPI::ClassId_NSMutableArray);
15906   if (!IsMutableArray) {
15907     return None;
15908   }
15909 
15910   Selector Sel = Message->getSelector();
15911 
15912   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15913     S.NSAPIObj->getNSArrayMethodKind(Sel);
15914   if (!MKOpt) {
15915     return None;
15916   }
15917 
15918   NSAPI::NSArrayMethodKind MK = *MKOpt;
15919 
15920   switch (MK) {
15921     case NSAPI::NSMutableArr_addObject:
15922     case NSAPI::NSMutableArr_insertObjectAtIndex:
15923     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15924       return 0;
15925     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15926       return 1;
15927 
15928     default:
15929       return None;
15930   }
15931 
15932   return None;
15933 }
15934 
15935 static
15936 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15937                                                   ObjCMessageExpr *Message) {
15938   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15939                                             Message->getReceiverInterface(),
15940                                             NSAPI::ClassId_NSMutableDictionary);
15941   if (!IsMutableDictionary) {
15942     return None;
15943   }
15944 
15945   Selector Sel = Message->getSelector();
15946 
15947   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15948     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15949   if (!MKOpt) {
15950     return None;
15951   }
15952 
15953   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15954 
15955   switch (MK) {
15956     case NSAPI::NSMutableDict_setObjectForKey:
15957     case NSAPI::NSMutableDict_setValueForKey:
15958     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15959       return 0;
15960 
15961     default:
15962       return None;
15963   }
15964 
15965   return None;
15966 }
15967 
15968 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15969   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15970                                                 Message->getReceiverInterface(),
15971                                                 NSAPI::ClassId_NSMutableSet);
15972 
15973   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15974                                             Message->getReceiverInterface(),
15975                                             NSAPI::ClassId_NSMutableOrderedSet);
15976   if (!IsMutableSet && !IsMutableOrderedSet) {
15977     return None;
15978   }
15979 
15980   Selector Sel = Message->getSelector();
15981 
15982   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15983   if (!MKOpt) {
15984     return None;
15985   }
15986 
15987   NSAPI::NSSetMethodKind MK = *MKOpt;
15988 
15989   switch (MK) {
15990     case NSAPI::NSMutableSet_addObject:
15991     case NSAPI::NSOrderedSet_setObjectAtIndex:
15992     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15993     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15994       return 0;
15995     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15996       return 1;
15997   }
15998 
15999   return None;
16000 }
16001 
16002 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
16003   if (!Message->isInstanceMessage()) {
16004     return;
16005   }
16006 
16007   Optional<int> ArgOpt;
16008 
16009   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
16010       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
16011       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
16012     return;
16013   }
16014 
16015   int ArgIndex = *ArgOpt;
16016 
16017   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
16018   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
16019     Arg = OE->getSourceExpr()->IgnoreImpCasts();
16020   }
16021 
16022   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
16023     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
16024       if (ArgRE->isObjCSelfExpr()) {
16025         Diag(Message->getSourceRange().getBegin(),
16026              diag::warn_objc_circular_container)
16027           << ArgRE->getDecl() << StringRef("'super'");
16028       }
16029     }
16030   } else {
16031     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
16032 
16033     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
16034       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
16035     }
16036 
16037     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
16038       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
16039         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
16040           ValueDecl *Decl = ReceiverRE->getDecl();
16041           Diag(Message->getSourceRange().getBegin(),
16042                diag::warn_objc_circular_container)
16043             << Decl << Decl;
16044           if (!ArgRE->isObjCSelfExpr()) {
16045             Diag(Decl->getLocation(),
16046                  diag::note_objc_circular_container_declared_here)
16047               << Decl;
16048           }
16049         }
16050       }
16051     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
16052       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
16053         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
16054           ObjCIvarDecl *Decl = IvarRE->getDecl();
16055           Diag(Message->getSourceRange().getBegin(),
16056                diag::warn_objc_circular_container)
16057             << Decl << Decl;
16058           Diag(Decl->getLocation(),
16059                diag::note_objc_circular_container_declared_here)
16060             << Decl;
16061         }
16062       }
16063     }
16064   }
16065 }
16066 
16067 /// Check a message send to see if it's likely to cause a retain cycle.
16068 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
16069   // Only check instance methods whose selector looks like a setter.
16070   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
16071     return;
16072 
16073   // Try to find a variable that the receiver is strongly owned by.
16074   RetainCycleOwner owner;
16075   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
16076     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
16077       return;
16078   } else {
16079     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
16080     owner.Variable = getCurMethodDecl()->getSelfDecl();
16081     owner.Loc = msg->getSuperLoc();
16082     owner.Range = msg->getSuperLoc();
16083   }
16084 
16085   // Check whether the receiver is captured by any of the arguments.
16086   const ObjCMethodDecl *MD = msg->getMethodDecl();
16087   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
16088     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
16089       // noescape blocks should not be retained by the method.
16090       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
16091         continue;
16092       return diagnoseRetainCycle(*this, capturer, owner);
16093     }
16094   }
16095 }
16096 
16097 /// Check a property assign to see if it's likely to cause a retain cycle.
16098 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
16099   RetainCycleOwner owner;
16100   if (!findRetainCycleOwner(*this, receiver, owner))
16101     return;
16102 
16103   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
16104     diagnoseRetainCycle(*this, capturer, owner);
16105 }
16106 
16107 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
16108   RetainCycleOwner Owner;
16109   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
16110     return;
16111 
16112   // Because we don't have an expression for the variable, we have to set the
16113   // location explicitly here.
16114   Owner.Loc = Var->getLocation();
16115   Owner.Range = Var->getSourceRange();
16116 
16117   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
16118     diagnoseRetainCycle(*this, Capturer, Owner);
16119 }
16120 
16121 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
16122                                      Expr *RHS, bool isProperty) {
16123   // Check if RHS is an Objective-C object literal, which also can get
16124   // immediately zapped in a weak reference.  Note that we explicitly
16125   // allow ObjCStringLiterals, since those are designed to never really die.
16126   RHS = RHS->IgnoreParenImpCasts();
16127 
16128   // This enum needs to match with the 'select' in
16129   // warn_objc_arc_literal_assign (off-by-1).
16130   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
16131   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
16132     return false;
16133 
16134   S.Diag(Loc, diag::warn_arc_literal_assign)
16135     << (unsigned) Kind
16136     << (isProperty ? 0 : 1)
16137     << RHS->getSourceRange();
16138 
16139   return true;
16140 }
16141 
16142 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
16143                                     Qualifiers::ObjCLifetime LT,
16144                                     Expr *RHS, bool isProperty) {
16145   // Strip off any implicit cast added to get to the one ARC-specific.
16146   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16147     if (cast->getCastKind() == CK_ARCConsumeObject) {
16148       S.Diag(Loc, diag::warn_arc_retained_assign)
16149         << (LT == Qualifiers::OCL_ExplicitNone)
16150         << (isProperty ? 0 : 1)
16151         << RHS->getSourceRange();
16152       return true;
16153     }
16154     RHS = cast->getSubExpr();
16155   }
16156 
16157   if (LT == Qualifiers::OCL_Weak &&
16158       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16159     return true;
16160 
16161   return false;
16162 }
16163 
16164 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
16165                               QualType LHS, Expr *RHS) {
16166   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
16167 
16168   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
16169     return false;
16170 
16171   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
16172     return true;
16173 
16174   return false;
16175 }
16176 
16177 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
16178                               Expr *LHS, Expr *RHS) {
16179   QualType LHSType;
16180   // PropertyRef on LHS type need be directly obtained from
16181   // its declaration as it has a PseudoType.
16182   ObjCPropertyRefExpr *PRE
16183     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
16184   if (PRE && !PRE->isImplicitProperty()) {
16185     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16186     if (PD)
16187       LHSType = PD->getType();
16188   }
16189 
16190   if (LHSType.isNull())
16191     LHSType = LHS->getType();
16192 
16193   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
16194 
16195   if (LT == Qualifiers::OCL_Weak) {
16196     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
16197       getCurFunction()->markSafeWeakUse(LHS);
16198   }
16199 
16200   if (checkUnsafeAssigns(Loc, LHSType, RHS))
16201     return;
16202 
16203   // FIXME. Check for other life times.
16204   if (LT != Qualifiers::OCL_None)
16205     return;
16206 
16207   if (PRE) {
16208     if (PRE->isImplicitProperty())
16209       return;
16210     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16211     if (!PD)
16212       return;
16213 
16214     unsigned Attributes = PD->getPropertyAttributes();
16215     if (Attributes & ObjCPropertyAttribute::kind_assign) {
16216       // when 'assign' attribute was not explicitly specified
16217       // by user, ignore it and rely on property type itself
16218       // for lifetime info.
16219       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16220       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16221           LHSType->isObjCRetainableType())
16222         return;
16223 
16224       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16225         if (cast->getCastKind() == CK_ARCConsumeObject) {
16226           Diag(Loc, diag::warn_arc_retained_property_assign)
16227           << RHS->getSourceRange();
16228           return;
16229         }
16230         RHS = cast->getSubExpr();
16231       }
16232     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16233       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
16234         return;
16235     }
16236   }
16237 }
16238 
16239 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16240 
16241 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16242                                         SourceLocation StmtLoc,
16243                                         const NullStmt *Body) {
16244   // Do not warn if the body is a macro that expands to nothing, e.g:
16245   //
16246   // #define CALL(x)
16247   // if (condition)
16248   //   CALL(0);
16249   if (Body->hasLeadingEmptyMacro())
16250     return false;
16251 
16252   // Get line numbers of statement and body.
16253   bool StmtLineInvalid;
16254   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16255                                                       &StmtLineInvalid);
16256   if (StmtLineInvalid)
16257     return false;
16258 
16259   bool BodyLineInvalid;
16260   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16261                                                       &BodyLineInvalid);
16262   if (BodyLineInvalid)
16263     return false;
16264 
16265   // Warn if null statement and body are on the same line.
16266   if (StmtLine != BodyLine)
16267     return false;
16268 
16269   return true;
16270 }
16271 
16272 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
16273                                  const Stmt *Body,
16274                                  unsigned DiagID) {
16275   // Since this is a syntactic check, don't emit diagnostic for template
16276   // instantiations, this just adds noise.
16277   if (CurrentInstantiationScope)
16278     return;
16279 
16280   // The body should be a null statement.
16281   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16282   if (!NBody)
16283     return;
16284 
16285   // Do the usual checks.
16286   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16287     return;
16288 
16289   Diag(NBody->getSemiLoc(), DiagID);
16290   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16291 }
16292 
16293 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
16294                                  const Stmt *PossibleBody) {
16295   assert(!CurrentInstantiationScope); // Ensured by caller
16296 
16297   SourceLocation StmtLoc;
16298   const Stmt *Body;
16299   unsigned DiagID;
16300   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16301     StmtLoc = FS->getRParenLoc();
16302     Body = FS->getBody();
16303     DiagID = diag::warn_empty_for_body;
16304   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16305     StmtLoc = WS->getCond()->getSourceRange().getEnd();
16306     Body = WS->getBody();
16307     DiagID = diag::warn_empty_while_body;
16308   } else
16309     return; // Neither `for' nor `while'.
16310 
16311   // The body should be a null statement.
16312   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16313   if (!NBody)
16314     return;
16315 
16316   // Skip expensive checks if diagnostic is disabled.
16317   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16318     return;
16319 
16320   // Do the usual checks.
16321   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16322     return;
16323 
16324   // `for(...);' and `while(...);' are popular idioms, so in order to keep
16325   // noise level low, emit diagnostics only if for/while is followed by a
16326   // CompoundStmt, e.g.:
16327   //    for (int i = 0; i < n; i++);
16328   //    {
16329   //      a(i);
16330   //    }
16331   // or if for/while is followed by a statement with more indentation
16332   // than for/while itself:
16333   //    for (int i = 0; i < n; i++);
16334   //      a(i);
16335   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16336   if (!ProbableTypo) {
16337     bool BodyColInvalid;
16338     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16339         PossibleBody->getBeginLoc(), &BodyColInvalid);
16340     if (BodyColInvalid)
16341       return;
16342 
16343     bool StmtColInvalid;
16344     unsigned StmtCol =
16345         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16346     if (StmtColInvalid)
16347       return;
16348 
16349     if (BodyCol > StmtCol)
16350       ProbableTypo = true;
16351   }
16352 
16353   if (ProbableTypo) {
16354     Diag(NBody->getSemiLoc(), DiagID);
16355     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16356   }
16357 }
16358 
16359 //===--- CHECK: Warn on self move with std::move. -------------------------===//
16360 
16361 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
16362 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16363                              SourceLocation OpLoc) {
16364   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16365     return;
16366 
16367   if (inTemplateInstantiation())
16368     return;
16369 
16370   // Strip parens and casts away.
16371   LHSExpr = LHSExpr->IgnoreParenImpCasts();
16372   RHSExpr = RHSExpr->IgnoreParenImpCasts();
16373 
16374   // Check for a call expression
16375   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
16376   if (!CE || CE->getNumArgs() != 1)
16377     return;
16378 
16379   // Check for a call to std::move
16380   if (!CE->isCallToStdMove())
16381     return;
16382 
16383   // Get argument from std::move
16384   RHSExpr = CE->getArg(0);
16385 
16386   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16387   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16388 
16389   // Two DeclRefExpr's, check that the decls are the same.
16390   if (LHSDeclRef && RHSDeclRef) {
16391     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16392       return;
16393     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16394         RHSDeclRef->getDecl()->getCanonicalDecl())
16395       return;
16396 
16397     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16398                                         << LHSExpr->getSourceRange()
16399                                         << RHSExpr->getSourceRange();
16400     return;
16401   }
16402 
16403   // Member variables require a different approach to check for self moves.
16404   // MemberExpr's are the same if every nested MemberExpr refers to the same
16405   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16406   // the base Expr's are CXXThisExpr's.
16407   const Expr *LHSBase = LHSExpr;
16408   const Expr *RHSBase = RHSExpr;
16409   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16410   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16411   if (!LHSME || !RHSME)
16412     return;
16413 
16414   while (LHSME && RHSME) {
16415     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16416         RHSME->getMemberDecl()->getCanonicalDecl())
16417       return;
16418 
16419     LHSBase = LHSME->getBase();
16420     RHSBase = RHSME->getBase();
16421     LHSME = dyn_cast<MemberExpr>(LHSBase);
16422     RHSME = dyn_cast<MemberExpr>(RHSBase);
16423   }
16424 
16425   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16426   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16427   if (LHSDeclRef && RHSDeclRef) {
16428     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16429       return;
16430     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16431         RHSDeclRef->getDecl()->getCanonicalDecl())
16432       return;
16433 
16434     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16435                                         << LHSExpr->getSourceRange()
16436                                         << RHSExpr->getSourceRange();
16437     return;
16438   }
16439 
16440   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16441     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16442                                         << LHSExpr->getSourceRange()
16443                                         << RHSExpr->getSourceRange();
16444 }
16445 
16446 //===--- Layout compatibility ----------------------------------------------//
16447 
16448 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
16449 
16450 /// Check if two enumeration types are layout-compatible.
16451 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
16452   // C++11 [dcl.enum] p8:
16453   // Two enumeration types are layout-compatible if they have the same
16454   // underlying type.
16455   return ED1->isComplete() && ED2->isComplete() &&
16456          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16457 }
16458 
16459 /// Check if two fields are layout-compatible.
16460 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
16461                                FieldDecl *Field2) {
16462   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16463     return false;
16464 
16465   if (Field1->isBitField() != Field2->isBitField())
16466     return false;
16467 
16468   if (Field1->isBitField()) {
16469     // Make sure that the bit-fields are the same length.
16470     unsigned Bits1 = Field1->getBitWidthValue(C);
16471     unsigned Bits2 = Field2->getBitWidthValue(C);
16472 
16473     if (Bits1 != Bits2)
16474       return false;
16475   }
16476 
16477   return true;
16478 }
16479 
16480 /// Check if two standard-layout structs are layout-compatible.
16481 /// (C++11 [class.mem] p17)
16482 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
16483                                      RecordDecl *RD2) {
16484   // If both records are C++ classes, check that base classes match.
16485   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
16486     // If one of records is a CXXRecordDecl we are in C++ mode,
16487     // thus the other one is a CXXRecordDecl, too.
16488     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
16489     // Check number of base classes.
16490     if (D1CXX->getNumBases() != D2CXX->getNumBases())
16491       return false;
16492 
16493     // Check the base classes.
16494     for (CXXRecordDecl::base_class_const_iterator
16495                Base1 = D1CXX->bases_begin(),
16496            BaseEnd1 = D1CXX->bases_end(),
16497               Base2 = D2CXX->bases_begin();
16498          Base1 != BaseEnd1;
16499          ++Base1, ++Base2) {
16500       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16501         return false;
16502     }
16503   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16504     // If only RD2 is a C++ class, it should have zero base classes.
16505     if (D2CXX->getNumBases() > 0)
16506       return false;
16507   }
16508 
16509   // Check the fields.
16510   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16511                              Field2End = RD2->field_end(),
16512                              Field1 = RD1->field_begin(),
16513                              Field1End = RD1->field_end();
16514   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16515     if (!isLayoutCompatible(C, *Field1, *Field2))
16516       return false;
16517   }
16518   if (Field1 != Field1End || Field2 != Field2End)
16519     return false;
16520 
16521   return true;
16522 }
16523 
16524 /// Check if two standard-layout unions are layout-compatible.
16525 /// (C++11 [class.mem] p18)
16526 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16527                                     RecordDecl *RD2) {
16528   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16529   for (auto *Field2 : RD2->fields())
16530     UnmatchedFields.insert(Field2);
16531 
16532   for (auto *Field1 : RD1->fields()) {
16533     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16534         I = UnmatchedFields.begin(),
16535         E = UnmatchedFields.end();
16536 
16537     for ( ; I != E; ++I) {
16538       if (isLayoutCompatible(C, Field1, *I)) {
16539         bool Result = UnmatchedFields.erase(*I);
16540         (void) Result;
16541         assert(Result);
16542         break;
16543       }
16544     }
16545     if (I == E)
16546       return false;
16547   }
16548 
16549   return UnmatchedFields.empty();
16550 }
16551 
16552 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16553                                RecordDecl *RD2) {
16554   if (RD1->isUnion() != RD2->isUnion())
16555     return false;
16556 
16557   if (RD1->isUnion())
16558     return isLayoutCompatibleUnion(C, RD1, RD2);
16559   else
16560     return isLayoutCompatibleStruct(C, RD1, RD2);
16561 }
16562 
16563 /// Check if two types are layout-compatible in C++11 sense.
16564 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16565   if (T1.isNull() || T2.isNull())
16566     return false;
16567 
16568   // C++11 [basic.types] p11:
16569   // If two types T1 and T2 are the same type, then T1 and T2 are
16570   // layout-compatible types.
16571   if (C.hasSameType(T1, T2))
16572     return true;
16573 
16574   T1 = T1.getCanonicalType().getUnqualifiedType();
16575   T2 = T2.getCanonicalType().getUnqualifiedType();
16576 
16577   const Type::TypeClass TC1 = T1->getTypeClass();
16578   const Type::TypeClass TC2 = T2->getTypeClass();
16579 
16580   if (TC1 != TC2)
16581     return false;
16582 
16583   if (TC1 == Type::Enum) {
16584     return isLayoutCompatible(C,
16585                               cast<EnumType>(T1)->getDecl(),
16586                               cast<EnumType>(T2)->getDecl());
16587   } else if (TC1 == Type::Record) {
16588     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16589       return false;
16590 
16591     return isLayoutCompatible(C,
16592                               cast<RecordType>(T1)->getDecl(),
16593                               cast<RecordType>(T2)->getDecl());
16594   }
16595 
16596   return false;
16597 }
16598 
16599 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16600 
16601 /// Given a type tag expression find the type tag itself.
16602 ///
16603 /// \param TypeExpr Type tag expression, as it appears in user's code.
16604 ///
16605 /// \param VD Declaration of an identifier that appears in a type tag.
16606 ///
16607 /// \param MagicValue Type tag magic value.
16608 ///
16609 /// \param isConstantEvaluated whether the evalaution should be performed in
16610 
16611 /// constant context.
16612 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16613                             const ValueDecl **VD, uint64_t *MagicValue,
16614                             bool isConstantEvaluated) {
16615   while(true) {
16616     if (!TypeExpr)
16617       return false;
16618 
16619     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16620 
16621     switch (TypeExpr->getStmtClass()) {
16622     case Stmt::UnaryOperatorClass: {
16623       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16624       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16625         TypeExpr = UO->getSubExpr();
16626         continue;
16627       }
16628       return false;
16629     }
16630 
16631     case Stmt::DeclRefExprClass: {
16632       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16633       *VD = DRE->getDecl();
16634       return true;
16635     }
16636 
16637     case Stmt::IntegerLiteralClass: {
16638       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16639       llvm::APInt MagicValueAPInt = IL->getValue();
16640       if (MagicValueAPInt.getActiveBits() <= 64) {
16641         *MagicValue = MagicValueAPInt.getZExtValue();
16642         return true;
16643       } else
16644         return false;
16645     }
16646 
16647     case Stmt::BinaryConditionalOperatorClass:
16648     case Stmt::ConditionalOperatorClass: {
16649       const AbstractConditionalOperator *ACO =
16650           cast<AbstractConditionalOperator>(TypeExpr);
16651       bool Result;
16652       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16653                                                      isConstantEvaluated)) {
16654         if (Result)
16655           TypeExpr = ACO->getTrueExpr();
16656         else
16657           TypeExpr = ACO->getFalseExpr();
16658         continue;
16659       }
16660       return false;
16661     }
16662 
16663     case Stmt::BinaryOperatorClass: {
16664       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16665       if (BO->getOpcode() == BO_Comma) {
16666         TypeExpr = BO->getRHS();
16667         continue;
16668       }
16669       return false;
16670     }
16671 
16672     default:
16673       return false;
16674     }
16675   }
16676 }
16677 
16678 /// Retrieve the C type corresponding to type tag TypeExpr.
16679 ///
16680 /// \param TypeExpr Expression that specifies a type tag.
16681 ///
16682 /// \param MagicValues Registered magic values.
16683 ///
16684 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16685 ///        kind.
16686 ///
16687 /// \param TypeInfo Information about the corresponding C type.
16688 ///
16689 /// \param isConstantEvaluated whether the evalaution should be performed in
16690 /// constant context.
16691 ///
16692 /// \returns true if the corresponding C type was found.
16693 static bool GetMatchingCType(
16694     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16695     const ASTContext &Ctx,
16696     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16697         *MagicValues,
16698     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16699     bool isConstantEvaluated) {
16700   FoundWrongKind = false;
16701 
16702   // Variable declaration that has type_tag_for_datatype attribute.
16703   const ValueDecl *VD = nullptr;
16704 
16705   uint64_t MagicValue;
16706 
16707   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16708     return false;
16709 
16710   if (VD) {
16711     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16712       if (I->getArgumentKind() != ArgumentKind) {
16713         FoundWrongKind = true;
16714         return false;
16715       }
16716       TypeInfo.Type = I->getMatchingCType();
16717       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16718       TypeInfo.MustBeNull = I->getMustBeNull();
16719       return true;
16720     }
16721     return false;
16722   }
16723 
16724   if (!MagicValues)
16725     return false;
16726 
16727   llvm::DenseMap<Sema::TypeTagMagicValue,
16728                  Sema::TypeTagData>::const_iterator I =
16729       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16730   if (I == MagicValues->end())
16731     return false;
16732 
16733   TypeInfo = I->second;
16734   return true;
16735 }
16736 
16737 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16738                                       uint64_t MagicValue, QualType Type,
16739                                       bool LayoutCompatible,
16740                                       bool MustBeNull) {
16741   if (!TypeTagForDatatypeMagicValues)
16742     TypeTagForDatatypeMagicValues.reset(
16743         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16744 
16745   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16746   (*TypeTagForDatatypeMagicValues)[Magic] =
16747       TypeTagData(Type, LayoutCompatible, MustBeNull);
16748 }
16749 
16750 static bool IsSameCharType(QualType T1, QualType T2) {
16751   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16752   if (!BT1)
16753     return false;
16754 
16755   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16756   if (!BT2)
16757     return false;
16758 
16759   BuiltinType::Kind T1Kind = BT1->getKind();
16760   BuiltinType::Kind T2Kind = BT2->getKind();
16761 
16762   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16763          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16764          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16765          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16766 }
16767 
16768 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16769                                     const ArrayRef<const Expr *> ExprArgs,
16770                                     SourceLocation CallSiteLoc) {
16771   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16772   bool IsPointerAttr = Attr->getIsPointer();
16773 
16774   // Retrieve the argument representing the 'type_tag'.
16775   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16776   if (TypeTagIdxAST >= ExprArgs.size()) {
16777     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16778         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16779     return;
16780   }
16781   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16782   bool FoundWrongKind;
16783   TypeTagData TypeInfo;
16784   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16785                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16786                         TypeInfo, isConstantEvaluated())) {
16787     if (FoundWrongKind)
16788       Diag(TypeTagExpr->getExprLoc(),
16789            diag::warn_type_tag_for_datatype_wrong_kind)
16790         << TypeTagExpr->getSourceRange();
16791     return;
16792   }
16793 
16794   // Retrieve the argument representing the 'arg_idx'.
16795   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16796   if (ArgumentIdxAST >= ExprArgs.size()) {
16797     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16798         << 1 << Attr->getArgumentIdx().getSourceIndex();
16799     return;
16800   }
16801   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16802   if (IsPointerAttr) {
16803     // Skip implicit cast of pointer to `void *' (as a function argument).
16804     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16805       if (ICE->getType()->isVoidPointerType() &&
16806           ICE->getCastKind() == CK_BitCast)
16807         ArgumentExpr = ICE->getSubExpr();
16808   }
16809   QualType ArgumentType = ArgumentExpr->getType();
16810 
16811   // Passing a `void*' pointer shouldn't trigger a warning.
16812   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16813     return;
16814 
16815   if (TypeInfo.MustBeNull) {
16816     // Type tag with matching void type requires a null pointer.
16817     if (!ArgumentExpr->isNullPointerConstant(Context,
16818                                              Expr::NPC_ValueDependentIsNotNull)) {
16819       Diag(ArgumentExpr->getExprLoc(),
16820            diag::warn_type_safety_null_pointer_required)
16821           << ArgumentKind->getName()
16822           << ArgumentExpr->getSourceRange()
16823           << TypeTagExpr->getSourceRange();
16824     }
16825     return;
16826   }
16827 
16828   QualType RequiredType = TypeInfo.Type;
16829   if (IsPointerAttr)
16830     RequiredType = Context.getPointerType(RequiredType);
16831 
16832   bool mismatch = false;
16833   if (!TypeInfo.LayoutCompatible) {
16834     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16835 
16836     // C++11 [basic.fundamental] p1:
16837     // Plain char, signed char, and unsigned char are three distinct types.
16838     //
16839     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16840     // char' depending on the current char signedness mode.
16841     if (mismatch)
16842       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16843                                            RequiredType->getPointeeType())) ||
16844           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16845         mismatch = false;
16846   } else
16847     if (IsPointerAttr)
16848       mismatch = !isLayoutCompatible(Context,
16849                                      ArgumentType->getPointeeType(),
16850                                      RequiredType->getPointeeType());
16851     else
16852       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16853 
16854   if (mismatch)
16855     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16856         << ArgumentType << ArgumentKind
16857         << TypeInfo.LayoutCompatible << RequiredType
16858         << ArgumentExpr->getSourceRange()
16859         << TypeTagExpr->getSourceRange();
16860 }
16861 
16862 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16863                                          CharUnits Alignment) {
16864   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16865 }
16866 
16867 void Sema::DiagnoseMisalignedMembers() {
16868   for (MisalignedMember &m : MisalignedMembers) {
16869     const NamedDecl *ND = m.RD;
16870     if (ND->getName().empty()) {
16871       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16872         ND = TD;
16873     }
16874     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16875         << m.MD << ND << m.E->getSourceRange();
16876   }
16877   MisalignedMembers.clear();
16878 }
16879 
16880 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16881   E = E->IgnoreParens();
16882   if (!T->isPointerType() && !T->isIntegerType())
16883     return;
16884   if (isa<UnaryOperator>(E) &&
16885       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16886     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16887     if (isa<MemberExpr>(Op)) {
16888       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16889       if (MA != MisalignedMembers.end() &&
16890           (T->isIntegerType() ||
16891            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16892                                    Context.getTypeAlignInChars(
16893                                        T->getPointeeType()) <= MA->Alignment))))
16894         MisalignedMembers.erase(MA);
16895     }
16896   }
16897 }
16898 
16899 void Sema::RefersToMemberWithReducedAlignment(
16900     Expr *E,
16901     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16902         Action) {
16903   const auto *ME = dyn_cast<MemberExpr>(E);
16904   if (!ME)
16905     return;
16906 
16907   // No need to check expressions with an __unaligned-qualified type.
16908   if (E->getType().getQualifiers().hasUnaligned())
16909     return;
16910 
16911   // For a chain of MemberExpr like "a.b.c.d" this list
16912   // will keep FieldDecl's like [d, c, b].
16913   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16914   const MemberExpr *TopME = nullptr;
16915   bool AnyIsPacked = false;
16916   do {
16917     QualType BaseType = ME->getBase()->getType();
16918     if (BaseType->isDependentType())
16919       return;
16920     if (ME->isArrow())
16921       BaseType = BaseType->getPointeeType();
16922     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16923     if (RD->isInvalidDecl())
16924       return;
16925 
16926     ValueDecl *MD = ME->getMemberDecl();
16927     auto *FD = dyn_cast<FieldDecl>(MD);
16928     // We do not care about non-data members.
16929     if (!FD || FD->isInvalidDecl())
16930       return;
16931 
16932     AnyIsPacked =
16933         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16934     ReverseMemberChain.push_back(FD);
16935 
16936     TopME = ME;
16937     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16938   } while (ME);
16939   assert(TopME && "We did not compute a topmost MemberExpr!");
16940 
16941   // Not the scope of this diagnostic.
16942   if (!AnyIsPacked)
16943     return;
16944 
16945   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16946   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16947   // TODO: The innermost base of the member expression may be too complicated.
16948   // For now, just disregard these cases. This is left for future
16949   // improvement.
16950   if (!DRE && !isa<CXXThisExpr>(TopBase))
16951       return;
16952 
16953   // Alignment expected by the whole expression.
16954   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16955 
16956   // No need to do anything else with this case.
16957   if (ExpectedAlignment.isOne())
16958     return;
16959 
16960   // Synthesize offset of the whole access.
16961   CharUnits Offset;
16962   for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16963     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16964 
16965   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16966   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16967       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16968 
16969   // The base expression of the innermost MemberExpr may give
16970   // stronger guarantees than the class containing the member.
16971   if (DRE && !TopME->isArrow()) {
16972     const ValueDecl *VD = DRE->getDecl();
16973     if (!VD->getType()->isReferenceType())
16974       CompleteObjectAlignment =
16975           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16976   }
16977 
16978   // Check if the synthesized offset fulfills the alignment.
16979   if (Offset % ExpectedAlignment != 0 ||
16980       // It may fulfill the offset it but the effective alignment may still be
16981       // lower than the expected expression alignment.
16982       CompleteObjectAlignment < ExpectedAlignment) {
16983     // If this happens, we want to determine a sensible culprit of this.
16984     // Intuitively, watching the chain of member expressions from right to
16985     // left, we start with the required alignment (as required by the field
16986     // type) but some packed attribute in that chain has reduced the alignment.
16987     // It may happen that another packed structure increases it again. But if
16988     // we are here such increase has not been enough. So pointing the first
16989     // FieldDecl that either is packed or else its RecordDecl is,
16990     // seems reasonable.
16991     FieldDecl *FD = nullptr;
16992     CharUnits Alignment;
16993     for (FieldDecl *FDI : ReverseMemberChain) {
16994       if (FDI->hasAttr<PackedAttr>() ||
16995           FDI->getParent()->hasAttr<PackedAttr>()) {
16996         FD = FDI;
16997         Alignment = std::min(
16998             Context.getTypeAlignInChars(FD->getType()),
16999             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
17000         break;
17001       }
17002     }
17003     assert(FD && "We did not find a packed FieldDecl!");
17004     Action(E, FD->getParent(), FD, Alignment);
17005   }
17006 }
17007 
17008 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
17009   using namespace std::placeholders;
17010 
17011   RefersToMemberWithReducedAlignment(
17012       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
17013                      _2, _3, _4));
17014 }
17015 
17016 // Check if \p Ty is a valid type for the elementwise math builtins. If it is
17017 // not a valid type, emit an error message and return true. Otherwise return
17018 // false.
17019 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc,
17020                                         QualType Ty) {
17021   if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) {
17022     S.Diag(Loc, diag::err_builtin_invalid_arg_type)
17023         << 1 << /* vector, integer or float ty*/ 0 << Ty;
17024     return true;
17025   }
17026   return false;
17027 }
17028 
17029 bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) {
17030   if (checkArgCount(*this, TheCall, 1))
17031     return true;
17032 
17033   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17034   if (A.isInvalid())
17035     return true;
17036 
17037   TheCall->setArg(0, A.get());
17038   QualType TyA = A.get()->getType();
17039 
17040   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
17041     return true;
17042 
17043   TheCall->setType(TyA);
17044   return false;
17045 }
17046 
17047 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) {
17048   if (checkArgCount(*this, TheCall, 2))
17049     return true;
17050 
17051   ExprResult A = TheCall->getArg(0);
17052   ExprResult B = TheCall->getArg(1);
17053   // Do standard promotions between the two arguments, returning their common
17054   // type.
17055   QualType Res =
17056       UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
17057   if (A.isInvalid() || B.isInvalid())
17058     return true;
17059 
17060   QualType TyA = A.get()->getType();
17061   QualType TyB = B.get()->getType();
17062 
17063   if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
17064     return Diag(A.get()->getBeginLoc(),
17065                 diag::err_typecheck_call_different_arg_types)
17066            << TyA << TyB;
17067 
17068   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
17069     return true;
17070 
17071   TheCall->setArg(0, A.get());
17072   TheCall->setArg(1, B.get());
17073   TheCall->setType(Res);
17074   return false;
17075 }
17076 
17077 bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
17078   if (checkArgCount(*this, TheCall, 1))
17079     return true;
17080 
17081   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17082   if (A.isInvalid())
17083     return true;
17084 
17085   TheCall->setArg(0, A.get());
17086   return false;
17087 }
17088 
17089 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
17090                                             ExprResult CallResult) {
17091   if (checkArgCount(*this, TheCall, 1))
17092     return ExprError();
17093 
17094   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
17095   if (MatrixArg.isInvalid())
17096     return MatrixArg;
17097   Expr *Matrix = MatrixArg.get();
17098 
17099   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17100   if (!MType) {
17101     Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17102         << 1 << /* matrix ty*/ 1 << Matrix->getType();
17103     return ExprError();
17104   }
17105 
17106   // Create returned matrix type by swapping rows and columns of the argument
17107   // matrix type.
17108   QualType ResultType = Context.getConstantMatrixType(
17109       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
17110 
17111   // Change the return type to the type of the returned matrix.
17112   TheCall->setType(ResultType);
17113 
17114   // Update call argument to use the possibly converted matrix argument.
17115   TheCall->setArg(0, Matrix);
17116   return CallResult;
17117 }
17118 
17119 // Get and verify the matrix dimensions.
17120 static llvm::Optional<unsigned>
17121 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
17122   SourceLocation ErrorPos;
17123   Optional<llvm::APSInt> Value =
17124       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
17125   if (!Value) {
17126     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
17127         << Name;
17128     return {};
17129   }
17130   uint64_t Dim = Value->getZExtValue();
17131   if (!ConstantMatrixType::isDimensionValid(Dim)) {
17132     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
17133         << Name << ConstantMatrixType::getMaxElementsPerDimension();
17134     return {};
17135   }
17136   return Dim;
17137 }
17138 
17139 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17140                                                   ExprResult CallResult) {
17141   if (!getLangOpts().MatrixTypes) {
17142     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17143     return ExprError();
17144   }
17145 
17146   if (checkArgCount(*this, TheCall, 4))
17147     return ExprError();
17148 
17149   unsigned PtrArgIdx = 0;
17150   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17151   Expr *RowsExpr = TheCall->getArg(1);
17152   Expr *ColumnsExpr = TheCall->getArg(2);
17153   Expr *StrideExpr = TheCall->getArg(3);
17154 
17155   bool ArgError = false;
17156 
17157   // Check pointer argument.
17158   {
17159     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17160     if (PtrConv.isInvalid())
17161       return PtrConv;
17162     PtrExpr = PtrConv.get();
17163     TheCall->setArg(0, PtrExpr);
17164     if (PtrExpr->isTypeDependent()) {
17165       TheCall->setType(Context.DependentTy);
17166       return TheCall;
17167     }
17168   }
17169 
17170   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17171   QualType ElementTy;
17172   if (!PtrTy) {
17173     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17174         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17175     ArgError = true;
17176   } else {
17177     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17178 
17179     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
17180       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17181           << PtrArgIdx + 1 << /* pointer to element ty*/ 2
17182           << PtrExpr->getType();
17183       ArgError = true;
17184     }
17185   }
17186 
17187   // Apply default Lvalue conversions and convert the expression to size_t.
17188   auto ApplyArgumentConversions = [this](Expr *E) {
17189     ExprResult Conv = DefaultLvalueConversion(E);
17190     if (Conv.isInvalid())
17191       return Conv;
17192 
17193     return tryConvertExprToType(Conv.get(), Context.getSizeType());
17194   };
17195 
17196   // Apply conversion to row and column expressions.
17197   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17198   if (!RowsConv.isInvalid()) {
17199     RowsExpr = RowsConv.get();
17200     TheCall->setArg(1, RowsExpr);
17201   } else
17202     RowsExpr = nullptr;
17203 
17204   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17205   if (!ColumnsConv.isInvalid()) {
17206     ColumnsExpr = ColumnsConv.get();
17207     TheCall->setArg(2, ColumnsExpr);
17208   } else
17209     ColumnsExpr = nullptr;
17210 
17211   // If any any part of the result matrix type is still pending, just use
17212   // Context.DependentTy, until all parts are resolved.
17213   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17214       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17215     TheCall->setType(Context.DependentTy);
17216     return CallResult;
17217   }
17218 
17219   // Check row and column dimensions.
17220   llvm::Optional<unsigned> MaybeRows;
17221   if (RowsExpr)
17222     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17223 
17224   llvm::Optional<unsigned> MaybeColumns;
17225   if (ColumnsExpr)
17226     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17227 
17228   // Check stride argument.
17229   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17230   if (StrideConv.isInvalid())
17231     return ExprError();
17232   StrideExpr = StrideConv.get();
17233   TheCall->setArg(3, StrideExpr);
17234 
17235   if (MaybeRows) {
17236     if (Optional<llvm::APSInt> Value =
17237             StrideExpr->getIntegerConstantExpr(Context)) {
17238       uint64_t Stride = Value->getZExtValue();
17239       if (Stride < *MaybeRows) {
17240         Diag(StrideExpr->getBeginLoc(),
17241              diag::err_builtin_matrix_stride_too_small);
17242         ArgError = true;
17243       }
17244     }
17245   }
17246 
17247   if (ArgError || !MaybeRows || !MaybeColumns)
17248     return ExprError();
17249 
17250   TheCall->setType(
17251       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17252   return CallResult;
17253 }
17254 
17255 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17256                                                    ExprResult CallResult) {
17257   if (checkArgCount(*this, TheCall, 3))
17258     return ExprError();
17259 
17260   unsigned PtrArgIdx = 1;
17261   Expr *MatrixExpr = TheCall->getArg(0);
17262   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17263   Expr *StrideExpr = TheCall->getArg(2);
17264 
17265   bool ArgError = false;
17266 
17267   {
17268     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17269     if (MatrixConv.isInvalid())
17270       return MatrixConv;
17271     MatrixExpr = MatrixConv.get();
17272     TheCall->setArg(0, MatrixExpr);
17273   }
17274   if (MatrixExpr->isTypeDependent()) {
17275     TheCall->setType(Context.DependentTy);
17276     return TheCall;
17277   }
17278 
17279   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17280   if (!MatrixTy) {
17281     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17282         << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
17283     ArgError = true;
17284   }
17285 
17286   {
17287     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17288     if (PtrConv.isInvalid())
17289       return PtrConv;
17290     PtrExpr = PtrConv.get();
17291     TheCall->setArg(1, PtrExpr);
17292     if (PtrExpr->isTypeDependent()) {
17293       TheCall->setType(Context.DependentTy);
17294       return TheCall;
17295     }
17296   }
17297 
17298   // Check pointer argument.
17299   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17300   if (!PtrTy) {
17301     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17302         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17303     ArgError = true;
17304   } else {
17305     QualType ElementTy = PtrTy->getPointeeType();
17306     if (ElementTy.isConstQualified()) {
17307       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17308       ArgError = true;
17309     }
17310     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17311     if (MatrixTy &&
17312         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17313       Diag(PtrExpr->getBeginLoc(),
17314            diag::err_builtin_matrix_pointer_arg_mismatch)
17315           << ElementTy << MatrixTy->getElementType();
17316       ArgError = true;
17317     }
17318   }
17319 
17320   // Apply default Lvalue conversions and convert the stride expression to
17321   // size_t.
17322   {
17323     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17324     if (StrideConv.isInvalid())
17325       return StrideConv;
17326 
17327     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17328     if (StrideConv.isInvalid())
17329       return StrideConv;
17330     StrideExpr = StrideConv.get();
17331     TheCall->setArg(2, StrideExpr);
17332   }
17333 
17334   // Check stride argument.
17335   if (MatrixTy) {
17336     if (Optional<llvm::APSInt> Value =
17337             StrideExpr->getIntegerConstantExpr(Context)) {
17338       uint64_t Stride = Value->getZExtValue();
17339       if (Stride < MatrixTy->getNumRows()) {
17340         Diag(StrideExpr->getBeginLoc(),
17341              diag::err_builtin_matrix_stride_too_small);
17342         ArgError = true;
17343       }
17344     }
17345   }
17346 
17347   if (ArgError)
17348     return ExprError();
17349 
17350   return CallResult;
17351 }
17352 
17353 /// \brief Enforce the bounds of a TCB
17354 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
17355 /// directly calls other functions in the same TCB as marked by the enforce_tcb
17356 /// and enforce_tcb_leaf attributes.
17357 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
17358                                const FunctionDecl *Callee) {
17359   const FunctionDecl *Caller = getCurFunctionDecl();
17360 
17361   // Calls to builtins are not enforced.
17362   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
17363       Callee->getBuiltinID() != 0)
17364     return;
17365 
17366   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17367   // all TCBs the callee is a part of.
17368   llvm::StringSet<> CalleeTCBs;
17369   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
17370            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17371   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
17372            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17373 
17374   // Go through the TCBs the caller is a part of and emit warnings if Caller
17375   // is in a TCB that the Callee is not.
17376   for_each(
17377       Caller->specific_attrs<EnforceTCBAttr>(),
17378       [&](const auto *A) {
17379         StringRef CallerTCB = A->getTCBName();
17380         if (CalleeTCBs.count(CallerTCB) == 0) {
17381           this->Diag(TheCall->getExprLoc(),
17382                      diag::warn_tcb_enforcement_violation) << Callee
17383                                                            << CallerTCB;
17384         }
17385       });
17386 }
17387