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: Floating-Point comparisons (-Wfloat-equal) ---------------===//
11440 
11441 /// Check for comparisons of floating point operands using != and ==.
11442 /// Issue a warning if these are no self-comparisons, as they are not likely
11443 /// to do what the programmer intended.
11444 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
11445   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
11446   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
11447 
11448   // Special case: check for x == x (which is OK).
11449   // Do not emit warnings for such cases.
11450   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11451     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11452       if (DRL->getDecl() == DRR->getDecl())
11453         return;
11454 
11455   // Special case: check for comparisons against literals that can be exactly
11456   //  represented by APFloat.  In such cases, do not emit a warning.  This
11457   //  is a heuristic: often comparison against such literals are used to
11458   //  detect if a value in a variable has not changed.  This clearly can
11459   //  lead to false negatives.
11460   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11461     if (FLL->isExact())
11462       return;
11463   } else
11464     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11465       if (FLR->isExact())
11466         return;
11467 
11468   // Check for comparisons with builtin types.
11469   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11470     if (CL->getBuiltinCallee())
11471       return;
11472 
11473   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11474     if (CR->getBuiltinCallee())
11475       return;
11476 
11477   // Emit the diagnostic.
11478   Diag(Loc, diag::warn_floatingpoint_eq)
11479     << LHS->getSourceRange() << RHS->getSourceRange();
11480 }
11481 
11482 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11483 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11484 
11485 namespace {
11486 
11487 /// Structure recording the 'active' range of an integer-valued
11488 /// expression.
11489 struct IntRange {
11490   /// The number of bits active in the int. Note that this includes exactly one
11491   /// sign bit if !NonNegative.
11492   unsigned Width;
11493 
11494   /// True if the int is known not to have negative values. If so, all leading
11495   /// bits before Width are known zero, otherwise they are known to be the
11496   /// same as the MSB within Width.
11497   bool NonNegative;
11498 
11499   IntRange(unsigned Width, bool NonNegative)
11500       : Width(Width), NonNegative(NonNegative) {}
11501 
11502   /// Number of bits excluding the sign bit.
11503   unsigned valueBits() const {
11504     return NonNegative ? Width : Width - 1;
11505   }
11506 
11507   /// Returns the range of the bool type.
11508   static IntRange forBoolType() {
11509     return IntRange(1, true);
11510   }
11511 
11512   /// Returns the range of an opaque value of the given integral type.
11513   static IntRange forValueOfType(ASTContext &C, QualType T) {
11514     return forValueOfCanonicalType(C,
11515                           T->getCanonicalTypeInternal().getTypePtr());
11516   }
11517 
11518   /// Returns the range of an opaque value of a canonical integral type.
11519   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11520     assert(T->isCanonicalUnqualified());
11521 
11522     if (const VectorType *VT = dyn_cast<VectorType>(T))
11523       T = VT->getElementType().getTypePtr();
11524     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11525       T = CT->getElementType().getTypePtr();
11526     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11527       T = AT->getValueType().getTypePtr();
11528 
11529     if (!C.getLangOpts().CPlusPlus) {
11530       // For enum types in C code, use the underlying datatype.
11531       if (const EnumType *ET = dyn_cast<EnumType>(T))
11532         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11533     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11534       // For enum types in C++, use the known bit width of the enumerators.
11535       EnumDecl *Enum = ET->getDecl();
11536       // In C++11, enums can have a fixed underlying type. Use this type to
11537       // compute the range.
11538       if (Enum->isFixed()) {
11539         return IntRange(C.getIntWidth(QualType(T, 0)),
11540                         !ET->isSignedIntegerOrEnumerationType());
11541       }
11542 
11543       unsigned NumPositive = Enum->getNumPositiveBits();
11544       unsigned NumNegative = Enum->getNumNegativeBits();
11545 
11546       if (NumNegative == 0)
11547         return IntRange(NumPositive, true/*NonNegative*/);
11548       else
11549         return IntRange(std::max(NumPositive + 1, NumNegative),
11550                         false/*NonNegative*/);
11551     }
11552 
11553     if (const auto *EIT = dyn_cast<BitIntType>(T))
11554       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11555 
11556     const BuiltinType *BT = cast<BuiltinType>(T);
11557     assert(BT->isInteger());
11558 
11559     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11560   }
11561 
11562   /// Returns the "target" range of a canonical integral type, i.e.
11563   /// the range of values expressible in the type.
11564   ///
11565   /// This matches forValueOfCanonicalType except that enums have the
11566   /// full range of their type, not the range of their enumerators.
11567   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11568     assert(T->isCanonicalUnqualified());
11569 
11570     if (const VectorType *VT = dyn_cast<VectorType>(T))
11571       T = VT->getElementType().getTypePtr();
11572     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11573       T = CT->getElementType().getTypePtr();
11574     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11575       T = AT->getValueType().getTypePtr();
11576     if (const EnumType *ET = dyn_cast<EnumType>(T))
11577       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11578 
11579     if (const auto *EIT = dyn_cast<BitIntType>(T))
11580       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11581 
11582     const BuiltinType *BT = cast<BuiltinType>(T);
11583     assert(BT->isInteger());
11584 
11585     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11586   }
11587 
11588   /// Returns the supremum of two ranges: i.e. their conservative merge.
11589   static IntRange join(IntRange L, IntRange R) {
11590     bool Unsigned = L.NonNegative && R.NonNegative;
11591     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11592                     L.NonNegative && R.NonNegative);
11593   }
11594 
11595   /// Return the range of a bitwise-AND of the two ranges.
11596   static IntRange bit_and(IntRange L, IntRange R) {
11597     unsigned Bits = std::max(L.Width, R.Width);
11598     bool NonNegative = false;
11599     if (L.NonNegative) {
11600       Bits = std::min(Bits, L.Width);
11601       NonNegative = true;
11602     }
11603     if (R.NonNegative) {
11604       Bits = std::min(Bits, R.Width);
11605       NonNegative = true;
11606     }
11607     return IntRange(Bits, NonNegative);
11608   }
11609 
11610   /// Return the range of a sum of the two ranges.
11611   static IntRange sum(IntRange L, IntRange R) {
11612     bool Unsigned = L.NonNegative && R.NonNegative;
11613     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11614                     Unsigned);
11615   }
11616 
11617   /// Return the range of a difference of the two ranges.
11618   static IntRange difference(IntRange L, IntRange R) {
11619     // We need a 1-bit-wider range if:
11620     //   1) LHS can be negative: least value can be reduced.
11621     //   2) RHS can be negative: greatest value can be increased.
11622     bool CanWiden = !L.NonNegative || !R.NonNegative;
11623     bool Unsigned = L.NonNegative && R.Width == 0;
11624     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11625                         !Unsigned,
11626                     Unsigned);
11627   }
11628 
11629   /// Return the range of a product of the two ranges.
11630   static IntRange product(IntRange L, IntRange R) {
11631     // If both LHS and RHS can be negative, we can form
11632     //   -2^L * -2^R = 2^(L + R)
11633     // which requires L + R + 1 value bits to represent.
11634     bool CanWiden = !L.NonNegative && !R.NonNegative;
11635     bool Unsigned = L.NonNegative && R.NonNegative;
11636     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11637                     Unsigned);
11638   }
11639 
11640   /// Return the range of a remainder operation between the two ranges.
11641   static IntRange rem(IntRange L, IntRange R) {
11642     // The result of a remainder can't be larger than the result of
11643     // either side. The sign of the result is the sign of the LHS.
11644     bool Unsigned = L.NonNegative;
11645     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11646                     Unsigned);
11647   }
11648 };
11649 
11650 } // namespace
11651 
11652 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11653                               unsigned MaxWidth) {
11654   if (value.isSigned() && value.isNegative())
11655     return IntRange(value.getMinSignedBits(), false);
11656 
11657   if (value.getBitWidth() > MaxWidth)
11658     value = value.trunc(MaxWidth);
11659 
11660   // isNonNegative() just checks the sign bit without considering
11661   // signedness.
11662   return IntRange(value.getActiveBits(), true);
11663 }
11664 
11665 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11666                               unsigned MaxWidth) {
11667   if (result.isInt())
11668     return GetValueRange(C, result.getInt(), MaxWidth);
11669 
11670   if (result.isVector()) {
11671     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11672     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11673       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11674       R = IntRange::join(R, El);
11675     }
11676     return R;
11677   }
11678 
11679   if (result.isComplexInt()) {
11680     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11681     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11682     return IntRange::join(R, I);
11683   }
11684 
11685   // This can happen with lossless casts to intptr_t of "based" lvalues.
11686   // Assume it might use arbitrary bits.
11687   // FIXME: The only reason we need to pass the type in here is to get
11688   // the sign right on this one case.  It would be nice if APValue
11689   // preserved this.
11690   assert(result.isLValue() || result.isAddrLabelDiff());
11691   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11692 }
11693 
11694 static QualType GetExprType(const Expr *E) {
11695   QualType Ty = E->getType();
11696   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11697     Ty = AtomicRHS->getValueType();
11698   return Ty;
11699 }
11700 
11701 /// Pseudo-evaluate the given integer expression, estimating the
11702 /// range of values it might take.
11703 ///
11704 /// \param MaxWidth The width to which the value will be truncated.
11705 /// \param Approximate If \c true, return a likely range for the result: in
11706 ///        particular, assume that arithmetic on narrower types doesn't leave
11707 ///        those types. If \c false, return a range including all possible
11708 ///        result values.
11709 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11710                              bool InConstantContext, bool Approximate) {
11711   E = E->IgnoreParens();
11712 
11713   // Try a full evaluation first.
11714   Expr::EvalResult result;
11715   if (E->EvaluateAsRValue(result, C, InConstantContext))
11716     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11717 
11718   // I think we only want to look through implicit casts here; if the
11719   // user has an explicit widening cast, we should treat the value as
11720   // being of the new, wider type.
11721   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11722     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11723       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11724                           Approximate);
11725 
11726     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11727 
11728     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11729                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11730 
11731     // Assume that non-integer casts can span the full range of the type.
11732     if (!isIntegerCast)
11733       return OutputTypeRange;
11734 
11735     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11736                                      std::min(MaxWidth, OutputTypeRange.Width),
11737                                      InConstantContext, Approximate);
11738 
11739     // Bail out if the subexpr's range is as wide as the cast type.
11740     if (SubRange.Width >= OutputTypeRange.Width)
11741       return OutputTypeRange;
11742 
11743     // Otherwise, we take the smaller width, and we're non-negative if
11744     // either the output type or the subexpr is.
11745     return IntRange(SubRange.Width,
11746                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11747   }
11748 
11749   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11750     // If we can fold the condition, just take that operand.
11751     bool CondResult;
11752     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11753       return GetExprRange(C,
11754                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11755                           MaxWidth, InConstantContext, Approximate);
11756 
11757     // Otherwise, conservatively merge.
11758     // GetExprRange requires an integer expression, but a throw expression
11759     // results in a void type.
11760     Expr *E = CO->getTrueExpr();
11761     IntRange L = E->getType()->isVoidType()
11762                      ? IntRange{0, true}
11763                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11764     E = CO->getFalseExpr();
11765     IntRange R = E->getType()->isVoidType()
11766                      ? IntRange{0, true}
11767                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11768     return IntRange::join(L, R);
11769   }
11770 
11771   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11772     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11773 
11774     switch (BO->getOpcode()) {
11775     case BO_Cmp:
11776       llvm_unreachable("builtin <=> should have class type");
11777 
11778     // Boolean-valued operations are single-bit and positive.
11779     case BO_LAnd:
11780     case BO_LOr:
11781     case BO_LT:
11782     case BO_GT:
11783     case BO_LE:
11784     case BO_GE:
11785     case BO_EQ:
11786     case BO_NE:
11787       return IntRange::forBoolType();
11788 
11789     // The type of the assignments is the type of the LHS, so the RHS
11790     // is not necessarily the same type.
11791     case BO_MulAssign:
11792     case BO_DivAssign:
11793     case BO_RemAssign:
11794     case BO_AddAssign:
11795     case BO_SubAssign:
11796     case BO_XorAssign:
11797     case BO_OrAssign:
11798       // TODO: bitfields?
11799       return IntRange::forValueOfType(C, GetExprType(E));
11800 
11801     // Simple assignments just pass through the RHS, which will have
11802     // been coerced to the LHS type.
11803     case BO_Assign:
11804       // TODO: bitfields?
11805       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11806                           Approximate);
11807 
11808     // Operations with opaque sources are black-listed.
11809     case BO_PtrMemD:
11810     case BO_PtrMemI:
11811       return IntRange::forValueOfType(C, GetExprType(E));
11812 
11813     // Bitwise-and uses the *infinum* of the two source ranges.
11814     case BO_And:
11815     case BO_AndAssign:
11816       Combine = IntRange::bit_and;
11817       break;
11818 
11819     // Left shift gets black-listed based on a judgement call.
11820     case BO_Shl:
11821       // ...except that we want to treat '1 << (blah)' as logically
11822       // positive.  It's an important idiom.
11823       if (IntegerLiteral *I
11824             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11825         if (I->getValue() == 1) {
11826           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11827           return IntRange(R.Width, /*NonNegative*/ true);
11828         }
11829       }
11830       LLVM_FALLTHROUGH;
11831 
11832     case BO_ShlAssign:
11833       return IntRange::forValueOfType(C, GetExprType(E));
11834 
11835     // Right shift by a constant can narrow its left argument.
11836     case BO_Shr:
11837     case BO_ShrAssign: {
11838       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11839                                 Approximate);
11840 
11841       // If the shift amount is a positive constant, drop the width by
11842       // that much.
11843       if (Optional<llvm::APSInt> shift =
11844               BO->getRHS()->getIntegerConstantExpr(C)) {
11845         if (shift->isNonNegative()) {
11846           unsigned zext = shift->getZExtValue();
11847           if (zext >= L.Width)
11848             L.Width = (L.NonNegative ? 0 : 1);
11849           else
11850             L.Width -= zext;
11851         }
11852       }
11853 
11854       return L;
11855     }
11856 
11857     // Comma acts as its right operand.
11858     case BO_Comma:
11859       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11860                           Approximate);
11861 
11862     case BO_Add:
11863       if (!Approximate)
11864         Combine = IntRange::sum;
11865       break;
11866 
11867     case BO_Sub:
11868       if (BO->getLHS()->getType()->isPointerType())
11869         return IntRange::forValueOfType(C, GetExprType(E));
11870       if (!Approximate)
11871         Combine = IntRange::difference;
11872       break;
11873 
11874     case BO_Mul:
11875       if (!Approximate)
11876         Combine = IntRange::product;
11877       break;
11878 
11879     // The width of a division result is mostly determined by the size
11880     // of the LHS.
11881     case BO_Div: {
11882       // Don't 'pre-truncate' the operands.
11883       unsigned opWidth = C.getIntWidth(GetExprType(E));
11884       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11885                                 Approximate);
11886 
11887       // If the divisor is constant, use that.
11888       if (Optional<llvm::APSInt> divisor =
11889               BO->getRHS()->getIntegerConstantExpr(C)) {
11890         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11891         if (log2 >= L.Width)
11892           L.Width = (L.NonNegative ? 0 : 1);
11893         else
11894           L.Width = std::min(L.Width - log2, MaxWidth);
11895         return L;
11896       }
11897 
11898       // Otherwise, just use the LHS's width.
11899       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11900       // could be -1.
11901       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11902                                 Approximate);
11903       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11904     }
11905 
11906     case BO_Rem:
11907       Combine = IntRange::rem;
11908       break;
11909 
11910     // The default behavior is okay for these.
11911     case BO_Xor:
11912     case BO_Or:
11913       break;
11914     }
11915 
11916     // Combine the two ranges, but limit the result to the type in which we
11917     // performed the computation.
11918     QualType T = GetExprType(E);
11919     unsigned opWidth = C.getIntWidth(T);
11920     IntRange L =
11921         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11922     IntRange R =
11923         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11924     IntRange C = Combine(L, R);
11925     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11926     C.Width = std::min(C.Width, MaxWidth);
11927     return C;
11928   }
11929 
11930   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11931     switch (UO->getOpcode()) {
11932     // Boolean-valued operations are white-listed.
11933     case UO_LNot:
11934       return IntRange::forBoolType();
11935 
11936     // Operations with opaque sources are black-listed.
11937     case UO_Deref:
11938     case UO_AddrOf: // should be impossible
11939       return IntRange::forValueOfType(C, GetExprType(E));
11940 
11941     default:
11942       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11943                           Approximate);
11944     }
11945   }
11946 
11947   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11948     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11949                         Approximate);
11950 
11951   if (const auto *BitField = E->getSourceBitField())
11952     return IntRange(BitField->getBitWidthValue(C),
11953                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11954 
11955   return IntRange::forValueOfType(C, GetExprType(E));
11956 }
11957 
11958 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11959                              bool InConstantContext, bool Approximate) {
11960   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11961                       Approximate);
11962 }
11963 
11964 /// Checks whether the given value, which currently has the given
11965 /// source semantics, has the same value when coerced through the
11966 /// target semantics.
11967 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11968                                  const llvm::fltSemantics &Src,
11969                                  const llvm::fltSemantics &Tgt) {
11970   llvm::APFloat truncated = value;
11971 
11972   bool ignored;
11973   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11974   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11975 
11976   return truncated.bitwiseIsEqual(value);
11977 }
11978 
11979 /// Checks whether the given value, which currently has the given
11980 /// source semantics, has the same value when coerced through the
11981 /// target semantics.
11982 ///
11983 /// The value might be a vector of floats (or a complex number).
11984 static bool IsSameFloatAfterCast(const APValue &value,
11985                                  const llvm::fltSemantics &Src,
11986                                  const llvm::fltSemantics &Tgt) {
11987   if (value.isFloat())
11988     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11989 
11990   if (value.isVector()) {
11991     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11992       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11993         return false;
11994     return true;
11995   }
11996 
11997   assert(value.isComplexFloat());
11998   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11999           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
12000 }
12001 
12002 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
12003                                        bool IsListInit = false);
12004 
12005 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
12006   // Suppress cases where we are comparing against an enum constant.
12007   if (const DeclRefExpr *DR =
12008       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
12009     if (isa<EnumConstantDecl>(DR->getDecl()))
12010       return true;
12011 
12012   // Suppress cases where the value is expanded from a macro, unless that macro
12013   // is how a language represents a boolean literal. This is the case in both C
12014   // and Objective-C.
12015   SourceLocation BeginLoc = E->getBeginLoc();
12016   if (BeginLoc.isMacroID()) {
12017     StringRef MacroName = Lexer::getImmediateMacroName(
12018         BeginLoc, S.getSourceManager(), S.getLangOpts());
12019     return MacroName != "YES" && MacroName != "NO" &&
12020            MacroName != "true" && MacroName != "false";
12021   }
12022 
12023   return false;
12024 }
12025 
12026 static bool isKnownToHaveUnsignedValue(Expr *E) {
12027   return E->getType()->isIntegerType() &&
12028          (!E->getType()->isSignedIntegerType() ||
12029           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
12030 }
12031 
12032 namespace {
12033 /// The promoted range of values of a type. In general this has the
12034 /// following structure:
12035 ///
12036 ///     |-----------| . . . |-----------|
12037 ///     ^           ^       ^           ^
12038 ///    Min       HoleMin  HoleMax      Max
12039 ///
12040 /// ... where there is only a hole if a signed type is promoted to unsigned
12041 /// (in which case Min and Max are the smallest and largest representable
12042 /// values).
12043 struct PromotedRange {
12044   // Min, or HoleMax if there is a hole.
12045   llvm::APSInt PromotedMin;
12046   // Max, or HoleMin if there is a hole.
12047   llvm::APSInt PromotedMax;
12048 
12049   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12050     if (R.Width == 0)
12051       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12052     else if (R.Width >= BitWidth && !Unsigned) {
12053       // Promotion made the type *narrower*. This happens when promoting
12054       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12055       // Treat all values of 'signed int' as being in range for now.
12056       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
12057       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
12058     } else {
12059       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
12060                         .extOrTrunc(BitWidth);
12061       PromotedMin.setIsUnsigned(Unsigned);
12062 
12063       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
12064                         .extOrTrunc(BitWidth);
12065       PromotedMax.setIsUnsigned(Unsigned);
12066     }
12067   }
12068 
12069   // Determine whether this range is contiguous (has no hole).
12070   bool isContiguous() const { return PromotedMin <= PromotedMax; }
12071 
12072   // Where a constant value is within the range.
12073   enum ComparisonResult {
12074     LT = 0x1,
12075     LE = 0x2,
12076     GT = 0x4,
12077     GE = 0x8,
12078     EQ = 0x10,
12079     NE = 0x20,
12080     InRangeFlag = 0x40,
12081 
12082     Less = LE | LT | NE,
12083     Min = LE | InRangeFlag,
12084     InRange = InRangeFlag,
12085     Max = GE | InRangeFlag,
12086     Greater = GE | GT | NE,
12087 
12088     OnlyValue = LE | GE | EQ | InRangeFlag,
12089     InHole = NE
12090   };
12091 
12092   ComparisonResult compare(const llvm::APSInt &Value) const {
12093     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12094            Value.isUnsigned() == PromotedMin.isUnsigned());
12095     if (!isContiguous()) {
12096       assert(Value.isUnsigned() && "discontiguous range for signed compare");
12097       if (Value.isMinValue()) return Min;
12098       if (Value.isMaxValue()) return Max;
12099       if (Value >= PromotedMin) return InRange;
12100       if (Value <= PromotedMax) return InRange;
12101       return InHole;
12102     }
12103 
12104     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
12105     case -1: return Less;
12106     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12107     case 1:
12108       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
12109       case -1: return InRange;
12110       case 0: return Max;
12111       case 1: return Greater;
12112       }
12113     }
12114 
12115     llvm_unreachable("impossible compare result");
12116   }
12117 
12118   static llvm::Optional<StringRef>
12119   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12120     if (Op == BO_Cmp) {
12121       ComparisonResult LTFlag = LT, GTFlag = GT;
12122       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
12123 
12124       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12125       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12126       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12127       return llvm::None;
12128     }
12129 
12130     ComparisonResult TrueFlag, FalseFlag;
12131     if (Op == BO_EQ) {
12132       TrueFlag = EQ;
12133       FalseFlag = NE;
12134     } else if (Op == BO_NE) {
12135       TrueFlag = NE;
12136       FalseFlag = EQ;
12137     } else {
12138       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12139         TrueFlag = LT;
12140         FalseFlag = GE;
12141       } else {
12142         TrueFlag = GT;
12143         FalseFlag = LE;
12144       }
12145       if (Op == BO_GE || Op == BO_LE)
12146         std::swap(TrueFlag, FalseFlag);
12147     }
12148     if (R & TrueFlag)
12149       return StringRef("true");
12150     if (R & FalseFlag)
12151       return StringRef("false");
12152     return llvm::None;
12153   }
12154 };
12155 }
12156 
12157 static bool HasEnumType(Expr *E) {
12158   // Strip off implicit integral promotions.
12159   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12160     if (ICE->getCastKind() != CK_IntegralCast &&
12161         ICE->getCastKind() != CK_NoOp)
12162       break;
12163     E = ICE->getSubExpr();
12164   }
12165 
12166   return E->getType()->isEnumeralType();
12167 }
12168 
12169 static int classifyConstantValue(Expr *Constant) {
12170   // The values of this enumeration are used in the diagnostics
12171   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12172   enum ConstantValueKind {
12173     Miscellaneous = 0,
12174     LiteralTrue,
12175     LiteralFalse
12176   };
12177   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12178     return BL->getValue() ? ConstantValueKind::LiteralTrue
12179                           : ConstantValueKind::LiteralFalse;
12180   return ConstantValueKind::Miscellaneous;
12181 }
12182 
12183 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
12184                                         Expr *Constant, Expr *Other,
12185                                         const llvm::APSInt &Value,
12186                                         bool RhsConstant) {
12187   if (S.inTemplateInstantiation())
12188     return false;
12189 
12190   Expr *OriginalOther = Other;
12191 
12192   Constant = Constant->IgnoreParenImpCasts();
12193   Other = Other->IgnoreParenImpCasts();
12194 
12195   // Suppress warnings on tautological comparisons between values of the same
12196   // enumeration type. There are only two ways we could warn on this:
12197   //  - If the constant is outside the range of representable values of
12198   //    the enumeration. In such a case, we should warn about the cast
12199   //    to enumeration type, not about the comparison.
12200   //  - If the constant is the maximum / minimum in-range value. For an
12201   //    enumeratin type, such comparisons can be meaningful and useful.
12202   if (Constant->getType()->isEnumeralType() &&
12203       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12204     return false;
12205 
12206   IntRange OtherValueRange = GetExprRange(
12207       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
12208 
12209   QualType OtherT = Other->getType();
12210   if (const auto *AT = OtherT->getAs<AtomicType>())
12211     OtherT = AT->getValueType();
12212   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12213 
12214   // Special case for ObjC BOOL on targets where its a typedef for a signed char
12215   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12216   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12217                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
12218                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12219 
12220   // Whether we're treating Other as being a bool because of the form of
12221   // expression despite it having another type (typically 'int' in C).
12222   bool OtherIsBooleanDespiteType =
12223       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12224   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12225     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
12226 
12227   // Check if all values in the range of possible values of this expression
12228   // lead to the same comparison outcome.
12229   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
12230                                         Value.isUnsigned());
12231   auto Cmp = OtherPromotedValueRange.compare(Value);
12232   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12233   if (!Result)
12234     return false;
12235 
12236   // Also consider the range determined by the type alone. This allows us to
12237   // classify the warning under the proper diagnostic group.
12238   bool TautologicalTypeCompare = false;
12239   {
12240     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12241                                          Value.isUnsigned());
12242     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12243     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12244                                                        RhsConstant)) {
12245       TautologicalTypeCompare = true;
12246       Cmp = TypeCmp;
12247       Result = TypeResult;
12248     }
12249   }
12250 
12251   // Don't warn if the non-constant operand actually always evaluates to the
12252   // same value.
12253   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
12254     return false;
12255 
12256   // Suppress the diagnostic for an in-range comparison if the constant comes
12257   // from a macro or enumerator. We don't want to diagnose
12258   //
12259   //   some_long_value <= INT_MAX
12260   //
12261   // when sizeof(int) == sizeof(long).
12262   bool InRange = Cmp & PromotedRange::InRangeFlag;
12263   if (InRange && IsEnumConstOrFromMacro(S, Constant))
12264     return false;
12265 
12266   // A comparison of an unsigned bit-field against 0 is really a type problem,
12267   // even though at the type level the bit-field might promote to 'signed int'.
12268   if (Other->refersToBitField() && InRange && Value == 0 &&
12269       Other->getType()->isUnsignedIntegerOrEnumerationType())
12270     TautologicalTypeCompare = true;
12271 
12272   // If this is a comparison to an enum constant, include that
12273   // constant in the diagnostic.
12274   const EnumConstantDecl *ED = nullptr;
12275   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
12276     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12277 
12278   // Should be enough for uint128 (39 decimal digits)
12279   SmallString<64> PrettySourceValue;
12280   llvm::raw_svector_ostream OS(PrettySourceValue);
12281   if (ED) {
12282     OS << '\'' << *ED << "' (" << Value << ")";
12283   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12284                Constant->IgnoreParenImpCasts())) {
12285     OS << (BL->getValue() ? "YES" : "NO");
12286   } else {
12287     OS << Value;
12288   }
12289 
12290   if (!TautologicalTypeCompare) {
12291     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12292         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
12293         << E->getOpcodeStr() << OS.str() << *Result
12294         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12295     return true;
12296   }
12297 
12298   if (IsObjCSignedCharBool) {
12299     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12300                           S.PDiag(diag::warn_tautological_compare_objc_bool)
12301                               << OS.str() << *Result);
12302     return true;
12303   }
12304 
12305   // FIXME: We use a somewhat different formatting for the in-range cases and
12306   // cases involving boolean values for historical reasons. We should pick a
12307   // consistent way of presenting these diagnostics.
12308   if (!InRange || Other->isKnownToHaveBooleanValue()) {
12309 
12310     S.DiagRuntimeBehavior(
12311         E->getOperatorLoc(), E,
12312         S.PDiag(!InRange ? diag::warn_out_of_range_compare
12313                          : diag::warn_tautological_bool_compare)
12314             << OS.str() << classifyConstantValue(Constant) << OtherT
12315             << OtherIsBooleanDespiteType << *Result
12316             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12317   } else {
12318     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12319     unsigned Diag =
12320         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12321             ? (HasEnumType(OriginalOther)
12322                    ? diag::warn_unsigned_enum_always_true_comparison
12323                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12324                               : diag::warn_unsigned_always_true_comparison)
12325             : diag::warn_tautological_constant_compare;
12326 
12327     S.Diag(E->getOperatorLoc(), Diag)
12328         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12329         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12330   }
12331 
12332   return true;
12333 }
12334 
12335 /// Analyze the operands of the given comparison.  Implements the
12336 /// fallback case from AnalyzeComparison.
12337 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12338   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12339   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12340 }
12341 
12342 /// Implements -Wsign-compare.
12343 ///
12344 /// \param E the binary operator to check for warnings
12345 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12346   // The type the comparison is being performed in.
12347   QualType T = E->getLHS()->getType();
12348 
12349   // Only analyze comparison operators where both sides have been converted to
12350   // the same type.
12351   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12352     return AnalyzeImpConvsInComparison(S, E);
12353 
12354   // Don't analyze value-dependent comparisons directly.
12355   if (E->isValueDependent())
12356     return AnalyzeImpConvsInComparison(S, E);
12357 
12358   Expr *LHS = E->getLHS();
12359   Expr *RHS = E->getRHS();
12360 
12361   if (T->isIntegralType(S.Context)) {
12362     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
12363     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
12364 
12365     // We don't care about expressions whose result is a constant.
12366     if (RHSValue && LHSValue)
12367       return AnalyzeImpConvsInComparison(S, E);
12368 
12369     // We only care about expressions where just one side is literal
12370     if ((bool)RHSValue ^ (bool)LHSValue) {
12371       // Is the constant on the RHS or LHS?
12372       const bool RhsConstant = (bool)RHSValue;
12373       Expr *Const = RhsConstant ? RHS : LHS;
12374       Expr *Other = RhsConstant ? LHS : RHS;
12375       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12376 
12377       // Check whether an integer constant comparison results in a value
12378       // of 'true' or 'false'.
12379       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12380         return AnalyzeImpConvsInComparison(S, E);
12381     }
12382   }
12383 
12384   if (!T->hasUnsignedIntegerRepresentation()) {
12385     // We don't do anything special if this isn't an unsigned integral
12386     // comparison:  we're only interested in integral comparisons, and
12387     // signed comparisons only happen in cases we don't care to warn about.
12388     return AnalyzeImpConvsInComparison(S, E);
12389   }
12390 
12391   LHS = LHS->IgnoreParenImpCasts();
12392   RHS = RHS->IgnoreParenImpCasts();
12393 
12394   if (!S.getLangOpts().CPlusPlus) {
12395     // Avoid warning about comparison of integers with different signs when
12396     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12397     // the type of `E`.
12398     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12399       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12400     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12401       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12402   }
12403 
12404   // Check to see if one of the (unmodified) operands is of different
12405   // signedness.
12406   Expr *signedOperand, *unsignedOperand;
12407   if (LHS->getType()->hasSignedIntegerRepresentation()) {
12408     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12409            "unsigned comparison between two signed integer expressions?");
12410     signedOperand = LHS;
12411     unsignedOperand = RHS;
12412   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12413     signedOperand = RHS;
12414     unsignedOperand = LHS;
12415   } else {
12416     return AnalyzeImpConvsInComparison(S, E);
12417   }
12418 
12419   // Otherwise, calculate the effective range of the signed operand.
12420   IntRange signedRange = GetExprRange(
12421       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
12422 
12423   // Go ahead and analyze implicit conversions in the operands.  Note
12424   // that we skip the implicit conversions on both sides.
12425   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
12426   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
12427 
12428   // If the signed range is non-negative, -Wsign-compare won't fire.
12429   if (signedRange.NonNegative)
12430     return;
12431 
12432   // For (in)equality comparisons, if the unsigned operand is a
12433   // constant which cannot collide with a overflowed signed operand,
12434   // then reinterpreting the signed operand as unsigned will not
12435   // change the result of the comparison.
12436   if (E->isEqualityOp()) {
12437     unsigned comparisonWidth = S.Context.getIntWidth(T);
12438     IntRange unsignedRange =
12439         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
12440                      /*Approximate*/ true);
12441 
12442     // We should never be unable to prove that the unsigned operand is
12443     // non-negative.
12444     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
12445 
12446     if (unsignedRange.Width < comparisonWidth)
12447       return;
12448   }
12449 
12450   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12451                         S.PDiag(diag::warn_mixed_sign_comparison)
12452                             << LHS->getType() << RHS->getType()
12453                             << LHS->getSourceRange() << RHS->getSourceRange());
12454 }
12455 
12456 /// Analyzes an attempt to assign the given value to a bitfield.
12457 ///
12458 /// Returns true if there was something fishy about the attempt.
12459 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12460                                       SourceLocation InitLoc) {
12461   assert(Bitfield->isBitField());
12462   if (Bitfield->isInvalidDecl())
12463     return false;
12464 
12465   // White-list bool bitfields.
12466   QualType BitfieldType = Bitfield->getType();
12467   if (BitfieldType->isBooleanType())
12468      return false;
12469 
12470   if (BitfieldType->isEnumeralType()) {
12471     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12472     // If the underlying enum type was not explicitly specified as an unsigned
12473     // type and the enum contain only positive values, MSVC++ will cause an
12474     // inconsistency by storing this as a signed type.
12475     if (S.getLangOpts().CPlusPlus11 &&
12476         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12477         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12478         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12479       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12480           << BitfieldEnumDecl;
12481     }
12482   }
12483 
12484   if (Bitfield->getType()->isBooleanType())
12485     return false;
12486 
12487   // Ignore value- or type-dependent expressions.
12488   if (Bitfield->getBitWidth()->isValueDependent() ||
12489       Bitfield->getBitWidth()->isTypeDependent() ||
12490       Init->isValueDependent() ||
12491       Init->isTypeDependent())
12492     return false;
12493 
12494   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12495   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12496 
12497   Expr::EvalResult Result;
12498   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12499                                    Expr::SE_AllowSideEffects)) {
12500     // The RHS is not constant.  If the RHS has an enum type, make sure the
12501     // bitfield is wide enough to hold all the values of the enum without
12502     // truncation.
12503     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12504       EnumDecl *ED = EnumTy->getDecl();
12505       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12506 
12507       // Enum types are implicitly signed on Windows, so check if there are any
12508       // negative enumerators to see if the enum was intended to be signed or
12509       // not.
12510       bool SignedEnum = ED->getNumNegativeBits() > 0;
12511 
12512       // Check for surprising sign changes when assigning enum values to a
12513       // bitfield of different signedness.  If the bitfield is signed and we
12514       // have exactly the right number of bits to store this unsigned enum,
12515       // suggest changing the enum to an unsigned type. This typically happens
12516       // on Windows where unfixed enums always use an underlying type of 'int'.
12517       unsigned DiagID = 0;
12518       if (SignedEnum && !SignedBitfield) {
12519         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12520       } else if (SignedBitfield && !SignedEnum &&
12521                  ED->getNumPositiveBits() == FieldWidth) {
12522         DiagID = diag::warn_signed_bitfield_enum_conversion;
12523       }
12524 
12525       if (DiagID) {
12526         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12527         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12528         SourceRange TypeRange =
12529             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12530         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12531             << SignedEnum << TypeRange;
12532       }
12533 
12534       // Compute the required bitwidth. If the enum has negative values, we need
12535       // one more bit than the normal number of positive bits to represent the
12536       // sign bit.
12537       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12538                                                   ED->getNumNegativeBits())
12539                                        : ED->getNumPositiveBits();
12540 
12541       // Check the bitwidth.
12542       if (BitsNeeded > FieldWidth) {
12543         Expr *WidthExpr = Bitfield->getBitWidth();
12544         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12545             << Bitfield << ED;
12546         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12547             << BitsNeeded << ED << WidthExpr->getSourceRange();
12548       }
12549     }
12550 
12551     return false;
12552   }
12553 
12554   llvm::APSInt Value = Result.Val.getInt();
12555 
12556   unsigned OriginalWidth = Value.getBitWidth();
12557 
12558   if (!Value.isSigned() || Value.isNegative())
12559     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12560       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12561         OriginalWidth = Value.getMinSignedBits();
12562 
12563   if (OriginalWidth <= FieldWidth)
12564     return false;
12565 
12566   // Compute the value which the bitfield will contain.
12567   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12568   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12569 
12570   // Check whether the stored value is equal to the original value.
12571   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12572   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12573     return false;
12574 
12575   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12576   // therefore don't strictly fit into a signed bitfield of width 1.
12577   if (FieldWidth == 1 && Value == 1)
12578     return false;
12579 
12580   std::string PrettyValue = toString(Value, 10);
12581   std::string PrettyTrunc = toString(TruncatedValue, 10);
12582 
12583   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12584     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12585     << Init->getSourceRange();
12586 
12587   return true;
12588 }
12589 
12590 /// Analyze the given simple or compound assignment for warning-worthy
12591 /// operations.
12592 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12593   // Just recurse on the LHS.
12594   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12595 
12596   // We want to recurse on the RHS as normal unless we're assigning to
12597   // a bitfield.
12598   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12599     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12600                                   E->getOperatorLoc())) {
12601       // Recurse, ignoring any implicit conversions on the RHS.
12602       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12603                                         E->getOperatorLoc());
12604     }
12605   }
12606 
12607   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12608 
12609   // Diagnose implicitly sequentially-consistent atomic assignment.
12610   if (E->getLHS()->getType()->isAtomicType())
12611     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12612 }
12613 
12614 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12615 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12616                             SourceLocation CContext, unsigned diag,
12617                             bool pruneControlFlow = false) {
12618   if (pruneControlFlow) {
12619     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12620                           S.PDiag(diag)
12621                               << SourceType << T << E->getSourceRange()
12622                               << SourceRange(CContext));
12623     return;
12624   }
12625   S.Diag(E->getExprLoc(), diag)
12626     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12627 }
12628 
12629 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12630 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12631                             SourceLocation CContext,
12632                             unsigned diag, bool pruneControlFlow = false) {
12633   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12634 }
12635 
12636 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12637   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12638       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12639 }
12640 
12641 static void adornObjCBoolConversionDiagWithTernaryFixit(
12642     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12643   Expr *Ignored = SourceExpr->IgnoreImplicit();
12644   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12645     Ignored = OVE->getSourceExpr();
12646   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12647                      isa<BinaryOperator>(Ignored) ||
12648                      isa<CXXOperatorCallExpr>(Ignored);
12649   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12650   if (NeedsParens)
12651     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12652             << FixItHint::CreateInsertion(EndLoc, ")");
12653   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12654 }
12655 
12656 /// Diagnose an implicit cast from a floating point value to an integer value.
12657 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12658                                     SourceLocation CContext) {
12659   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12660   const bool PruneWarnings = S.inTemplateInstantiation();
12661 
12662   Expr *InnerE = E->IgnoreParenImpCasts();
12663   // We also want to warn on, e.g., "int i = -1.234"
12664   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12665     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12666       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12667 
12668   const bool IsLiteral =
12669       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12670 
12671   llvm::APFloat Value(0.0);
12672   bool IsConstant =
12673     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12674   if (!IsConstant) {
12675     if (isObjCSignedCharBool(S, T)) {
12676       return adornObjCBoolConversionDiagWithTernaryFixit(
12677           S, E,
12678           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12679               << E->getType());
12680     }
12681 
12682     return DiagnoseImpCast(S, E, T, CContext,
12683                            diag::warn_impcast_float_integer, PruneWarnings);
12684   }
12685 
12686   bool isExact = false;
12687 
12688   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12689                             T->hasUnsignedIntegerRepresentation());
12690   llvm::APFloat::opStatus Result = Value.convertToInteger(
12691       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12692 
12693   // FIXME: Force the precision of the source value down so we don't print
12694   // digits which are usually useless (we don't really care here if we
12695   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12696   // would automatically print the shortest representation, but it's a bit
12697   // tricky to implement.
12698   SmallString<16> PrettySourceValue;
12699   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12700   precision = (precision * 59 + 195) / 196;
12701   Value.toString(PrettySourceValue, precision);
12702 
12703   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12704     return adornObjCBoolConversionDiagWithTernaryFixit(
12705         S, E,
12706         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12707             << PrettySourceValue);
12708   }
12709 
12710   if (Result == llvm::APFloat::opOK && isExact) {
12711     if (IsLiteral) return;
12712     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12713                            PruneWarnings);
12714   }
12715 
12716   // Conversion of a floating-point value to a non-bool integer where the
12717   // integral part cannot be represented by the integer type is undefined.
12718   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12719     return DiagnoseImpCast(
12720         S, E, T, CContext,
12721         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12722                   : diag::warn_impcast_float_to_integer_out_of_range,
12723         PruneWarnings);
12724 
12725   unsigned DiagID = 0;
12726   if (IsLiteral) {
12727     // Warn on floating point literal to integer.
12728     DiagID = diag::warn_impcast_literal_float_to_integer;
12729   } else if (IntegerValue == 0) {
12730     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12731       return DiagnoseImpCast(S, E, T, CContext,
12732                              diag::warn_impcast_float_integer, PruneWarnings);
12733     }
12734     // Warn on non-zero to zero conversion.
12735     DiagID = diag::warn_impcast_float_to_integer_zero;
12736   } else {
12737     if (IntegerValue.isUnsigned()) {
12738       if (!IntegerValue.isMaxValue()) {
12739         return DiagnoseImpCast(S, E, T, CContext,
12740                                diag::warn_impcast_float_integer, PruneWarnings);
12741       }
12742     } else {  // IntegerValue.isSigned()
12743       if (!IntegerValue.isMaxSignedValue() &&
12744           !IntegerValue.isMinSignedValue()) {
12745         return DiagnoseImpCast(S, E, T, CContext,
12746                                diag::warn_impcast_float_integer, PruneWarnings);
12747       }
12748     }
12749     // Warn on evaluatable floating point expression to integer conversion.
12750     DiagID = diag::warn_impcast_float_to_integer;
12751   }
12752 
12753   SmallString<16> PrettyTargetValue;
12754   if (IsBool)
12755     PrettyTargetValue = Value.isZero() ? "false" : "true";
12756   else
12757     IntegerValue.toString(PrettyTargetValue);
12758 
12759   if (PruneWarnings) {
12760     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12761                           S.PDiag(DiagID)
12762                               << E->getType() << T.getUnqualifiedType()
12763                               << PrettySourceValue << PrettyTargetValue
12764                               << E->getSourceRange() << SourceRange(CContext));
12765   } else {
12766     S.Diag(E->getExprLoc(), DiagID)
12767         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12768         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12769   }
12770 }
12771 
12772 /// Analyze the given compound assignment for the possible losing of
12773 /// floating-point precision.
12774 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12775   assert(isa<CompoundAssignOperator>(E) &&
12776          "Must be compound assignment operation");
12777   // Recurse on the LHS and RHS in here
12778   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12779   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12780 
12781   if (E->getLHS()->getType()->isAtomicType())
12782     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12783 
12784   // Now check the outermost expression
12785   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12786   const auto *RBT = cast<CompoundAssignOperator>(E)
12787                         ->getComputationResultType()
12788                         ->getAs<BuiltinType>();
12789 
12790   // The below checks assume source is floating point.
12791   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12792 
12793   // If source is floating point but target is an integer.
12794   if (ResultBT->isInteger())
12795     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12796                            E->getExprLoc(), diag::warn_impcast_float_integer);
12797 
12798   if (!ResultBT->isFloatingPoint())
12799     return;
12800 
12801   // If both source and target are floating points, warn about losing precision.
12802   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12803       QualType(ResultBT, 0), QualType(RBT, 0));
12804   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12805     // warn about dropping FP rank.
12806     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12807                     diag::warn_impcast_float_result_precision);
12808 }
12809 
12810 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12811                                       IntRange Range) {
12812   if (!Range.Width) return "0";
12813 
12814   llvm::APSInt ValueInRange = Value;
12815   ValueInRange.setIsSigned(!Range.NonNegative);
12816   ValueInRange = ValueInRange.trunc(Range.Width);
12817   return toString(ValueInRange, 10);
12818 }
12819 
12820 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12821   if (!isa<ImplicitCastExpr>(Ex))
12822     return false;
12823 
12824   Expr *InnerE = Ex->IgnoreParenImpCasts();
12825   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12826   const Type *Source =
12827     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12828   if (Target->isDependentType())
12829     return false;
12830 
12831   const BuiltinType *FloatCandidateBT =
12832     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12833   const Type *BoolCandidateType = ToBool ? Target : Source;
12834 
12835   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12836           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12837 }
12838 
12839 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12840                                              SourceLocation CC) {
12841   unsigned NumArgs = TheCall->getNumArgs();
12842   for (unsigned i = 0; i < NumArgs; ++i) {
12843     Expr *CurrA = TheCall->getArg(i);
12844     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12845       continue;
12846 
12847     bool IsSwapped = ((i > 0) &&
12848         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12849     IsSwapped |= ((i < (NumArgs - 1)) &&
12850         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12851     if (IsSwapped) {
12852       // Warn on this floating-point to bool conversion.
12853       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12854                       CurrA->getType(), CC,
12855                       diag::warn_impcast_floating_point_to_bool);
12856     }
12857   }
12858 }
12859 
12860 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12861                                    SourceLocation CC) {
12862   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12863                         E->getExprLoc()))
12864     return;
12865 
12866   // Don't warn on functions which have return type nullptr_t.
12867   if (isa<CallExpr>(E))
12868     return;
12869 
12870   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12871   const Expr::NullPointerConstantKind NullKind =
12872       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12873   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12874     return;
12875 
12876   // Return if target type is a safe conversion.
12877   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12878       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12879     return;
12880 
12881   SourceLocation Loc = E->getSourceRange().getBegin();
12882 
12883   // Venture through the macro stacks to get to the source of macro arguments.
12884   // The new location is a better location than the complete location that was
12885   // passed in.
12886   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12887   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12888 
12889   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12890   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12891     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12892         Loc, S.SourceMgr, S.getLangOpts());
12893     if (MacroName == "NULL")
12894       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12895   }
12896 
12897   // Only warn if the null and context location are in the same macro expansion.
12898   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12899     return;
12900 
12901   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12902       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12903       << FixItHint::CreateReplacement(Loc,
12904                                       S.getFixItZeroLiteralForType(T, Loc));
12905 }
12906 
12907 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12908                                   ObjCArrayLiteral *ArrayLiteral);
12909 
12910 static void
12911 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12912                            ObjCDictionaryLiteral *DictionaryLiteral);
12913 
12914 /// Check a single element within a collection literal against the
12915 /// target element type.
12916 static void checkObjCCollectionLiteralElement(Sema &S,
12917                                               QualType TargetElementType,
12918                                               Expr *Element,
12919                                               unsigned ElementKind) {
12920   // Skip a bitcast to 'id' or qualified 'id'.
12921   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12922     if (ICE->getCastKind() == CK_BitCast &&
12923         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12924       Element = ICE->getSubExpr();
12925   }
12926 
12927   QualType ElementType = Element->getType();
12928   ExprResult ElementResult(Element);
12929   if (ElementType->getAs<ObjCObjectPointerType>() &&
12930       S.CheckSingleAssignmentConstraints(TargetElementType,
12931                                          ElementResult,
12932                                          false, false)
12933         != Sema::Compatible) {
12934     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12935         << ElementType << ElementKind << TargetElementType
12936         << Element->getSourceRange();
12937   }
12938 
12939   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12940     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12941   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12942     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12943 }
12944 
12945 /// Check an Objective-C array literal being converted to the given
12946 /// target type.
12947 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12948                                   ObjCArrayLiteral *ArrayLiteral) {
12949   if (!S.NSArrayDecl)
12950     return;
12951 
12952   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12953   if (!TargetObjCPtr)
12954     return;
12955 
12956   if (TargetObjCPtr->isUnspecialized() ||
12957       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12958         != S.NSArrayDecl->getCanonicalDecl())
12959     return;
12960 
12961   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12962   if (TypeArgs.size() != 1)
12963     return;
12964 
12965   QualType TargetElementType = TypeArgs[0];
12966   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12967     checkObjCCollectionLiteralElement(S, TargetElementType,
12968                                       ArrayLiteral->getElement(I),
12969                                       0);
12970   }
12971 }
12972 
12973 /// Check an Objective-C dictionary literal being converted to the given
12974 /// target type.
12975 static void
12976 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12977                            ObjCDictionaryLiteral *DictionaryLiteral) {
12978   if (!S.NSDictionaryDecl)
12979     return;
12980 
12981   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12982   if (!TargetObjCPtr)
12983     return;
12984 
12985   if (TargetObjCPtr->isUnspecialized() ||
12986       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12987         != S.NSDictionaryDecl->getCanonicalDecl())
12988     return;
12989 
12990   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12991   if (TypeArgs.size() != 2)
12992     return;
12993 
12994   QualType TargetKeyType = TypeArgs[0];
12995   QualType TargetObjectType = TypeArgs[1];
12996   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12997     auto Element = DictionaryLiteral->getKeyValueElement(I);
12998     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12999     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
13000   }
13001 }
13002 
13003 // Helper function to filter out cases for constant width constant conversion.
13004 // Don't warn on char array initialization or for non-decimal values.
13005 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
13006                                           SourceLocation CC) {
13007   // If initializing from a constant, and the constant starts with '0',
13008   // then it is a binary, octal, or hexadecimal.  Allow these constants
13009   // to fill all the bits, even if there is a sign change.
13010   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
13011     const char FirstLiteralCharacter =
13012         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
13013     if (FirstLiteralCharacter == '0')
13014       return false;
13015   }
13016 
13017   // If the CC location points to a '{', and the type is char, then assume
13018   // assume it is an array initialization.
13019   if (CC.isValid() && T->isCharType()) {
13020     const char FirstContextCharacter =
13021         S.getSourceManager().getCharacterData(CC)[0];
13022     if (FirstContextCharacter == '{')
13023       return false;
13024   }
13025 
13026   return true;
13027 }
13028 
13029 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
13030   const auto *IL = dyn_cast<IntegerLiteral>(E);
13031   if (!IL) {
13032     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
13033       if (UO->getOpcode() == UO_Minus)
13034         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
13035     }
13036   }
13037 
13038   return IL;
13039 }
13040 
13041 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
13042   E = E->IgnoreParenImpCasts();
13043   SourceLocation ExprLoc = E->getExprLoc();
13044 
13045   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
13046     BinaryOperator::Opcode Opc = BO->getOpcode();
13047     Expr::EvalResult Result;
13048     // Do not diagnose unsigned shifts.
13049     if (Opc == BO_Shl) {
13050       const auto *LHS = getIntegerLiteral(BO->getLHS());
13051       const auto *RHS = getIntegerLiteral(BO->getRHS());
13052       if (LHS && LHS->getValue() == 0)
13053         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
13054       else if (!E->isValueDependent() && LHS && RHS &&
13055                RHS->getValue().isNonNegative() &&
13056                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
13057         S.Diag(ExprLoc, diag::warn_left_shift_always)
13058             << (Result.Val.getInt() != 0);
13059       else if (E->getType()->isSignedIntegerType())
13060         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
13061     }
13062   }
13063 
13064   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
13065     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
13066     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
13067     if (!LHS || !RHS)
13068       return;
13069     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13070         (RHS->getValue() == 0 || RHS->getValue() == 1))
13071       // Do not diagnose common idioms.
13072       return;
13073     if (LHS->getValue() != 0 && RHS->getValue() != 0)
13074       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
13075   }
13076 }
13077 
13078 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
13079                                     SourceLocation CC,
13080                                     bool *ICContext = nullptr,
13081                                     bool IsListInit = false) {
13082   if (E->isTypeDependent() || E->isValueDependent()) return;
13083 
13084   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
13085   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
13086   if (Source == Target) return;
13087   if (Target->isDependentType()) return;
13088 
13089   // If the conversion context location is invalid don't complain. We also
13090   // don't want to emit a warning if the issue occurs from the expansion of
13091   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13092   // delay this check as long as possible. Once we detect we are in that
13093   // scenario, we just return.
13094   if (CC.isInvalid())
13095     return;
13096 
13097   if (Source->isAtomicType())
13098     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
13099 
13100   // Diagnose implicit casts to bool.
13101   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
13102     if (isa<StringLiteral>(E))
13103       // Warn on string literal to bool.  Checks for string literals in logical
13104       // and expressions, for instance, assert(0 && "error here"), are
13105       // prevented by a check in AnalyzeImplicitConversions().
13106       return DiagnoseImpCast(S, E, T, CC,
13107                              diag::warn_impcast_string_literal_to_bool);
13108     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
13109         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
13110       // This covers the literal expressions that evaluate to Objective-C
13111       // objects.
13112       return DiagnoseImpCast(S, E, T, CC,
13113                              diag::warn_impcast_objective_c_literal_to_bool);
13114     }
13115     if (Source->isPointerType() || Source->canDecayToPointerType()) {
13116       // Warn on pointer to bool conversion that is always true.
13117       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
13118                                      SourceRange(CC));
13119     }
13120   }
13121 
13122   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13123   // is a typedef for signed char (macOS), then that constant value has to be 1
13124   // or 0.
13125   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
13126     Expr::EvalResult Result;
13127     if (E->EvaluateAsInt(Result, S.getASTContext(),
13128                          Expr::SE_AllowSideEffects)) {
13129       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13130         adornObjCBoolConversionDiagWithTernaryFixit(
13131             S, E,
13132             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13133                 << toString(Result.Val.getInt(), 10));
13134       }
13135       return;
13136     }
13137   }
13138 
13139   // Check implicit casts from Objective-C collection literals to specialized
13140   // collection types, e.g., NSArray<NSString *> *.
13141   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13142     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
13143   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13144     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
13145 
13146   // Strip vector types.
13147   if (isa<VectorType>(Source)) {
13148     if (Target->isVLSTBuiltinType() &&
13149         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
13150                                          QualType(Source, 0)) ||
13151          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
13152                                             QualType(Source, 0))))
13153       return;
13154 
13155     if (!isa<VectorType>(Target)) {
13156       if (S.SourceMgr.isInSystemMacro(CC))
13157         return;
13158       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
13159     }
13160 
13161     // If the vector cast is cast between two vectors of the same size, it is
13162     // a bitcast, not a conversion.
13163     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
13164       return;
13165 
13166     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13167     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13168   }
13169   if (auto VecTy = dyn_cast<VectorType>(Target))
13170     Target = VecTy->getElementType().getTypePtr();
13171 
13172   // Strip complex types.
13173   if (isa<ComplexType>(Source)) {
13174     if (!isa<ComplexType>(Target)) {
13175       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13176         return;
13177 
13178       return DiagnoseImpCast(S, E, T, CC,
13179                              S.getLangOpts().CPlusPlus
13180                                  ? diag::err_impcast_complex_scalar
13181                                  : diag::warn_impcast_complex_scalar);
13182     }
13183 
13184     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13185     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13186   }
13187 
13188   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13189   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13190 
13191   // If the source is floating point...
13192   if (SourceBT && SourceBT->isFloatingPoint()) {
13193     // ...and the target is floating point...
13194     if (TargetBT && TargetBT->isFloatingPoint()) {
13195       // ...then warn if we're dropping FP rank.
13196 
13197       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
13198           QualType(SourceBT, 0), QualType(TargetBT, 0));
13199       if (Order > 0) {
13200         // Don't warn about float constants that are precisely
13201         // representable in the target type.
13202         Expr::EvalResult result;
13203         if (E->EvaluateAsRValue(result, S.Context)) {
13204           // Value might be a float, a float vector, or a float complex.
13205           if (IsSameFloatAfterCast(result.Val,
13206                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13207                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13208             return;
13209         }
13210 
13211         if (S.SourceMgr.isInSystemMacro(CC))
13212           return;
13213 
13214         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
13215       }
13216       // ... or possibly if we're increasing rank, too
13217       else if (Order < 0) {
13218         if (S.SourceMgr.isInSystemMacro(CC))
13219           return;
13220 
13221         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
13222       }
13223       return;
13224     }
13225 
13226     // If the target is integral, always warn.
13227     if (TargetBT && TargetBT->isInteger()) {
13228       if (S.SourceMgr.isInSystemMacro(CC))
13229         return;
13230 
13231       DiagnoseFloatingImpCast(S, E, T, CC);
13232     }
13233 
13234     // Detect the case where a call result is converted from floating-point to
13235     // to bool, and the final argument to the call is converted from bool, to
13236     // discover this typo:
13237     //
13238     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
13239     //
13240     // FIXME: This is an incredibly special case; is there some more general
13241     // way to detect this class of misplaced-parentheses bug?
13242     if (Target->isBooleanType() && isa<CallExpr>(E)) {
13243       // Check last argument of function call to see if it is an
13244       // implicit cast from a type matching the type the result
13245       // is being cast to.
13246       CallExpr *CEx = cast<CallExpr>(E);
13247       if (unsigned NumArgs = CEx->getNumArgs()) {
13248         Expr *LastA = CEx->getArg(NumArgs - 1);
13249         Expr *InnerE = LastA->IgnoreParenImpCasts();
13250         if (isa<ImplicitCastExpr>(LastA) &&
13251             InnerE->getType()->isBooleanType()) {
13252           // Warn on this floating-point to bool conversion
13253           DiagnoseImpCast(S, E, T, CC,
13254                           diag::warn_impcast_floating_point_to_bool);
13255         }
13256       }
13257     }
13258     return;
13259   }
13260 
13261   // Valid casts involving fixed point types should be accounted for here.
13262   if (Source->isFixedPointType()) {
13263     if (Target->isUnsaturatedFixedPointType()) {
13264       Expr::EvalResult Result;
13265       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
13266                                   S.isConstantEvaluated())) {
13267         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13268         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
13269         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
13270         if (Value > MaxVal || Value < MinVal) {
13271           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13272                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13273                                     << Value.toString() << T
13274                                     << E->getSourceRange()
13275                                     << clang::SourceRange(CC));
13276           return;
13277         }
13278       }
13279     } else if (Target->isIntegerType()) {
13280       Expr::EvalResult Result;
13281       if (!S.isConstantEvaluated() &&
13282           E->EvaluateAsFixedPoint(Result, S.Context,
13283                                   Expr::SE_AllowSideEffects)) {
13284         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13285 
13286         bool Overflowed;
13287         llvm::APSInt IntResult = FXResult.convertToInt(
13288             S.Context.getIntWidth(T),
13289             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
13290 
13291         if (Overflowed) {
13292           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13293                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13294                                     << FXResult.toString() << T
13295                                     << E->getSourceRange()
13296                                     << clang::SourceRange(CC));
13297           return;
13298         }
13299       }
13300     }
13301   } else if (Target->isUnsaturatedFixedPointType()) {
13302     if (Source->isIntegerType()) {
13303       Expr::EvalResult Result;
13304       if (!S.isConstantEvaluated() &&
13305           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
13306         llvm::APSInt Value = Result.Val.getInt();
13307 
13308         bool Overflowed;
13309         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13310             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
13311 
13312         if (Overflowed) {
13313           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13314                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13315                                     << toString(Value, /*Radix=*/10) << T
13316                                     << E->getSourceRange()
13317                                     << clang::SourceRange(CC));
13318           return;
13319         }
13320       }
13321     }
13322   }
13323 
13324   // If we are casting an integer type to a floating point type without
13325   // initialization-list syntax, we might lose accuracy if the floating
13326   // point type has a narrower significand than the integer type.
13327   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13328       TargetBT->isFloatingType() && !IsListInit) {
13329     // Determine the number of precision bits in the source integer type.
13330     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
13331                                         /*Approximate*/ true);
13332     unsigned int SourcePrecision = SourceRange.Width;
13333 
13334     // Determine the number of precision bits in the
13335     // target floating point type.
13336     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13337         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13338 
13339     if (SourcePrecision > 0 && TargetPrecision > 0 &&
13340         SourcePrecision > TargetPrecision) {
13341 
13342       if (Optional<llvm::APSInt> SourceInt =
13343               E->getIntegerConstantExpr(S.Context)) {
13344         // If the source integer is a constant, convert it to the target
13345         // floating point type. Issue a warning if the value changes
13346         // during the whole conversion.
13347         llvm::APFloat TargetFloatValue(
13348             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13349         llvm::APFloat::opStatus ConversionStatus =
13350             TargetFloatValue.convertFromAPInt(
13351                 *SourceInt, SourceBT->isSignedInteger(),
13352                 llvm::APFloat::rmNearestTiesToEven);
13353 
13354         if (ConversionStatus != llvm::APFloat::opOK) {
13355           SmallString<32> PrettySourceValue;
13356           SourceInt->toString(PrettySourceValue, 10);
13357           SmallString<32> PrettyTargetValue;
13358           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13359 
13360           S.DiagRuntimeBehavior(
13361               E->getExprLoc(), E,
13362               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
13363                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
13364                   << E->getSourceRange() << clang::SourceRange(CC));
13365         }
13366       } else {
13367         // Otherwise, the implicit conversion may lose precision.
13368         DiagnoseImpCast(S, E, T, CC,
13369                         diag::warn_impcast_integer_float_precision);
13370       }
13371     }
13372   }
13373 
13374   DiagnoseNullConversion(S, E, T, CC);
13375 
13376   S.DiscardMisalignedMemberAddress(Target, E);
13377 
13378   if (Target->isBooleanType())
13379     DiagnoseIntInBoolContext(S, E);
13380 
13381   if (!Source->isIntegerType() || !Target->isIntegerType())
13382     return;
13383 
13384   // TODO: remove this early return once the false positives for constant->bool
13385   // in templates, macros, etc, are reduced or removed.
13386   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13387     return;
13388 
13389   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
13390       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13391     return adornObjCBoolConversionDiagWithTernaryFixit(
13392         S, E,
13393         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13394             << E->getType());
13395   }
13396 
13397   IntRange SourceTypeRange =
13398       IntRange::forTargetOfCanonicalType(S.Context, Source);
13399   IntRange LikelySourceRange =
13400       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
13401   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
13402 
13403   if (LikelySourceRange.Width > TargetRange.Width) {
13404     // If the source is a constant, use a default-on diagnostic.
13405     // TODO: this should happen for bitfield stores, too.
13406     Expr::EvalResult Result;
13407     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
13408                          S.isConstantEvaluated())) {
13409       llvm::APSInt Value(32);
13410       Value = Result.Val.getInt();
13411 
13412       if (S.SourceMgr.isInSystemMacro(CC))
13413         return;
13414 
13415       std::string PrettySourceValue = toString(Value, 10);
13416       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13417 
13418       S.DiagRuntimeBehavior(
13419           E->getExprLoc(), E,
13420           S.PDiag(diag::warn_impcast_integer_precision_constant)
13421               << PrettySourceValue << PrettyTargetValue << E->getType() << T
13422               << E->getSourceRange() << SourceRange(CC));
13423       return;
13424     }
13425 
13426     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13427     if (S.SourceMgr.isInSystemMacro(CC))
13428       return;
13429 
13430     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
13431       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
13432                              /* pruneControlFlow */ true);
13433     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
13434   }
13435 
13436   if (TargetRange.Width > SourceTypeRange.Width) {
13437     if (auto *UO = dyn_cast<UnaryOperator>(E))
13438       if (UO->getOpcode() == UO_Minus)
13439         if (Source->isUnsignedIntegerType()) {
13440           if (Target->isUnsignedIntegerType())
13441             return DiagnoseImpCast(S, E, T, CC,
13442                                    diag::warn_impcast_high_order_zero_bits);
13443           if (Target->isSignedIntegerType())
13444             return DiagnoseImpCast(S, E, T, CC,
13445                                    diag::warn_impcast_nonnegative_result);
13446         }
13447   }
13448 
13449   if (TargetRange.Width == LikelySourceRange.Width &&
13450       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13451       Source->isSignedIntegerType()) {
13452     // Warn when doing a signed to signed conversion, warn if the positive
13453     // source value is exactly the width of the target type, which will
13454     // cause a negative value to be stored.
13455 
13456     Expr::EvalResult Result;
13457     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
13458         !S.SourceMgr.isInSystemMacro(CC)) {
13459       llvm::APSInt Value = Result.Val.getInt();
13460       if (isSameWidthConstantConversion(S, E, T, CC)) {
13461         std::string PrettySourceValue = toString(Value, 10);
13462         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13463 
13464         S.DiagRuntimeBehavior(
13465             E->getExprLoc(), E,
13466             S.PDiag(diag::warn_impcast_integer_precision_constant)
13467                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13468                 << E->getSourceRange() << SourceRange(CC));
13469         return;
13470       }
13471     }
13472 
13473     // Fall through for non-constants to give a sign conversion warning.
13474   }
13475 
13476   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13477       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13478        LikelySourceRange.Width == TargetRange.Width)) {
13479     if (S.SourceMgr.isInSystemMacro(CC))
13480       return;
13481 
13482     unsigned DiagID = diag::warn_impcast_integer_sign;
13483 
13484     // Traditionally, gcc has warned about this under -Wsign-compare.
13485     // We also want to warn about it in -Wconversion.
13486     // So if -Wconversion is off, use a completely identical diagnostic
13487     // in the sign-compare group.
13488     // The conditional-checking code will
13489     if (ICContext) {
13490       DiagID = diag::warn_impcast_integer_sign_conditional;
13491       *ICContext = true;
13492     }
13493 
13494     return DiagnoseImpCast(S, E, T, CC, DiagID);
13495   }
13496 
13497   // Diagnose conversions between different enumeration types.
13498   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13499   // type, to give us better diagnostics.
13500   QualType SourceType = E->getType();
13501   if (!S.getLangOpts().CPlusPlus) {
13502     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13503       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13504         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13505         SourceType = S.Context.getTypeDeclType(Enum);
13506         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13507       }
13508   }
13509 
13510   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13511     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13512       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13513           TargetEnum->getDecl()->hasNameForLinkage() &&
13514           SourceEnum != TargetEnum) {
13515         if (S.SourceMgr.isInSystemMacro(CC))
13516           return;
13517 
13518         return DiagnoseImpCast(S, E, SourceType, T, CC,
13519                                diag::warn_impcast_different_enum_types);
13520       }
13521 }
13522 
13523 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13524                                      SourceLocation CC, QualType T);
13525 
13526 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13527                                     SourceLocation CC, bool &ICContext) {
13528   E = E->IgnoreParenImpCasts();
13529 
13530   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13531     return CheckConditionalOperator(S, CO, CC, T);
13532 
13533   AnalyzeImplicitConversions(S, E, CC);
13534   if (E->getType() != T)
13535     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13536 }
13537 
13538 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13539                                      SourceLocation CC, QualType T) {
13540   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13541 
13542   Expr *TrueExpr = E->getTrueExpr();
13543   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13544     TrueExpr = BCO->getCommon();
13545 
13546   bool Suspicious = false;
13547   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13548   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13549 
13550   if (T->isBooleanType())
13551     DiagnoseIntInBoolContext(S, E);
13552 
13553   // If -Wconversion would have warned about either of the candidates
13554   // for a signedness conversion to the context type...
13555   if (!Suspicious) return;
13556 
13557   // ...but it's currently ignored...
13558   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13559     return;
13560 
13561   // ...then check whether it would have warned about either of the
13562   // candidates for a signedness conversion to the condition type.
13563   if (E->getType() == T) return;
13564 
13565   Suspicious = false;
13566   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13567                           E->getType(), CC, &Suspicious);
13568   if (!Suspicious)
13569     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13570                             E->getType(), CC, &Suspicious);
13571 }
13572 
13573 /// Check conversion of given expression to boolean.
13574 /// Input argument E is a logical expression.
13575 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13576   if (S.getLangOpts().Bool)
13577     return;
13578   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13579     return;
13580   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13581 }
13582 
13583 namespace {
13584 struct AnalyzeImplicitConversionsWorkItem {
13585   Expr *E;
13586   SourceLocation CC;
13587   bool IsListInit;
13588 };
13589 }
13590 
13591 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13592 /// that should be visited are added to WorkList.
13593 static void AnalyzeImplicitConversions(
13594     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13595     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13596   Expr *OrigE = Item.E;
13597   SourceLocation CC = Item.CC;
13598 
13599   QualType T = OrigE->getType();
13600   Expr *E = OrigE->IgnoreParenImpCasts();
13601 
13602   // Propagate whether we are in a C++ list initialization expression.
13603   // If so, we do not issue warnings for implicit int-float conversion
13604   // precision loss, because C++11 narrowing already handles it.
13605   bool IsListInit = Item.IsListInit ||
13606                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13607 
13608   if (E->isTypeDependent() || E->isValueDependent())
13609     return;
13610 
13611   Expr *SourceExpr = E;
13612   // Examine, but don't traverse into the source expression of an
13613   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13614   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13615   // evaluate it in the context of checking the specific conversion to T though.
13616   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13617     if (auto *Src = OVE->getSourceExpr())
13618       SourceExpr = Src;
13619 
13620   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13621     if (UO->getOpcode() == UO_Not &&
13622         UO->getSubExpr()->isKnownToHaveBooleanValue())
13623       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13624           << OrigE->getSourceRange() << T->isBooleanType()
13625           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13626 
13627   if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
13628     if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13629         BO->getLHS()->isKnownToHaveBooleanValue() &&
13630         BO->getRHS()->isKnownToHaveBooleanValue() &&
13631         BO->getLHS()->HasSideEffects(S.Context) &&
13632         BO->getRHS()->HasSideEffects(S.Context)) {
13633       S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13634           << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange()
13635           << FixItHint::CreateReplacement(
13636                  BO->getOperatorLoc(),
13637                  (BO->getOpcode() == BO_And ? "&&" : "||"));
13638       S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13639     }
13640 
13641   // For conditional operators, we analyze the arguments as if they
13642   // were being fed directly into the output.
13643   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13644     CheckConditionalOperator(S, CO, CC, T);
13645     return;
13646   }
13647 
13648   // Check implicit argument conversions for function calls.
13649   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13650     CheckImplicitArgumentConversions(S, Call, CC);
13651 
13652   // Go ahead and check any implicit conversions we might have skipped.
13653   // The non-canonical typecheck is just an optimization;
13654   // CheckImplicitConversion will filter out dead implicit conversions.
13655   if (SourceExpr->getType() != T)
13656     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13657 
13658   // Now continue drilling into this expression.
13659 
13660   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13661     // The bound subexpressions in a PseudoObjectExpr are not reachable
13662     // as transitive children.
13663     // FIXME: Use a more uniform representation for this.
13664     for (auto *SE : POE->semantics())
13665       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13666         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13667   }
13668 
13669   // Skip past explicit casts.
13670   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13671     E = CE->getSubExpr()->IgnoreParenImpCasts();
13672     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13673       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13674     WorkList.push_back({E, CC, IsListInit});
13675     return;
13676   }
13677 
13678   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13679     // Do a somewhat different check with comparison operators.
13680     if (BO->isComparisonOp())
13681       return AnalyzeComparison(S, BO);
13682 
13683     // And with simple assignments.
13684     if (BO->getOpcode() == BO_Assign)
13685       return AnalyzeAssignment(S, BO);
13686     // And with compound assignments.
13687     if (BO->isAssignmentOp())
13688       return AnalyzeCompoundAssignment(S, BO);
13689   }
13690 
13691   // These break the otherwise-useful invariant below.  Fortunately,
13692   // we don't really need to recurse into them, because any internal
13693   // expressions should have been analyzed already when they were
13694   // built into statements.
13695   if (isa<StmtExpr>(E)) return;
13696 
13697   // Don't descend into unevaluated contexts.
13698   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13699 
13700   // Now just recurse over the expression's children.
13701   CC = E->getExprLoc();
13702   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13703   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13704   for (Stmt *SubStmt : E->children()) {
13705     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13706     if (!ChildExpr)
13707       continue;
13708 
13709     if (IsLogicalAndOperator &&
13710         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13711       // Ignore checking string literals that are in logical and operators.
13712       // This is a common pattern for asserts.
13713       continue;
13714     WorkList.push_back({ChildExpr, CC, IsListInit});
13715   }
13716 
13717   if (BO && BO->isLogicalOp()) {
13718     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13719     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13720       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13721 
13722     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13723     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13724       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13725   }
13726 
13727   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13728     if (U->getOpcode() == UO_LNot) {
13729       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13730     } else if (U->getOpcode() != UO_AddrOf) {
13731       if (U->getSubExpr()->getType()->isAtomicType())
13732         S.Diag(U->getSubExpr()->getBeginLoc(),
13733                diag::warn_atomic_implicit_seq_cst);
13734     }
13735   }
13736 }
13737 
13738 /// AnalyzeImplicitConversions - Find and report any interesting
13739 /// implicit conversions in the given expression.  There are a couple
13740 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13741 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13742                                        bool IsListInit/*= false*/) {
13743   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13744   WorkList.push_back({OrigE, CC, IsListInit});
13745   while (!WorkList.empty())
13746     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13747 }
13748 
13749 /// Diagnose integer type and any valid implicit conversion to it.
13750 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13751   // Taking into account implicit conversions,
13752   // allow any integer.
13753   if (!E->getType()->isIntegerType()) {
13754     S.Diag(E->getBeginLoc(),
13755            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13756     return true;
13757   }
13758   // Potentially emit standard warnings for implicit conversions if enabled
13759   // using -Wconversion.
13760   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13761   return false;
13762 }
13763 
13764 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13765 // Returns true when emitting a warning about taking the address of a reference.
13766 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13767                               const PartialDiagnostic &PD) {
13768   E = E->IgnoreParenImpCasts();
13769 
13770   const FunctionDecl *FD = nullptr;
13771 
13772   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13773     if (!DRE->getDecl()->getType()->isReferenceType())
13774       return false;
13775   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13776     if (!M->getMemberDecl()->getType()->isReferenceType())
13777       return false;
13778   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13779     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13780       return false;
13781     FD = Call->getDirectCallee();
13782   } else {
13783     return false;
13784   }
13785 
13786   SemaRef.Diag(E->getExprLoc(), PD);
13787 
13788   // If possible, point to location of function.
13789   if (FD) {
13790     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13791   }
13792 
13793   return true;
13794 }
13795 
13796 // Returns true if the SourceLocation is expanded from any macro body.
13797 // Returns false if the SourceLocation is invalid, is from not in a macro
13798 // expansion, or is from expanded from a top-level macro argument.
13799 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13800   if (Loc.isInvalid())
13801     return false;
13802 
13803   while (Loc.isMacroID()) {
13804     if (SM.isMacroBodyExpansion(Loc))
13805       return true;
13806     Loc = SM.getImmediateMacroCallerLoc(Loc);
13807   }
13808 
13809   return false;
13810 }
13811 
13812 /// Diagnose pointers that are always non-null.
13813 /// \param E the expression containing the pointer
13814 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13815 /// compared to a null pointer
13816 /// \param IsEqual True when the comparison is equal to a null pointer
13817 /// \param Range Extra SourceRange to highlight in the diagnostic
13818 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13819                                         Expr::NullPointerConstantKind NullKind,
13820                                         bool IsEqual, SourceRange Range) {
13821   if (!E)
13822     return;
13823 
13824   // Don't warn inside macros.
13825   if (E->getExprLoc().isMacroID()) {
13826     const SourceManager &SM = getSourceManager();
13827     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13828         IsInAnyMacroBody(SM, Range.getBegin()))
13829       return;
13830   }
13831   E = E->IgnoreImpCasts();
13832 
13833   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13834 
13835   if (isa<CXXThisExpr>(E)) {
13836     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13837                                 : diag::warn_this_bool_conversion;
13838     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13839     return;
13840   }
13841 
13842   bool IsAddressOf = false;
13843 
13844   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13845     if (UO->getOpcode() != UO_AddrOf)
13846       return;
13847     IsAddressOf = true;
13848     E = UO->getSubExpr();
13849   }
13850 
13851   if (IsAddressOf) {
13852     unsigned DiagID = IsCompare
13853                           ? diag::warn_address_of_reference_null_compare
13854                           : diag::warn_address_of_reference_bool_conversion;
13855     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13856                                          << IsEqual;
13857     if (CheckForReference(*this, E, PD)) {
13858       return;
13859     }
13860   }
13861 
13862   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13863     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13864     std::string Str;
13865     llvm::raw_string_ostream S(Str);
13866     E->printPretty(S, nullptr, getPrintingPolicy());
13867     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13868                                 : diag::warn_cast_nonnull_to_bool;
13869     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13870       << E->getSourceRange() << Range << IsEqual;
13871     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13872   };
13873 
13874   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13875   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13876     if (auto *Callee = Call->getDirectCallee()) {
13877       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13878         ComplainAboutNonnullParamOrCall(A);
13879         return;
13880       }
13881     }
13882   }
13883 
13884   // Expect to find a single Decl.  Skip anything more complicated.
13885   ValueDecl *D = nullptr;
13886   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13887     D = R->getDecl();
13888   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13889     D = M->getMemberDecl();
13890   }
13891 
13892   // Weak Decls can be null.
13893   if (!D || D->isWeak())
13894     return;
13895 
13896   // Check for parameter decl with nonnull attribute
13897   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13898     if (getCurFunction() &&
13899         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13900       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13901         ComplainAboutNonnullParamOrCall(A);
13902         return;
13903       }
13904 
13905       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13906         // Skip function template not specialized yet.
13907         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13908           return;
13909         auto ParamIter = llvm::find(FD->parameters(), PV);
13910         assert(ParamIter != FD->param_end());
13911         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13912 
13913         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13914           if (!NonNull->args_size()) {
13915               ComplainAboutNonnullParamOrCall(NonNull);
13916               return;
13917           }
13918 
13919           for (const ParamIdx &ArgNo : NonNull->args()) {
13920             if (ArgNo.getASTIndex() == ParamNo) {
13921               ComplainAboutNonnullParamOrCall(NonNull);
13922               return;
13923             }
13924           }
13925         }
13926       }
13927     }
13928   }
13929 
13930   QualType T = D->getType();
13931   const bool IsArray = T->isArrayType();
13932   const bool IsFunction = T->isFunctionType();
13933 
13934   // Address of function is used to silence the function warning.
13935   if (IsAddressOf && IsFunction) {
13936     return;
13937   }
13938 
13939   // Found nothing.
13940   if (!IsAddressOf && !IsFunction && !IsArray)
13941     return;
13942 
13943   // Pretty print the expression for the diagnostic.
13944   std::string Str;
13945   llvm::raw_string_ostream S(Str);
13946   E->printPretty(S, nullptr, getPrintingPolicy());
13947 
13948   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13949                               : diag::warn_impcast_pointer_to_bool;
13950   enum {
13951     AddressOf,
13952     FunctionPointer,
13953     ArrayPointer
13954   } DiagType;
13955   if (IsAddressOf)
13956     DiagType = AddressOf;
13957   else if (IsFunction)
13958     DiagType = FunctionPointer;
13959   else if (IsArray)
13960     DiagType = ArrayPointer;
13961   else
13962     llvm_unreachable("Could not determine diagnostic.");
13963   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13964                                 << Range << IsEqual;
13965 
13966   if (!IsFunction)
13967     return;
13968 
13969   // Suggest '&' to silence the function warning.
13970   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13971       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13972 
13973   // Check to see if '()' fixit should be emitted.
13974   QualType ReturnType;
13975   UnresolvedSet<4> NonTemplateOverloads;
13976   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13977   if (ReturnType.isNull())
13978     return;
13979 
13980   if (IsCompare) {
13981     // There are two cases here.  If there is null constant, the only suggest
13982     // for a pointer return type.  If the null is 0, then suggest if the return
13983     // type is a pointer or an integer type.
13984     if (!ReturnType->isPointerType()) {
13985       if (NullKind == Expr::NPCK_ZeroExpression ||
13986           NullKind == Expr::NPCK_ZeroLiteral) {
13987         if (!ReturnType->isIntegerType())
13988           return;
13989       } else {
13990         return;
13991       }
13992     }
13993   } else { // !IsCompare
13994     // For function to bool, only suggest if the function pointer has bool
13995     // return type.
13996     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13997       return;
13998   }
13999   Diag(E->getExprLoc(), diag::note_function_to_function_call)
14000       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
14001 }
14002 
14003 /// Diagnoses "dangerous" implicit conversions within the given
14004 /// expression (which is a full expression).  Implements -Wconversion
14005 /// and -Wsign-compare.
14006 ///
14007 /// \param CC the "context" location of the implicit conversion, i.e.
14008 ///   the most location of the syntactic entity requiring the implicit
14009 ///   conversion
14010 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14011   // Don't diagnose in unevaluated contexts.
14012   if (isUnevaluatedContext())
14013     return;
14014 
14015   // Don't diagnose for value- or type-dependent expressions.
14016   if (E->isTypeDependent() || E->isValueDependent())
14017     return;
14018 
14019   // Check for array bounds violations in cases where the check isn't triggered
14020   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14021   // ArraySubscriptExpr is on the RHS of a variable initialization.
14022   CheckArrayAccess(E);
14023 
14024   // This is not the right CC for (e.g.) a variable initialization.
14025   AnalyzeImplicitConversions(*this, E, CC);
14026 }
14027 
14028 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
14029 /// Input argument E is a logical expression.
14030 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14031   ::CheckBoolLikeConversion(*this, E, CC);
14032 }
14033 
14034 /// Diagnose when expression is an integer constant expression and its evaluation
14035 /// results in integer overflow
14036 void Sema::CheckForIntOverflow (Expr *E) {
14037   // Use a work list to deal with nested struct initializers.
14038   SmallVector<Expr *, 2> Exprs(1, E);
14039 
14040   do {
14041     Expr *OriginalE = Exprs.pop_back_val();
14042     Expr *E = OriginalE->IgnoreParenCasts();
14043 
14044     if (isa<BinaryOperator>(E)) {
14045       E->EvaluateForOverflow(Context);
14046       continue;
14047     }
14048 
14049     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
14050       Exprs.append(InitList->inits().begin(), InitList->inits().end());
14051     else if (isa<ObjCBoxedExpr>(OriginalE))
14052       E->EvaluateForOverflow(Context);
14053     else if (auto Call = dyn_cast<CallExpr>(E))
14054       Exprs.append(Call->arg_begin(), Call->arg_end());
14055     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
14056       Exprs.append(Message->arg_begin(), Message->arg_end());
14057   } while (!Exprs.empty());
14058 }
14059 
14060 namespace {
14061 
14062 /// Visitor for expressions which looks for unsequenced operations on the
14063 /// same object.
14064 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14065   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14066 
14067   /// A tree of sequenced regions within an expression. Two regions are
14068   /// unsequenced if one is an ancestor or a descendent of the other. When we
14069   /// finish processing an expression with sequencing, such as a comma
14070   /// expression, we fold its tree nodes into its parent, since they are
14071   /// unsequenced with respect to nodes we will visit later.
14072   class SequenceTree {
14073     struct Value {
14074       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14075       unsigned Parent : 31;
14076       unsigned Merged : 1;
14077     };
14078     SmallVector<Value, 8> Values;
14079 
14080   public:
14081     /// A region within an expression which may be sequenced with respect
14082     /// to some other region.
14083     class Seq {
14084       friend class SequenceTree;
14085 
14086       unsigned Index;
14087 
14088       explicit Seq(unsigned N) : Index(N) {}
14089 
14090     public:
14091       Seq() : Index(0) {}
14092     };
14093 
14094     SequenceTree() { Values.push_back(Value(0)); }
14095     Seq root() const { return Seq(0); }
14096 
14097     /// Create a new sequence of operations, which is an unsequenced
14098     /// subset of \p Parent. This sequence of operations is sequenced with
14099     /// respect to other children of \p Parent.
14100     Seq allocate(Seq Parent) {
14101       Values.push_back(Value(Parent.Index));
14102       return Seq(Values.size() - 1);
14103     }
14104 
14105     /// Merge a sequence of operations into its parent.
14106     void merge(Seq S) {
14107       Values[S.Index].Merged = true;
14108     }
14109 
14110     /// Determine whether two operations are unsequenced. This operation
14111     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14112     /// should have been merged into its parent as appropriate.
14113     bool isUnsequenced(Seq Cur, Seq Old) {
14114       unsigned C = representative(Cur.Index);
14115       unsigned Target = representative(Old.Index);
14116       while (C >= Target) {
14117         if (C == Target)
14118           return true;
14119         C = Values[C].Parent;
14120       }
14121       return false;
14122     }
14123 
14124   private:
14125     /// Pick a representative for a sequence.
14126     unsigned representative(unsigned K) {
14127       if (Values[K].Merged)
14128         // Perform path compression as we go.
14129         return Values[K].Parent = representative(Values[K].Parent);
14130       return K;
14131     }
14132   };
14133 
14134   /// An object for which we can track unsequenced uses.
14135   using Object = const NamedDecl *;
14136 
14137   /// Different flavors of object usage which we track. We only track the
14138   /// least-sequenced usage of each kind.
14139   enum UsageKind {
14140     /// A read of an object. Multiple unsequenced reads are OK.
14141     UK_Use,
14142 
14143     /// A modification of an object which is sequenced before the value
14144     /// computation of the expression, such as ++n in C++.
14145     UK_ModAsValue,
14146 
14147     /// A modification of an object which is not sequenced before the value
14148     /// computation of the expression, such as n++.
14149     UK_ModAsSideEffect,
14150 
14151     UK_Count = UK_ModAsSideEffect + 1
14152   };
14153 
14154   /// Bundle together a sequencing region and the expression corresponding
14155   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14156   struct Usage {
14157     const Expr *UsageExpr;
14158     SequenceTree::Seq Seq;
14159 
14160     Usage() : UsageExpr(nullptr) {}
14161   };
14162 
14163   struct UsageInfo {
14164     Usage Uses[UK_Count];
14165 
14166     /// Have we issued a diagnostic for this object already?
14167     bool Diagnosed;
14168 
14169     UsageInfo() : Diagnosed(false) {}
14170   };
14171   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14172 
14173   Sema &SemaRef;
14174 
14175   /// Sequenced regions within the expression.
14176   SequenceTree Tree;
14177 
14178   /// Declaration modifications and references which we have seen.
14179   UsageInfoMap UsageMap;
14180 
14181   /// The region we are currently within.
14182   SequenceTree::Seq Region;
14183 
14184   /// Filled in with declarations which were modified as a side-effect
14185   /// (that is, post-increment operations).
14186   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14187 
14188   /// Expressions to check later. We defer checking these to reduce
14189   /// stack usage.
14190   SmallVectorImpl<const Expr *> &WorkList;
14191 
14192   /// RAII object wrapping the visitation of a sequenced subexpression of an
14193   /// expression. At the end of this process, the side-effects of the evaluation
14194   /// become sequenced with respect to the value computation of the result, so
14195   /// we downgrade any UK_ModAsSideEffect within the evaluation to
14196   /// UK_ModAsValue.
14197   struct SequencedSubexpression {
14198     SequencedSubexpression(SequenceChecker &Self)
14199       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14200       Self.ModAsSideEffect = &ModAsSideEffect;
14201     }
14202 
14203     ~SequencedSubexpression() {
14204       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14205         // Add a new usage with usage kind UK_ModAsValue, and then restore
14206         // the previous usage with UK_ModAsSideEffect (thus clearing it if
14207         // the previous one was empty).
14208         UsageInfo &UI = Self.UsageMap[M.first];
14209         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14210         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14211         SideEffectUsage = M.second;
14212       }
14213       Self.ModAsSideEffect = OldModAsSideEffect;
14214     }
14215 
14216     SequenceChecker &Self;
14217     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14218     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14219   };
14220 
14221   /// RAII object wrapping the visitation of a subexpression which we might
14222   /// choose to evaluate as a constant. If any subexpression is evaluated and
14223   /// found to be non-constant, this allows us to suppress the evaluation of
14224   /// the outer expression.
14225   class EvaluationTracker {
14226   public:
14227     EvaluationTracker(SequenceChecker &Self)
14228         : Self(Self), Prev(Self.EvalTracker) {
14229       Self.EvalTracker = this;
14230     }
14231 
14232     ~EvaluationTracker() {
14233       Self.EvalTracker = Prev;
14234       if (Prev)
14235         Prev->EvalOK &= EvalOK;
14236     }
14237 
14238     bool evaluate(const Expr *E, bool &Result) {
14239       if (!EvalOK || E->isValueDependent())
14240         return false;
14241       EvalOK = E->EvaluateAsBooleanCondition(
14242           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
14243       return EvalOK;
14244     }
14245 
14246   private:
14247     SequenceChecker &Self;
14248     EvaluationTracker *Prev;
14249     bool EvalOK = true;
14250   } *EvalTracker = nullptr;
14251 
14252   /// Find the object which is produced by the specified expression,
14253   /// if any.
14254   Object getObject(const Expr *E, bool Mod) const {
14255     E = E->IgnoreParenCasts();
14256     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14257       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14258         return getObject(UO->getSubExpr(), Mod);
14259     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14260       if (BO->getOpcode() == BO_Comma)
14261         return getObject(BO->getRHS(), Mod);
14262       if (Mod && BO->isAssignmentOp())
14263         return getObject(BO->getLHS(), Mod);
14264     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14265       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14266       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14267         return ME->getMemberDecl();
14268     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14269       // FIXME: If this is a reference, map through to its value.
14270       return DRE->getDecl();
14271     return nullptr;
14272   }
14273 
14274   /// Note that an object \p O was modified or used by an expression
14275   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14276   /// the object \p O as obtained via the \p UsageMap.
14277   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14278     // Get the old usage for the given object and usage kind.
14279     Usage &U = UI.Uses[UK];
14280     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14281       // If we have a modification as side effect and are in a sequenced
14282       // subexpression, save the old Usage so that we can restore it later
14283       // in SequencedSubexpression::~SequencedSubexpression.
14284       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14285         ModAsSideEffect->push_back(std::make_pair(O, U));
14286       // Then record the new usage with the current sequencing region.
14287       U.UsageExpr = UsageExpr;
14288       U.Seq = Region;
14289     }
14290   }
14291 
14292   /// Check whether a modification or use of an object \p O in an expression
14293   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14294   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14295   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14296   /// usage and false we are checking for a mod-use unsequenced usage.
14297   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14298                   UsageKind OtherKind, bool IsModMod) {
14299     if (UI.Diagnosed)
14300       return;
14301 
14302     const Usage &U = UI.Uses[OtherKind];
14303     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14304       return;
14305 
14306     const Expr *Mod = U.UsageExpr;
14307     const Expr *ModOrUse = UsageExpr;
14308     if (OtherKind == UK_Use)
14309       std::swap(Mod, ModOrUse);
14310 
14311     SemaRef.DiagRuntimeBehavior(
14312         Mod->getExprLoc(), {Mod, ModOrUse},
14313         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14314                                : diag::warn_unsequenced_mod_use)
14315             << O << SourceRange(ModOrUse->getExprLoc()));
14316     UI.Diagnosed = true;
14317   }
14318 
14319   // A note on note{Pre, Post}{Use, Mod}:
14320   //
14321   // (It helps to follow the algorithm with an expression such as
14322   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14323   //  operations before C++17 and both are well-defined in C++17).
14324   //
14325   // When visiting a node which uses/modify an object we first call notePreUse
14326   // or notePreMod before visiting its sub-expression(s). At this point the
14327   // children of the current node have not yet been visited and so the eventual
14328   // uses/modifications resulting from the children of the current node have not
14329   // been recorded yet.
14330   //
14331   // We then visit the children of the current node. After that notePostUse or
14332   // notePostMod is called. These will 1) detect an unsequenced modification
14333   // as side effect (as in "k++ + k") and 2) add a new usage with the
14334   // appropriate usage kind.
14335   //
14336   // We also have to be careful that some operation sequences modification as
14337   // side effect as well (for example: || or ,). To account for this we wrap
14338   // the visitation of such a sub-expression (for example: the LHS of || or ,)
14339   // with SequencedSubexpression. SequencedSubexpression is an RAII object
14340   // which record usages which are modifications as side effect, and then
14341   // downgrade them (or more accurately restore the previous usage which was a
14342   // modification as side effect) when exiting the scope of the sequenced
14343   // subexpression.
14344 
14345   void notePreUse(Object O, const Expr *UseExpr) {
14346     UsageInfo &UI = UsageMap[O];
14347     // Uses conflict with other modifications.
14348     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14349   }
14350 
14351   void notePostUse(Object O, const Expr *UseExpr) {
14352     UsageInfo &UI = UsageMap[O];
14353     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14354                /*IsModMod=*/false);
14355     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14356   }
14357 
14358   void notePreMod(Object O, const Expr *ModExpr) {
14359     UsageInfo &UI = UsageMap[O];
14360     // Modifications conflict with other modifications and with uses.
14361     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14362     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14363   }
14364 
14365   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14366     UsageInfo &UI = UsageMap[O];
14367     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14368                /*IsModMod=*/true);
14369     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14370   }
14371 
14372 public:
14373   SequenceChecker(Sema &S, const Expr *E,
14374                   SmallVectorImpl<const Expr *> &WorkList)
14375       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14376     Visit(E);
14377     // Silence a -Wunused-private-field since WorkList is now unused.
14378     // TODO: Evaluate if it can be used, and if not remove it.
14379     (void)this->WorkList;
14380   }
14381 
14382   void VisitStmt(const Stmt *S) {
14383     // Skip all statements which aren't expressions for now.
14384   }
14385 
14386   void VisitExpr(const Expr *E) {
14387     // By default, just recurse to evaluated subexpressions.
14388     Base::VisitStmt(E);
14389   }
14390 
14391   void VisitCastExpr(const CastExpr *E) {
14392     Object O = Object();
14393     if (E->getCastKind() == CK_LValueToRValue)
14394       O = getObject(E->getSubExpr(), false);
14395 
14396     if (O)
14397       notePreUse(O, E);
14398     VisitExpr(E);
14399     if (O)
14400       notePostUse(O, E);
14401   }
14402 
14403   void VisitSequencedExpressions(const Expr *SequencedBefore,
14404                                  const Expr *SequencedAfter) {
14405     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14406     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14407     SequenceTree::Seq OldRegion = Region;
14408 
14409     {
14410       SequencedSubexpression SeqBefore(*this);
14411       Region = BeforeRegion;
14412       Visit(SequencedBefore);
14413     }
14414 
14415     Region = AfterRegion;
14416     Visit(SequencedAfter);
14417 
14418     Region = OldRegion;
14419 
14420     Tree.merge(BeforeRegion);
14421     Tree.merge(AfterRegion);
14422   }
14423 
14424   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14425     // C++17 [expr.sub]p1:
14426     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14427     //   expression E1 is sequenced before the expression E2.
14428     if (SemaRef.getLangOpts().CPlusPlus17)
14429       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14430     else {
14431       Visit(ASE->getLHS());
14432       Visit(ASE->getRHS());
14433     }
14434   }
14435 
14436   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14437   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14438   void VisitBinPtrMem(const BinaryOperator *BO) {
14439     // C++17 [expr.mptr.oper]p4:
14440     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14441     //  the expression E1 is sequenced before the expression E2.
14442     if (SemaRef.getLangOpts().CPlusPlus17)
14443       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14444     else {
14445       Visit(BO->getLHS());
14446       Visit(BO->getRHS());
14447     }
14448   }
14449 
14450   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14451   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14452   void VisitBinShlShr(const BinaryOperator *BO) {
14453     // C++17 [expr.shift]p4:
14454     //  The expression E1 is sequenced before the expression E2.
14455     if (SemaRef.getLangOpts().CPlusPlus17)
14456       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14457     else {
14458       Visit(BO->getLHS());
14459       Visit(BO->getRHS());
14460     }
14461   }
14462 
14463   void VisitBinComma(const BinaryOperator *BO) {
14464     // C++11 [expr.comma]p1:
14465     //   Every value computation and side effect associated with the left
14466     //   expression is sequenced before every value computation and side
14467     //   effect associated with the right expression.
14468     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14469   }
14470 
14471   void VisitBinAssign(const BinaryOperator *BO) {
14472     SequenceTree::Seq RHSRegion;
14473     SequenceTree::Seq LHSRegion;
14474     if (SemaRef.getLangOpts().CPlusPlus17) {
14475       RHSRegion = Tree.allocate(Region);
14476       LHSRegion = Tree.allocate(Region);
14477     } else {
14478       RHSRegion = Region;
14479       LHSRegion = Region;
14480     }
14481     SequenceTree::Seq OldRegion = Region;
14482 
14483     // C++11 [expr.ass]p1:
14484     //  [...] the assignment is sequenced after the value computation
14485     //  of the right and left operands, [...]
14486     //
14487     // so check it before inspecting the operands and update the
14488     // map afterwards.
14489     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14490     if (O)
14491       notePreMod(O, BO);
14492 
14493     if (SemaRef.getLangOpts().CPlusPlus17) {
14494       // C++17 [expr.ass]p1:
14495       //  [...] The right operand is sequenced before the left operand. [...]
14496       {
14497         SequencedSubexpression SeqBefore(*this);
14498         Region = RHSRegion;
14499         Visit(BO->getRHS());
14500       }
14501 
14502       Region = LHSRegion;
14503       Visit(BO->getLHS());
14504 
14505       if (O && isa<CompoundAssignOperator>(BO))
14506         notePostUse(O, BO);
14507 
14508     } else {
14509       // C++11 does not specify any sequencing between the LHS and RHS.
14510       Region = LHSRegion;
14511       Visit(BO->getLHS());
14512 
14513       if (O && isa<CompoundAssignOperator>(BO))
14514         notePostUse(O, BO);
14515 
14516       Region = RHSRegion;
14517       Visit(BO->getRHS());
14518     }
14519 
14520     // C++11 [expr.ass]p1:
14521     //  the assignment is sequenced [...] before the value computation of the
14522     //  assignment expression.
14523     // C11 6.5.16/3 has no such rule.
14524     Region = OldRegion;
14525     if (O)
14526       notePostMod(O, BO,
14527                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14528                                                   : UK_ModAsSideEffect);
14529     if (SemaRef.getLangOpts().CPlusPlus17) {
14530       Tree.merge(RHSRegion);
14531       Tree.merge(LHSRegion);
14532     }
14533   }
14534 
14535   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14536     VisitBinAssign(CAO);
14537   }
14538 
14539   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14540   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14541   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14542     Object O = getObject(UO->getSubExpr(), true);
14543     if (!O)
14544       return VisitExpr(UO);
14545 
14546     notePreMod(O, UO);
14547     Visit(UO->getSubExpr());
14548     // C++11 [expr.pre.incr]p1:
14549     //   the expression ++x is equivalent to x+=1
14550     notePostMod(O, UO,
14551                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14552                                                 : UK_ModAsSideEffect);
14553   }
14554 
14555   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14556   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14557   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14558     Object O = getObject(UO->getSubExpr(), true);
14559     if (!O)
14560       return VisitExpr(UO);
14561 
14562     notePreMod(O, UO);
14563     Visit(UO->getSubExpr());
14564     notePostMod(O, UO, UK_ModAsSideEffect);
14565   }
14566 
14567   void VisitBinLOr(const BinaryOperator *BO) {
14568     // C++11 [expr.log.or]p2:
14569     //  If the second expression is evaluated, every value computation and
14570     //  side effect associated with the first expression is sequenced before
14571     //  every value computation and side effect associated with the
14572     //  second expression.
14573     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14574     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14575     SequenceTree::Seq OldRegion = Region;
14576 
14577     EvaluationTracker Eval(*this);
14578     {
14579       SequencedSubexpression Sequenced(*this);
14580       Region = LHSRegion;
14581       Visit(BO->getLHS());
14582     }
14583 
14584     // C++11 [expr.log.or]p1:
14585     //  [...] the second operand is not evaluated if the first operand
14586     //  evaluates to true.
14587     bool EvalResult = false;
14588     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14589     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14590     if (ShouldVisitRHS) {
14591       Region = RHSRegion;
14592       Visit(BO->getRHS());
14593     }
14594 
14595     Region = OldRegion;
14596     Tree.merge(LHSRegion);
14597     Tree.merge(RHSRegion);
14598   }
14599 
14600   void VisitBinLAnd(const BinaryOperator *BO) {
14601     // C++11 [expr.log.and]p2:
14602     //  If the second expression is evaluated, every value computation and
14603     //  side effect associated with the first expression is sequenced before
14604     //  every value computation and side effect associated with the
14605     //  second expression.
14606     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14607     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14608     SequenceTree::Seq OldRegion = Region;
14609 
14610     EvaluationTracker Eval(*this);
14611     {
14612       SequencedSubexpression Sequenced(*this);
14613       Region = LHSRegion;
14614       Visit(BO->getLHS());
14615     }
14616 
14617     // C++11 [expr.log.and]p1:
14618     //  [...] the second operand is not evaluated if the first operand is false.
14619     bool EvalResult = false;
14620     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14621     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14622     if (ShouldVisitRHS) {
14623       Region = RHSRegion;
14624       Visit(BO->getRHS());
14625     }
14626 
14627     Region = OldRegion;
14628     Tree.merge(LHSRegion);
14629     Tree.merge(RHSRegion);
14630   }
14631 
14632   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14633     // C++11 [expr.cond]p1:
14634     //  [...] Every value computation and side effect associated with the first
14635     //  expression is sequenced before every value computation and side effect
14636     //  associated with the second or third expression.
14637     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14638 
14639     // No sequencing is specified between the true and false expression.
14640     // However since exactly one of both is going to be evaluated we can
14641     // consider them to be sequenced. This is needed to avoid warning on
14642     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14643     // both the true and false expressions because we can't evaluate x.
14644     // This will still allow us to detect an expression like (pre C++17)
14645     // "(x ? y += 1 : y += 2) = y".
14646     //
14647     // We don't wrap the visitation of the true and false expression with
14648     // SequencedSubexpression because we don't want to downgrade modifications
14649     // as side effect in the true and false expressions after the visition
14650     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14651     // not warn between the two "y++", but we should warn between the "y++"
14652     // and the "y".
14653     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14654     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14655     SequenceTree::Seq OldRegion = Region;
14656 
14657     EvaluationTracker Eval(*this);
14658     {
14659       SequencedSubexpression Sequenced(*this);
14660       Region = ConditionRegion;
14661       Visit(CO->getCond());
14662     }
14663 
14664     // C++11 [expr.cond]p1:
14665     // [...] The first expression is contextually converted to bool (Clause 4).
14666     // It is evaluated and if it is true, the result of the conditional
14667     // expression is the value of the second expression, otherwise that of the
14668     // third expression. Only one of the second and third expressions is
14669     // evaluated. [...]
14670     bool EvalResult = false;
14671     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14672     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14673     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14674     if (ShouldVisitTrueExpr) {
14675       Region = TrueRegion;
14676       Visit(CO->getTrueExpr());
14677     }
14678     if (ShouldVisitFalseExpr) {
14679       Region = FalseRegion;
14680       Visit(CO->getFalseExpr());
14681     }
14682 
14683     Region = OldRegion;
14684     Tree.merge(ConditionRegion);
14685     Tree.merge(TrueRegion);
14686     Tree.merge(FalseRegion);
14687   }
14688 
14689   void VisitCallExpr(const CallExpr *CE) {
14690     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14691 
14692     if (CE->isUnevaluatedBuiltinCall(Context))
14693       return;
14694 
14695     // C++11 [intro.execution]p15:
14696     //   When calling a function [...], every value computation and side effect
14697     //   associated with any argument expression, or with the postfix expression
14698     //   designating the called function, is sequenced before execution of every
14699     //   expression or statement in the body of the function [and thus before
14700     //   the value computation of its result].
14701     SequencedSubexpression Sequenced(*this);
14702     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14703       // C++17 [expr.call]p5
14704       //   The postfix-expression is sequenced before each expression in the
14705       //   expression-list and any default argument. [...]
14706       SequenceTree::Seq CalleeRegion;
14707       SequenceTree::Seq OtherRegion;
14708       if (SemaRef.getLangOpts().CPlusPlus17) {
14709         CalleeRegion = Tree.allocate(Region);
14710         OtherRegion = Tree.allocate(Region);
14711       } else {
14712         CalleeRegion = Region;
14713         OtherRegion = Region;
14714       }
14715       SequenceTree::Seq OldRegion = Region;
14716 
14717       // Visit the callee expression first.
14718       Region = CalleeRegion;
14719       if (SemaRef.getLangOpts().CPlusPlus17) {
14720         SequencedSubexpression Sequenced(*this);
14721         Visit(CE->getCallee());
14722       } else {
14723         Visit(CE->getCallee());
14724       }
14725 
14726       // Then visit the argument expressions.
14727       Region = OtherRegion;
14728       for (const Expr *Argument : CE->arguments())
14729         Visit(Argument);
14730 
14731       Region = OldRegion;
14732       if (SemaRef.getLangOpts().CPlusPlus17) {
14733         Tree.merge(CalleeRegion);
14734         Tree.merge(OtherRegion);
14735       }
14736     });
14737   }
14738 
14739   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14740     // C++17 [over.match.oper]p2:
14741     //   [...] the operator notation is first transformed to the equivalent
14742     //   function-call notation as summarized in Table 12 (where @ denotes one
14743     //   of the operators covered in the specified subclause). However, the
14744     //   operands are sequenced in the order prescribed for the built-in
14745     //   operator (Clause 8).
14746     //
14747     // From the above only overloaded binary operators and overloaded call
14748     // operators have sequencing rules in C++17 that we need to handle
14749     // separately.
14750     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14751         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14752       return VisitCallExpr(CXXOCE);
14753 
14754     enum {
14755       NoSequencing,
14756       LHSBeforeRHS,
14757       RHSBeforeLHS,
14758       LHSBeforeRest
14759     } SequencingKind;
14760     switch (CXXOCE->getOperator()) {
14761     case OO_Equal:
14762     case OO_PlusEqual:
14763     case OO_MinusEqual:
14764     case OO_StarEqual:
14765     case OO_SlashEqual:
14766     case OO_PercentEqual:
14767     case OO_CaretEqual:
14768     case OO_AmpEqual:
14769     case OO_PipeEqual:
14770     case OO_LessLessEqual:
14771     case OO_GreaterGreaterEqual:
14772       SequencingKind = RHSBeforeLHS;
14773       break;
14774 
14775     case OO_LessLess:
14776     case OO_GreaterGreater:
14777     case OO_AmpAmp:
14778     case OO_PipePipe:
14779     case OO_Comma:
14780     case OO_ArrowStar:
14781     case OO_Subscript:
14782       SequencingKind = LHSBeforeRHS;
14783       break;
14784 
14785     case OO_Call:
14786       SequencingKind = LHSBeforeRest;
14787       break;
14788 
14789     default:
14790       SequencingKind = NoSequencing;
14791       break;
14792     }
14793 
14794     if (SequencingKind == NoSequencing)
14795       return VisitCallExpr(CXXOCE);
14796 
14797     // This is a call, so all subexpressions are sequenced before the result.
14798     SequencedSubexpression Sequenced(*this);
14799 
14800     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14801       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14802              "Should only get there with C++17 and above!");
14803       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14804              "Should only get there with an overloaded binary operator"
14805              " or an overloaded call operator!");
14806 
14807       if (SequencingKind == LHSBeforeRest) {
14808         assert(CXXOCE->getOperator() == OO_Call &&
14809                "We should only have an overloaded call operator here!");
14810 
14811         // This is very similar to VisitCallExpr, except that we only have the
14812         // C++17 case. The postfix-expression is the first argument of the
14813         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14814         // are in the following arguments.
14815         //
14816         // Note that we intentionally do not visit the callee expression since
14817         // it is just a decayed reference to a function.
14818         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14819         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14820         SequenceTree::Seq OldRegion = Region;
14821 
14822         assert(CXXOCE->getNumArgs() >= 1 &&
14823                "An overloaded call operator must have at least one argument"
14824                " for the postfix-expression!");
14825         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14826         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14827                                           CXXOCE->getNumArgs() - 1);
14828 
14829         // Visit the postfix-expression first.
14830         {
14831           Region = PostfixExprRegion;
14832           SequencedSubexpression Sequenced(*this);
14833           Visit(PostfixExpr);
14834         }
14835 
14836         // Then visit the argument expressions.
14837         Region = ArgsRegion;
14838         for (const Expr *Arg : Args)
14839           Visit(Arg);
14840 
14841         Region = OldRegion;
14842         Tree.merge(PostfixExprRegion);
14843         Tree.merge(ArgsRegion);
14844       } else {
14845         assert(CXXOCE->getNumArgs() == 2 &&
14846                "Should only have two arguments here!");
14847         assert((SequencingKind == LHSBeforeRHS ||
14848                 SequencingKind == RHSBeforeLHS) &&
14849                "Unexpected sequencing kind!");
14850 
14851         // We do not visit the callee expression since it is just a decayed
14852         // reference to a function.
14853         const Expr *E1 = CXXOCE->getArg(0);
14854         const Expr *E2 = CXXOCE->getArg(1);
14855         if (SequencingKind == RHSBeforeLHS)
14856           std::swap(E1, E2);
14857 
14858         return VisitSequencedExpressions(E1, E2);
14859       }
14860     });
14861   }
14862 
14863   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14864     // This is a call, so all subexpressions are sequenced before the result.
14865     SequencedSubexpression Sequenced(*this);
14866 
14867     if (!CCE->isListInitialization())
14868       return VisitExpr(CCE);
14869 
14870     // In C++11, list initializations are sequenced.
14871     SmallVector<SequenceTree::Seq, 32> Elts;
14872     SequenceTree::Seq Parent = Region;
14873     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14874                                               E = CCE->arg_end();
14875          I != E; ++I) {
14876       Region = Tree.allocate(Parent);
14877       Elts.push_back(Region);
14878       Visit(*I);
14879     }
14880 
14881     // Forget that the initializers are sequenced.
14882     Region = Parent;
14883     for (unsigned I = 0; I < Elts.size(); ++I)
14884       Tree.merge(Elts[I]);
14885   }
14886 
14887   void VisitInitListExpr(const InitListExpr *ILE) {
14888     if (!SemaRef.getLangOpts().CPlusPlus11)
14889       return VisitExpr(ILE);
14890 
14891     // In C++11, list initializations are sequenced.
14892     SmallVector<SequenceTree::Seq, 32> Elts;
14893     SequenceTree::Seq Parent = Region;
14894     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14895       const Expr *E = ILE->getInit(I);
14896       if (!E)
14897         continue;
14898       Region = Tree.allocate(Parent);
14899       Elts.push_back(Region);
14900       Visit(E);
14901     }
14902 
14903     // Forget that the initializers are sequenced.
14904     Region = Parent;
14905     for (unsigned I = 0; I < Elts.size(); ++I)
14906       Tree.merge(Elts[I]);
14907   }
14908 };
14909 
14910 } // namespace
14911 
14912 void Sema::CheckUnsequencedOperations(const Expr *E) {
14913   SmallVector<const Expr *, 8> WorkList;
14914   WorkList.push_back(E);
14915   while (!WorkList.empty()) {
14916     const Expr *Item = WorkList.pop_back_val();
14917     SequenceChecker(*this, Item, WorkList);
14918   }
14919 }
14920 
14921 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14922                               bool IsConstexpr) {
14923   llvm::SaveAndRestore<bool> ConstantContext(
14924       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14925   CheckImplicitConversions(E, CheckLoc);
14926   if (!E->isInstantiationDependent())
14927     CheckUnsequencedOperations(E);
14928   if (!IsConstexpr && !E->isValueDependent())
14929     CheckForIntOverflow(E);
14930   DiagnoseMisalignedMembers();
14931 }
14932 
14933 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14934                                        FieldDecl *BitField,
14935                                        Expr *Init) {
14936   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14937 }
14938 
14939 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14940                                          SourceLocation Loc) {
14941   if (!PType->isVariablyModifiedType())
14942     return;
14943   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14944     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14945     return;
14946   }
14947   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14948     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14949     return;
14950   }
14951   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14952     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14953     return;
14954   }
14955 
14956   const ArrayType *AT = S.Context.getAsArrayType(PType);
14957   if (!AT)
14958     return;
14959 
14960   if (AT->getSizeModifier() != ArrayType::Star) {
14961     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14962     return;
14963   }
14964 
14965   S.Diag(Loc, diag::err_array_star_in_function_definition);
14966 }
14967 
14968 /// CheckParmsForFunctionDef - Check that the parameters of the given
14969 /// function are appropriate for the definition of a function. This
14970 /// takes care of any checks that cannot be performed on the
14971 /// declaration itself, e.g., that the types of each of the function
14972 /// parameters are complete.
14973 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14974                                     bool CheckParameterNames) {
14975   bool HasInvalidParm = false;
14976   for (ParmVarDecl *Param : Parameters) {
14977     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14978     // function declarator that is part of a function definition of
14979     // that function shall not have incomplete type.
14980     //
14981     // This is also C++ [dcl.fct]p6.
14982     if (!Param->isInvalidDecl() &&
14983         RequireCompleteType(Param->getLocation(), Param->getType(),
14984                             diag::err_typecheck_decl_incomplete_type)) {
14985       Param->setInvalidDecl();
14986       HasInvalidParm = true;
14987     }
14988 
14989     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14990     // declaration of each parameter shall include an identifier.
14991     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14992         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14993       // Diagnose this as an extension in C17 and earlier.
14994       if (!getLangOpts().C2x)
14995         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14996     }
14997 
14998     // C99 6.7.5.3p12:
14999     //   If the function declarator is not part of a definition of that
15000     //   function, parameters may have incomplete type and may use the [*]
15001     //   notation in their sequences of declarator specifiers to specify
15002     //   variable length array types.
15003     QualType PType = Param->getOriginalType();
15004     // FIXME: This diagnostic should point the '[*]' if source-location
15005     // information is added for it.
15006     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
15007 
15008     // If the parameter is a c++ class type and it has to be destructed in the
15009     // callee function, declare the destructor so that it can be called by the
15010     // callee function. Do not perform any direct access check on the dtor here.
15011     if (!Param->isInvalidDecl()) {
15012       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15013         if (!ClassDecl->isInvalidDecl() &&
15014             !ClassDecl->hasIrrelevantDestructor() &&
15015             !ClassDecl->isDependentContext() &&
15016             ClassDecl->isParamDestroyedInCallee()) {
15017           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15018           MarkFunctionReferenced(Param->getLocation(), Destructor);
15019           DiagnoseUseOfDecl(Destructor, Param->getLocation());
15020         }
15021       }
15022     }
15023 
15024     // Parameters with the pass_object_size attribute only need to be marked
15025     // constant at function definitions. Because we lack information about
15026     // whether we're on a declaration or definition when we're instantiating the
15027     // attribute, we need to check for constness here.
15028     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15029       if (!Param->getType().isConstQualified())
15030         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
15031             << Attr->getSpelling() << 1;
15032 
15033     // Check for parameter names shadowing fields from the class.
15034     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15035       // The owning context for the parameter should be the function, but we
15036       // want to see if this function's declaration context is a record.
15037       DeclContext *DC = Param->getDeclContext();
15038       if (DC && DC->isFunctionOrMethod()) {
15039         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
15040           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
15041                                      RD, /*DeclIsField*/ false);
15042       }
15043     }
15044   }
15045 
15046   return HasInvalidParm;
15047 }
15048 
15049 Optional<std::pair<CharUnits, CharUnits>>
15050 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
15051 
15052 /// Compute the alignment and offset of the base class object given the
15053 /// derived-to-base cast expression and the alignment and offset of the derived
15054 /// class object.
15055 static std::pair<CharUnits, CharUnits>
15056 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
15057                                    CharUnits BaseAlignment, CharUnits Offset,
15058                                    ASTContext &Ctx) {
15059   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15060        ++PathI) {
15061     const CXXBaseSpecifier *Base = *PathI;
15062     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15063     if (Base->isVirtual()) {
15064       // The complete object may have a lower alignment than the non-virtual
15065       // alignment of the base, in which case the base may be misaligned. Choose
15066       // the smaller of the non-virtual alignment and BaseAlignment, which is a
15067       // conservative lower bound of the complete object alignment.
15068       CharUnits NonVirtualAlignment =
15069           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
15070       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15071       Offset = CharUnits::Zero();
15072     } else {
15073       const ASTRecordLayout &RL =
15074           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
15075       Offset += RL.getBaseClassOffset(BaseDecl);
15076     }
15077     DerivedType = Base->getType();
15078   }
15079 
15080   return std::make_pair(BaseAlignment, Offset);
15081 }
15082 
15083 /// Compute the alignment and offset of a binary additive operator.
15084 static Optional<std::pair<CharUnits, CharUnits>>
15085 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
15086                                      bool IsSub, ASTContext &Ctx) {
15087   QualType PointeeType = PtrE->getType()->getPointeeType();
15088 
15089   if (!PointeeType->isConstantSizeType())
15090     return llvm::None;
15091 
15092   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
15093 
15094   if (!P)
15095     return llvm::None;
15096 
15097   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
15098   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15099     CharUnits Offset = EltSize * IdxRes->getExtValue();
15100     if (IsSub)
15101       Offset = -Offset;
15102     return std::make_pair(P->first, P->second + Offset);
15103   }
15104 
15105   // If the integer expression isn't a constant expression, compute the lower
15106   // bound of the alignment using the alignment and offset of the pointer
15107   // expression and the element size.
15108   return std::make_pair(
15109       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15110       CharUnits::Zero());
15111 }
15112 
15113 /// This helper function takes an lvalue expression and returns the alignment of
15114 /// a VarDecl and a constant offset from the VarDecl.
15115 Optional<std::pair<CharUnits, CharUnits>>
15116 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
15117   E = E->IgnoreParens();
15118   switch (E->getStmtClass()) {
15119   default:
15120     break;
15121   case Stmt::CStyleCastExprClass:
15122   case Stmt::CXXStaticCastExprClass:
15123   case Stmt::ImplicitCastExprClass: {
15124     auto *CE = cast<CastExpr>(E);
15125     const Expr *From = CE->getSubExpr();
15126     switch (CE->getCastKind()) {
15127     default:
15128       break;
15129     case CK_NoOp:
15130       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15131     case CK_UncheckedDerivedToBase:
15132     case CK_DerivedToBase: {
15133       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15134       if (!P)
15135         break;
15136       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15137                                                 P->second, Ctx);
15138     }
15139     }
15140     break;
15141   }
15142   case Stmt::ArraySubscriptExprClass: {
15143     auto *ASE = cast<ArraySubscriptExpr>(E);
15144     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
15145                                                 false, Ctx);
15146   }
15147   case Stmt::DeclRefExprClass: {
15148     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15149       // FIXME: If VD is captured by copy or is an escaping __block variable,
15150       // use the alignment of VD's type.
15151       if (!VD->getType()->isReferenceType())
15152         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15153       if (VD->hasInit())
15154         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15155     }
15156     break;
15157   }
15158   case Stmt::MemberExprClass: {
15159     auto *ME = cast<MemberExpr>(E);
15160     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15161     if (!FD || FD->getType()->isReferenceType() ||
15162         FD->getParent()->isInvalidDecl())
15163       break;
15164     Optional<std::pair<CharUnits, CharUnits>> P;
15165     if (ME->isArrow())
15166       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15167     else
15168       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15169     if (!P)
15170       break;
15171     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15172     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15173     return std::make_pair(P->first,
15174                           P->second + CharUnits::fromQuantity(Offset));
15175   }
15176   case Stmt::UnaryOperatorClass: {
15177     auto *UO = cast<UnaryOperator>(E);
15178     switch (UO->getOpcode()) {
15179     default:
15180       break;
15181     case UO_Deref:
15182       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
15183     }
15184     break;
15185   }
15186   case Stmt::BinaryOperatorClass: {
15187     auto *BO = cast<BinaryOperator>(E);
15188     auto Opcode = BO->getOpcode();
15189     switch (Opcode) {
15190     default:
15191       break;
15192     case BO_Comma:
15193       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
15194     }
15195     break;
15196   }
15197   }
15198   return llvm::None;
15199 }
15200 
15201 /// This helper function takes a pointer expression and returns the alignment of
15202 /// a VarDecl and a constant offset from the VarDecl.
15203 Optional<std::pair<CharUnits, CharUnits>>
15204 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
15205   E = E->IgnoreParens();
15206   switch (E->getStmtClass()) {
15207   default:
15208     break;
15209   case Stmt::CStyleCastExprClass:
15210   case Stmt::CXXStaticCastExprClass:
15211   case Stmt::ImplicitCastExprClass: {
15212     auto *CE = cast<CastExpr>(E);
15213     const Expr *From = CE->getSubExpr();
15214     switch (CE->getCastKind()) {
15215     default:
15216       break;
15217     case CK_NoOp:
15218       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15219     case CK_ArrayToPointerDecay:
15220       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15221     case CK_UncheckedDerivedToBase:
15222     case CK_DerivedToBase: {
15223       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15224       if (!P)
15225         break;
15226       return getDerivedToBaseAlignmentAndOffset(
15227           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15228     }
15229     }
15230     break;
15231   }
15232   case Stmt::CXXThisExprClass: {
15233     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15234     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
15235     return std::make_pair(Alignment, CharUnits::Zero());
15236   }
15237   case Stmt::UnaryOperatorClass: {
15238     auto *UO = cast<UnaryOperator>(E);
15239     if (UO->getOpcode() == UO_AddrOf)
15240       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
15241     break;
15242   }
15243   case Stmt::BinaryOperatorClass: {
15244     auto *BO = cast<BinaryOperator>(E);
15245     auto Opcode = BO->getOpcode();
15246     switch (Opcode) {
15247     default:
15248       break;
15249     case BO_Add:
15250     case BO_Sub: {
15251       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15252       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15253         std::swap(LHS, RHS);
15254       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15255                                                   Ctx);
15256     }
15257     case BO_Comma:
15258       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15259     }
15260     break;
15261   }
15262   }
15263   return llvm::None;
15264 }
15265 
15266 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
15267   // See if we can compute the alignment of a VarDecl and an offset from it.
15268   Optional<std::pair<CharUnits, CharUnits>> P =
15269       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
15270 
15271   if (P)
15272     return P->first.alignmentAtOffset(P->second);
15273 
15274   // If that failed, return the type's alignment.
15275   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
15276 }
15277 
15278 /// CheckCastAlign - Implements -Wcast-align, which warns when a
15279 /// pointer cast increases the alignment requirements.
15280 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
15281   // This is actually a lot of work to potentially be doing on every
15282   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15283   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15284     return;
15285 
15286   // Ignore dependent types.
15287   if (T->isDependentType() || Op->getType()->isDependentType())
15288     return;
15289 
15290   // Require that the destination be a pointer type.
15291   const PointerType *DestPtr = T->getAs<PointerType>();
15292   if (!DestPtr) return;
15293 
15294   // If the destination has alignment 1, we're done.
15295   QualType DestPointee = DestPtr->getPointeeType();
15296   if (DestPointee->isIncompleteType()) return;
15297   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15298   if (DestAlign.isOne()) return;
15299 
15300   // Require that the source be a pointer type.
15301   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15302   if (!SrcPtr) return;
15303   QualType SrcPointee = SrcPtr->getPointeeType();
15304 
15305   // Explicitly allow casts from cv void*.  We already implicitly
15306   // allowed casts to cv void*, since they have alignment 1.
15307   // Also allow casts involving incomplete types, which implicitly
15308   // includes 'void'.
15309   if (SrcPointee->isIncompleteType()) return;
15310 
15311   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15312 
15313   if (SrcAlign >= DestAlign) return;
15314 
15315   Diag(TRange.getBegin(), diag::warn_cast_align)
15316     << Op->getType() << T
15317     << static_cast<unsigned>(SrcAlign.getQuantity())
15318     << static_cast<unsigned>(DestAlign.getQuantity())
15319     << TRange << Op->getSourceRange();
15320 }
15321 
15322 /// Check whether this array fits the idiom of a size-one tail padded
15323 /// array member of a struct.
15324 ///
15325 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
15326 /// commonly used to emulate flexible arrays in C89 code.
15327 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
15328                                     const NamedDecl *ND) {
15329   if (Size != 1 || !ND) return false;
15330 
15331   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
15332   if (!FD) return false;
15333 
15334   // Don't consider sizes resulting from macro expansions or template argument
15335   // substitution to form C89 tail-padded arrays.
15336 
15337   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
15338   while (TInfo) {
15339     TypeLoc TL = TInfo->getTypeLoc();
15340     // Look through typedefs.
15341     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
15342       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
15343       TInfo = TDL->getTypeSourceInfo();
15344       continue;
15345     }
15346     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
15347       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
15348       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
15349         return false;
15350     }
15351     break;
15352   }
15353 
15354   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
15355   if (!RD) return false;
15356   if (RD->isUnion()) return false;
15357   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15358     if (!CRD->isStandardLayout()) return false;
15359   }
15360 
15361   // See if this is the last field decl in the record.
15362   const Decl *D = FD;
15363   while ((D = D->getNextDeclInContext()))
15364     if (isa<FieldDecl>(D))
15365       return false;
15366   return true;
15367 }
15368 
15369 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15370                             const ArraySubscriptExpr *ASE,
15371                             bool AllowOnePastEnd, bool IndexNegated) {
15372   // Already diagnosed by the constant evaluator.
15373   if (isConstantEvaluated())
15374     return;
15375 
15376   IndexExpr = IndexExpr->IgnoreParenImpCasts();
15377   if (IndexExpr->isValueDependent())
15378     return;
15379 
15380   const Type *EffectiveType =
15381       BaseExpr->getType()->getPointeeOrArrayElementType();
15382   BaseExpr = BaseExpr->IgnoreParenCasts();
15383   const ConstantArrayType *ArrayTy =
15384       Context.getAsConstantArrayType(BaseExpr->getType());
15385 
15386   const Type *BaseType =
15387       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15388   bool IsUnboundedArray = (BaseType == nullptr);
15389   if (EffectiveType->isDependentType() ||
15390       (!IsUnboundedArray && BaseType->isDependentType()))
15391     return;
15392 
15393   Expr::EvalResult Result;
15394   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15395     return;
15396 
15397   llvm::APSInt index = Result.Val.getInt();
15398   if (IndexNegated) {
15399     index.setIsUnsigned(false);
15400     index = -index;
15401   }
15402 
15403   const NamedDecl *ND = nullptr;
15404   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15405     ND = DRE->getDecl();
15406   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
15407     ND = ME->getMemberDecl();
15408 
15409   if (IsUnboundedArray) {
15410     if (index.isUnsigned() || !index.isNegative()) {
15411       const auto &ASTC = getASTContext();
15412       unsigned AddrBits =
15413           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
15414               EffectiveType->getCanonicalTypeInternal()));
15415       if (index.getBitWidth() < AddrBits)
15416         index = index.zext(AddrBits);
15417       Optional<CharUnits> ElemCharUnits =
15418           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15419       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15420       // pointer) bounds-checking isn't meaningful.
15421       if (!ElemCharUnits)
15422         return;
15423       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15424       // If index has more active bits than address space, we already know
15425       // we have a bounds violation to warn about.  Otherwise, compute
15426       // address of (index + 1)th element, and warn about bounds violation
15427       // only if that address exceeds address space.
15428       if (index.getActiveBits() <= AddrBits) {
15429         bool Overflow;
15430         llvm::APInt Product(index);
15431         Product += 1;
15432         Product = Product.umul_ov(ElemBytes, Overflow);
15433         if (!Overflow && Product.getActiveBits() <= AddrBits)
15434           return;
15435       }
15436 
15437       // Need to compute max possible elements in address space, since that
15438       // is included in diag message.
15439       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15440       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15441       MaxElems += 1;
15442       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15443       MaxElems = MaxElems.udiv(ElemBytes);
15444 
15445       unsigned DiagID =
15446           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15447               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15448 
15449       // Diag message shows element size in bits and in "bytes" (platform-
15450       // dependent CharUnits)
15451       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15452                           PDiag(DiagID)
15453                               << toString(index, 10, true) << AddrBits
15454                               << (unsigned)ASTC.toBits(*ElemCharUnits)
15455                               << toString(ElemBytes, 10, false)
15456                               << toString(MaxElems, 10, false)
15457                               << (unsigned)MaxElems.getLimitedValue(~0U)
15458                               << IndexExpr->getSourceRange());
15459 
15460       if (!ND) {
15461         // Try harder to find a NamedDecl to point at in the note.
15462         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15463           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15464         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15465           ND = DRE->getDecl();
15466         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15467           ND = ME->getMemberDecl();
15468       }
15469 
15470       if (ND)
15471         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15472                             PDiag(diag::note_array_declared_here) << ND);
15473     }
15474     return;
15475   }
15476 
15477   if (index.isUnsigned() || !index.isNegative()) {
15478     // It is possible that the type of the base expression after
15479     // IgnoreParenCasts is incomplete, even though the type of the base
15480     // expression before IgnoreParenCasts is complete (see PR39746 for an
15481     // example). In this case we have no information about whether the array
15482     // access exceeds the array bounds. However we can still diagnose an array
15483     // access which precedes the array bounds.
15484     if (BaseType->isIncompleteType())
15485       return;
15486 
15487     llvm::APInt size = ArrayTy->getSize();
15488     if (!size.isStrictlyPositive())
15489       return;
15490 
15491     if (BaseType != EffectiveType) {
15492       // Make sure we're comparing apples to apples when comparing index to size
15493       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15494       uint64_t array_typesize = Context.getTypeSize(BaseType);
15495       // Handle ptrarith_typesize being zero, such as when casting to void*
15496       if (!ptrarith_typesize) ptrarith_typesize = 1;
15497       if (ptrarith_typesize != array_typesize) {
15498         // There's a cast to a different size type involved
15499         uint64_t ratio = array_typesize / ptrarith_typesize;
15500         // TODO: Be smarter about handling cases where array_typesize is not a
15501         // multiple of ptrarith_typesize
15502         if (ptrarith_typesize * ratio == array_typesize)
15503           size *= llvm::APInt(size.getBitWidth(), ratio);
15504       }
15505     }
15506 
15507     if (size.getBitWidth() > index.getBitWidth())
15508       index = index.zext(size.getBitWidth());
15509     else if (size.getBitWidth() < index.getBitWidth())
15510       size = size.zext(index.getBitWidth());
15511 
15512     // For array subscripting the index must be less than size, but for pointer
15513     // arithmetic also allow the index (offset) to be equal to size since
15514     // computing the next address after the end of the array is legal and
15515     // commonly done e.g. in C++ iterators and range-based for loops.
15516     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15517       return;
15518 
15519     // Also don't warn for arrays of size 1 which are members of some
15520     // structure. These are often used to approximate flexible arrays in C89
15521     // code.
15522     if (IsTailPaddedMemberArray(*this, size, ND))
15523       return;
15524 
15525     // Suppress the warning if the subscript expression (as identified by the
15526     // ']' location) and the index expression are both from macro expansions
15527     // within a system header.
15528     if (ASE) {
15529       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15530           ASE->getRBracketLoc());
15531       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15532         SourceLocation IndexLoc =
15533             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15534         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15535           return;
15536       }
15537     }
15538 
15539     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15540                           : diag::warn_ptr_arith_exceeds_bounds;
15541 
15542     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15543                         PDiag(DiagID) << toString(index, 10, true)
15544                                       << toString(size, 10, true)
15545                                       << (unsigned)size.getLimitedValue(~0U)
15546                                       << IndexExpr->getSourceRange());
15547   } else {
15548     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15549     if (!ASE) {
15550       DiagID = diag::warn_ptr_arith_precedes_bounds;
15551       if (index.isNegative()) index = -index;
15552     }
15553 
15554     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15555                         PDiag(DiagID) << toString(index, 10, true)
15556                                       << IndexExpr->getSourceRange());
15557   }
15558 
15559   if (!ND) {
15560     // Try harder to find a NamedDecl to point at in the note.
15561     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15562       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15563     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15564       ND = DRE->getDecl();
15565     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15566       ND = ME->getMemberDecl();
15567   }
15568 
15569   if (ND)
15570     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15571                         PDiag(diag::note_array_declared_here) << ND);
15572 }
15573 
15574 void Sema::CheckArrayAccess(const Expr *expr) {
15575   int AllowOnePastEnd = 0;
15576   while (expr) {
15577     expr = expr->IgnoreParenImpCasts();
15578     switch (expr->getStmtClass()) {
15579       case Stmt::ArraySubscriptExprClass: {
15580         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15581         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15582                          AllowOnePastEnd > 0);
15583         expr = ASE->getBase();
15584         break;
15585       }
15586       case Stmt::MemberExprClass: {
15587         expr = cast<MemberExpr>(expr)->getBase();
15588         break;
15589       }
15590       case Stmt::OMPArraySectionExprClass: {
15591         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15592         if (ASE->getLowerBound())
15593           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15594                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15595         return;
15596       }
15597       case Stmt::UnaryOperatorClass: {
15598         // Only unwrap the * and & unary operators
15599         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15600         expr = UO->getSubExpr();
15601         switch (UO->getOpcode()) {
15602           case UO_AddrOf:
15603             AllowOnePastEnd++;
15604             break;
15605           case UO_Deref:
15606             AllowOnePastEnd--;
15607             break;
15608           default:
15609             return;
15610         }
15611         break;
15612       }
15613       case Stmt::ConditionalOperatorClass: {
15614         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15615         if (const Expr *lhs = cond->getLHS())
15616           CheckArrayAccess(lhs);
15617         if (const Expr *rhs = cond->getRHS())
15618           CheckArrayAccess(rhs);
15619         return;
15620       }
15621       case Stmt::CXXOperatorCallExprClass: {
15622         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15623         for (const auto *Arg : OCE->arguments())
15624           CheckArrayAccess(Arg);
15625         return;
15626       }
15627       default:
15628         return;
15629     }
15630   }
15631 }
15632 
15633 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15634 
15635 namespace {
15636 
15637 struct RetainCycleOwner {
15638   VarDecl *Variable = nullptr;
15639   SourceRange Range;
15640   SourceLocation Loc;
15641   bool Indirect = false;
15642 
15643   RetainCycleOwner() = default;
15644 
15645   void setLocsFrom(Expr *e) {
15646     Loc = e->getExprLoc();
15647     Range = e->getSourceRange();
15648   }
15649 };
15650 
15651 } // namespace
15652 
15653 /// Consider whether capturing the given variable can possibly lead to
15654 /// a retain cycle.
15655 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15656   // In ARC, it's captured strongly iff the variable has __strong
15657   // lifetime.  In MRR, it's captured strongly if the variable is
15658   // __block and has an appropriate type.
15659   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15660     return false;
15661 
15662   owner.Variable = var;
15663   if (ref)
15664     owner.setLocsFrom(ref);
15665   return true;
15666 }
15667 
15668 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15669   while (true) {
15670     e = e->IgnoreParens();
15671     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15672       switch (cast->getCastKind()) {
15673       case CK_BitCast:
15674       case CK_LValueBitCast:
15675       case CK_LValueToRValue:
15676       case CK_ARCReclaimReturnedObject:
15677         e = cast->getSubExpr();
15678         continue;
15679 
15680       default:
15681         return false;
15682       }
15683     }
15684 
15685     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15686       ObjCIvarDecl *ivar = ref->getDecl();
15687       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15688         return false;
15689 
15690       // Try to find a retain cycle in the base.
15691       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15692         return false;
15693 
15694       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15695       owner.Indirect = true;
15696       return true;
15697     }
15698 
15699     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15700       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15701       if (!var) return false;
15702       return considerVariable(var, ref, owner);
15703     }
15704 
15705     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15706       if (member->isArrow()) return false;
15707 
15708       // Don't count this as an indirect ownership.
15709       e = member->getBase();
15710       continue;
15711     }
15712 
15713     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15714       // Only pay attention to pseudo-objects on property references.
15715       ObjCPropertyRefExpr *pre
15716         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15717                                               ->IgnoreParens());
15718       if (!pre) return false;
15719       if (pre->isImplicitProperty()) return false;
15720       ObjCPropertyDecl *property = pre->getExplicitProperty();
15721       if (!property->isRetaining() &&
15722           !(property->getPropertyIvarDecl() &&
15723             property->getPropertyIvarDecl()->getType()
15724               .getObjCLifetime() == Qualifiers::OCL_Strong))
15725           return false;
15726 
15727       owner.Indirect = true;
15728       if (pre->isSuperReceiver()) {
15729         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15730         if (!owner.Variable)
15731           return false;
15732         owner.Loc = pre->getLocation();
15733         owner.Range = pre->getSourceRange();
15734         return true;
15735       }
15736       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15737                               ->getSourceExpr());
15738       continue;
15739     }
15740 
15741     // Array ivars?
15742 
15743     return false;
15744   }
15745 }
15746 
15747 namespace {
15748 
15749   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15750     ASTContext &Context;
15751     VarDecl *Variable;
15752     Expr *Capturer = nullptr;
15753     bool VarWillBeReased = false;
15754 
15755     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15756         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15757           Context(Context), Variable(variable) {}
15758 
15759     void VisitDeclRefExpr(DeclRefExpr *ref) {
15760       if (ref->getDecl() == Variable && !Capturer)
15761         Capturer = ref;
15762     }
15763 
15764     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15765       if (Capturer) return;
15766       Visit(ref->getBase());
15767       if (Capturer && ref->isFreeIvar())
15768         Capturer = ref;
15769     }
15770 
15771     void VisitBlockExpr(BlockExpr *block) {
15772       // Look inside nested blocks
15773       if (block->getBlockDecl()->capturesVariable(Variable))
15774         Visit(block->getBlockDecl()->getBody());
15775     }
15776 
15777     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15778       if (Capturer) return;
15779       if (OVE->getSourceExpr())
15780         Visit(OVE->getSourceExpr());
15781     }
15782 
15783     void VisitBinaryOperator(BinaryOperator *BinOp) {
15784       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15785         return;
15786       Expr *LHS = BinOp->getLHS();
15787       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15788         if (DRE->getDecl() != Variable)
15789           return;
15790         if (Expr *RHS = BinOp->getRHS()) {
15791           RHS = RHS->IgnoreParenCasts();
15792           Optional<llvm::APSInt> Value;
15793           VarWillBeReased =
15794               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15795                *Value == 0);
15796         }
15797       }
15798     }
15799   };
15800 
15801 } // namespace
15802 
15803 /// Check whether the given argument is a block which captures a
15804 /// variable.
15805 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15806   assert(owner.Variable && owner.Loc.isValid());
15807 
15808   e = e->IgnoreParenCasts();
15809 
15810   // Look through [^{...} copy] and Block_copy(^{...}).
15811   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15812     Selector Cmd = ME->getSelector();
15813     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15814       e = ME->getInstanceReceiver();
15815       if (!e)
15816         return nullptr;
15817       e = e->IgnoreParenCasts();
15818     }
15819   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15820     if (CE->getNumArgs() == 1) {
15821       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15822       if (Fn) {
15823         const IdentifierInfo *FnI = Fn->getIdentifier();
15824         if (FnI && FnI->isStr("_Block_copy")) {
15825           e = CE->getArg(0)->IgnoreParenCasts();
15826         }
15827       }
15828     }
15829   }
15830 
15831   BlockExpr *block = dyn_cast<BlockExpr>(e);
15832   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15833     return nullptr;
15834 
15835   FindCaptureVisitor visitor(S.Context, owner.Variable);
15836   visitor.Visit(block->getBlockDecl()->getBody());
15837   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15838 }
15839 
15840 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15841                                 RetainCycleOwner &owner) {
15842   assert(capturer);
15843   assert(owner.Variable && owner.Loc.isValid());
15844 
15845   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15846     << owner.Variable << capturer->getSourceRange();
15847   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15848     << owner.Indirect << owner.Range;
15849 }
15850 
15851 /// Check for a keyword selector that starts with the word 'add' or
15852 /// 'set'.
15853 static bool isSetterLikeSelector(Selector sel) {
15854   if (sel.isUnarySelector()) return false;
15855 
15856   StringRef str = sel.getNameForSlot(0);
15857   while (!str.empty() && str.front() == '_') str = str.substr(1);
15858   if (str.startswith("set"))
15859     str = str.substr(3);
15860   else if (str.startswith("add")) {
15861     // Specially allow 'addOperationWithBlock:'.
15862     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15863       return false;
15864     str = str.substr(3);
15865   }
15866   else
15867     return false;
15868 
15869   if (str.empty()) return true;
15870   return !isLowercase(str.front());
15871 }
15872 
15873 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15874                                                     ObjCMessageExpr *Message) {
15875   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15876                                                 Message->getReceiverInterface(),
15877                                                 NSAPI::ClassId_NSMutableArray);
15878   if (!IsMutableArray) {
15879     return None;
15880   }
15881 
15882   Selector Sel = Message->getSelector();
15883 
15884   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15885     S.NSAPIObj->getNSArrayMethodKind(Sel);
15886   if (!MKOpt) {
15887     return None;
15888   }
15889 
15890   NSAPI::NSArrayMethodKind MK = *MKOpt;
15891 
15892   switch (MK) {
15893     case NSAPI::NSMutableArr_addObject:
15894     case NSAPI::NSMutableArr_insertObjectAtIndex:
15895     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15896       return 0;
15897     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15898       return 1;
15899 
15900     default:
15901       return None;
15902   }
15903 
15904   return None;
15905 }
15906 
15907 static
15908 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15909                                                   ObjCMessageExpr *Message) {
15910   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15911                                             Message->getReceiverInterface(),
15912                                             NSAPI::ClassId_NSMutableDictionary);
15913   if (!IsMutableDictionary) {
15914     return None;
15915   }
15916 
15917   Selector Sel = Message->getSelector();
15918 
15919   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15920     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15921   if (!MKOpt) {
15922     return None;
15923   }
15924 
15925   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15926 
15927   switch (MK) {
15928     case NSAPI::NSMutableDict_setObjectForKey:
15929     case NSAPI::NSMutableDict_setValueForKey:
15930     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15931       return 0;
15932 
15933     default:
15934       return None;
15935   }
15936 
15937   return None;
15938 }
15939 
15940 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15941   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15942                                                 Message->getReceiverInterface(),
15943                                                 NSAPI::ClassId_NSMutableSet);
15944 
15945   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15946                                             Message->getReceiverInterface(),
15947                                             NSAPI::ClassId_NSMutableOrderedSet);
15948   if (!IsMutableSet && !IsMutableOrderedSet) {
15949     return None;
15950   }
15951 
15952   Selector Sel = Message->getSelector();
15953 
15954   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15955   if (!MKOpt) {
15956     return None;
15957   }
15958 
15959   NSAPI::NSSetMethodKind MK = *MKOpt;
15960 
15961   switch (MK) {
15962     case NSAPI::NSMutableSet_addObject:
15963     case NSAPI::NSOrderedSet_setObjectAtIndex:
15964     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15965     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15966       return 0;
15967     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15968       return 1;
15969   }
15970 
15971   return None;
15972 }
15973 
15974 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15975   if (!Message->isInstanceMessage()) {
15976     return;
15977   }
15978 
15979   Optional<int> ArgOpt;
15980 
15981   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15982       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15983       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15984     return;
15985   }
15986 
15987   int ArgIndex = *ArgOpt;
15988 
15989   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15990   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15991     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15992   }
15993 
15994   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15995     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15996       if (ArgRE->isObjCSelfExpr()) {
15997         Diag(Message->getSourceRange().getBegin(),
15998              diag::warn_objc_circular_container)
15999           << ArgRE->getDecl() << StringRef("'super'");
16000       }
16001     }
16002   } else {
16003     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
16004 
16005     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
16006       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
16007     }
16008 
16009     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
16010       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
16011         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
16012           ValueDecl *Decl = ReceiverRE->getDecl();
16013           Diag(Message->getSourceRange().getBegin(),
16014                diag::warn_objc_circular_container)
16015             << Decl << Decl;
16016           if (!ArgRE->isObjCSelfExpr()) {
16017             Diag(Decl->getLocation(),
16018                  diag::note_objc_circular_container_declared_here)
16019               << Decl;
16020           }
16021         }
16022       }
16023     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
16024       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
16025         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
16026           ObjCIvarDecl *Decl = IvarRE->getDecl();
16027           Diag(Message->getSourceRange().getBegin(),
16028                diag::warn_objc_circular_container)
16029             << Decl << Decl;
16030           Diag(Decl->getLocation(),
16031                diag::note_objc_circular_container_declared_here)
16032             << Decl;
16033         }
16034       }
16035     }
16036   }
16037 }
16038 
16039 /// Check a message send to see if it's likely to cause a retain cycle.
16040 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
16041   // Only check instance methods whose selector looks like a setter.
16042   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
16043     return;
16044 
16045   // Try to find a variable that the receiver is strongly owned by.
16046   RetainCycleOwner owner;
16047   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
16048     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
16049       return;
16050   } else {
16051     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
16052     owner.Variable = getCurMethodDecl()->getSelfDecl();
16053     owner.Loc = msg->getSuperLoc();
16054     owner.Range = msg->getSuperLoc();
16055   }
16056 
16057   // Check whether the receiver is captured by any of the arguments.
16058   const ObjCMethodDecl *MD = msg->getMethodDecl();
16059   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
16060     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
16061       // noescape blocks should not be retained by the method.
16062       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
16063         continue;
16064       return diagnoseRetainCycle(*this, capturer, owner);
16065     }
16066   }
16067 }
16068 
16069 /// Check a property assign to see if it's likely to cause a retain cycle.
16070 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
16071   RetainCycleOwner owner;
16072   if (!findRetainCycleOwner(*this, receiver, owner))
16073     return;
16074 
16075   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
16076     diagnoseRetainCycle(*this, capturer, owner);
16077 }
16078 
16079 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
16080   RetainCycleOwner Owner;
16081   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
16082     return;
16083 
16084   // Because we don't have an expression for the variable, we have to set the
16085   // location explicitly here.
16086   Owner.Loc = Var->getLocation();
16087   Owner.Range = Var->getSourceRange();
16088 
16089   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
16090     diagnoseRetainCycle(*this, Capturer, Owner);
16091 }
16092 
16093 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
16094                                      Expr *RHS, bool isProperty) {
16095   // Check if RHS is an Objective-C object literal, which also can get
16096   // immediately zapped in a weak reference.  Note that we explicitly
16097   // allow ObjCStringLiterals, since those are designed to never really die.
16098   RHS = RHS->IgnoreParenImpCasts();
16099 
16100   // This enum needs to match with the 'select' in
16101   // warn_objc_arc_literal_assign (off-by-1).
16102   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
16103   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
16104     return false;
16105 
16106   S.Diag(Loc, diag::warn_arc_literal_assign)
16107     << (unsigned) Kind
16108     << (isProperty ? 0 : 1)
16109     << RHS->getSourceRange();
16110 
16111   return true;
16112 }
16113 
16114 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
16115                                     Qualifiers::ObjCLifetime LT,
16116                                     Expr *RHS, bool isProperty) {
16117   // Strip off any implicit cast added to get to the one ARC-specific.
16118   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16119     if (cast->getCastKind() == CK_ARCConsumeObject) {
16120       S.Diag(Loc, diag::warn_arc_retained_assign)
16121         << (LT == Qualifiers::OCL_ExplicitNone)
16122         << (isProperty ? 0 : 1)
16123         << RHS->getSourceRange();
16124       return true;
16125     }
16126     RHS = cast->getSubExpr();
16127   }
16128 
16129   if (LT == Qualifiers::OCL_Weak &&
16130       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16131     return true;
16132 
16133   return false;
16134 }
16135 
16136 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
16137                               QualType LHS, Expr *RHS) {
16138   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
16139 
16140   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
16141     return false;
16142 
16143   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
16144     return true;
16145 
16146   return false;
16147 }
16148 
16149 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
16150                               Expr *LHS, Expr *RHS) {
16151   QualType LHSType;
16152   // PropertyRef on LHS type need be directly obtained from
16153   // its declaration as it has a PseudoType.
16154   ObjCPropertyRefExpr *PRE
16155     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
16156   if (PRE && !PRE->isImplicitProperty()) {
16157     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16158     if (PD)
16159       LHSType = PD->getType();
16160   }
16161 
16162   if (LHSType.isNull())
16163     LHSType = LHS->getType();
16164 
16165   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
16166 
16167   if (LT == Qualifiers::OCL_Weak) {
16168     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
16169       getCurFunction()->markSafeWeakUse(LHS);
16170   }
16171 
16172   if (checkUnsafeAssigns(Loc, LHSType, RHS))
16173     return;
16174 
16175   // FIXME. Check for other life times.
16176   if (LT != Qualifiers::OCL_None)
16177     return;
16178 
16179   if (PRE) {
16180     if (PRE->isImplicitProperty())
16181       return;
16182     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16183     if (!PD)
16184       return;
16185 
16186     unsigned Attributes = PD->getPropertyAttributes();
16187     if (Attributes & ObjCPropertyAttribute::kind_assign) {
16188       // when 'assign' attribute was not explicitly specified
16189       // by user, ignore it and rely on property type itself
16190       // for lifetime info.
16191       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16192       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16193           LHSType->isObjCRetainableType())
16194         return;
16195 
16196       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16197         if (cast->getCastKind() == CK_ARCConsumeObject) {
16198           Diag(Loc, diag::warn_arc_retained_property_assign)
16199           << RHS->getSourceRange();
16200           return;
16201         }
16202         RHS = cast->getSubExpr();
16203       }
16204     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16205       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
16206         return;
16207     }
16208   }
16209 }
16210 
16211 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16212 
16213 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16214                                         SourceLocation StmtLoc,
16215                                         const NullStmt *Body) {
16216   // Do not warn if the body is a macro that expands to nothing, e.g:
16217   //
16218   // #define CALL(x)
16219   // if (condition)
16220   //   CALL(0);
16221   if (Body->hasLeadingEmptyMacro())
16222     return false;
16223 
16224   // Get line numbers of statement and body.
16225   bool StmtLineInvalid;
16226   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16227                                                       &StmtLineInvalid);
16228   if (StmtLineInvalid)
16229     return false;
16230 
16231   bool BodyLineInvalid;
16232   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16233                                                       &BodyLineInvalid);
16234   if (BodyLineInvalid)
16235     return false;
16236 
16237   // Warn if null statement and body are on the same line.
16238   if (StmtLine != BodyLine)
16239     return false;
16240 
16241   return true;
16242 }
16243 
16244 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
16245                                  const Stmt *Body,
16246                                  unsigned DiagID) {
16247   // Since this is a syntactic check, don't emit diagnostic for template
16248   // instantiations, this just adds noise.
16249   if (CurrentInstantiationScope)
16250     return;
16251 
16252   // The body should be a null statement.
16253   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16254   if (!NBody)
16255     return;
16256 
16257   // Do the usual checks.
16258   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16259     return;
16260 
16261   Diag(NBody->getSemiLoc(), DiagID);
16262   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16263 }
16264 
16265 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
16266                                  const Stmt *PossibleBody) {
16267   assert(!CurrentInstantiationScope); // Ensured by caller
16268 
16269   SourceLocation StmtLoc;
16270   const Stmt *Body;
16271   unsigned DiagID;
16272   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16273     StmtLoc = FS->getRParenLoc();
16274     Body = FS->getBody();
16275     DiagID = diag::warn_empty_for_body;
16276   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16277     StmtLoc = WS->getCond()->getSourceRange().getEnd();
16278     Body = WS->getBody();
16279     DiagID = diag::warn_empty_while_body;
16280   } else
16281     return; // Neither `for' nor `while'.
16282 
16283   // The body should be a null statement.
16284   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16285   if (!NBody)
16286     return;
16287 
16288   // Skip expensive checks if diagnostic is disabled.
16289   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16290     return;
16291 
16292   // Do the usual checks.
16293   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16294     return;
16295 
16296   // `for(...);' and `while(...);' are popular idioms, so in order to keep
16297   // noise level low, emit diagnostics only if for/while is followed by a
16298   // CompoundStmt, e.g.:
16299   //    for (int i = 0; i < n; i++);
16300   //    {
16301   //      a(i);
16302   //    }
16303   // or if for/while is followed by a statement with more indentation
16304   // than for/while itself:
16305   //    for (int i = 0; i < n; i++);
16306   //      a(i);
16307   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16308   if (!ProbableTypo) {
16309     bool BodyColInvalid;
16310     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16311         PossibleBody->getBeginLoc(), &BodyColInvalid);
16312     if (BodyColInvalid)
16313       return;
16314 
16315     bool StmtColInvalid;
16316     unsigned StmtCol =
16317         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16318     if (StmtColInvalid)
16319       return;
16320 
16321     if (BodyCol > StmtCol)
16322       ProbableTypo = true;
16323   }
16324 
16325   if (ProbableTypo) {
16326     Diag(NBody->getSemiLoc(), DiagID);
16327     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16328   }
16329 }
16330 
16331 //===--- CHECK: Warn on self move with std::move. -------------------------===//
16332 
16333 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
16334 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16335                              SourceLocation OpLoc) {
16336   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16337     return;
16338 
16339   if (inTemplateInstantiation())
16340     return;
16341 
16342   // Strip parens and casts away.
16343   LHSExpr = LHSExpr->IgnoreParenImpCasts();
16344   RHSExpr = RHSExpr->IgnoreParenImpCasts();
16345 
16346   // Check for a call expression
16347   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
16348   if (!CE || CE->getNumArgs() != 1)
16349     return;
16350 
16351   // Check for a call to std::move
16352   if (!CE->isCallToStdMove())
16353     return;
16354 
16355   // Get argument from std::move
16356   RHSExpr = CE->getArg(0);
16357 
16358   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16359   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16360 
16361   // Two DeclRefExpr's, check that the decls are the same.
16362   if (LHSDeclRef && RHSDeclRef) {
16363     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16364       return;
16365     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16366         RHSDeclRef->getDecl()->getCanonicalDecl())
16367       return;
16368 
16369     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16370                                         << LHSExpr->getSourceRange()
16371                                         << RHSExpr->getSourceRange();
16372     return;
16373   }
16374 
16375   // Member variables require a different approach to check for self moves.
16376   // MemberExpr's are the same if every nested MemberExpr refers to the same
16377   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16378   // the base Expr's are CXXThisExpr's.
16379   const Expr *LHSBase = LHSExpr;
16380   const Expr *RHSBase = RHSExpr;
16381   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16382   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16383   if (!LHSME || !RHSME)
16384     return;
16385 
16386   while (LHSME && RHSME) {
16387     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16388         RHSME->getMemberDecl()->getCanonicalDecl())
16389       return;
16390 
16391     LHSBase = LHSME->getBase();
16392     RHSBase = RHSME->getBase();
16393     LHSME = dyn_cast<MemberExpr>(LHSBase);
16394     RHSME = dyn_cast<MemberExpr>(RHSBase);
16395   }
16396 
16397   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16398   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16399   if (LHSDeclRef && RHSDeclRef) {
16400     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16401       return;
16402     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16403         RHSDeclRef->getDecl()->getCanonicalDecl())
16404       return;
16405 
16406     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16407                                         << LHSExpr->getSourceRange()
16408                                         << RHSExpr->getSourceRange();
16409     return;
16410   }
16411 
16412   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16413     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16414                                         << LHSExpr->getSourceRange()
16415                                         << RHSExpr->getSourceRange();
16416 }
16417 
16418 //===--- Layout compatibility ----------------------------------------------//
16419 
16420 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
16421 
16422 /// Check if two enumeration types are layout-compatible.
16423 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
16424   // C++11 [dcl.enum] p8:
16425   // Two enumeration types are layout-compatible if they have the same
16426   // underlying type.
16427   return ED1->isComplete() && ED2->isComplete() &&
16428          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16429 }
16430 
16431 /// Check if two fields are layout-compatible.
16432 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
16433                                FieldDecl *Field2) {
16434   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16435     return false;
16436 
16437   if (Field1->isBitField() != Field2->isBitField())
16438     return false;
16439 
16440   if (Field1->isBitField()) {
16441     // Make sure that the bit-fields are the same length.
16442     unsigned Bits1 = Field1->getBitWidthValue(C);
16443     unsigned Bits2 = Field2->getBitWidthValue(C);
16444 
16445     if (Bits1 != Bits2)
16446       return false;
16447   }
16448 
16449   return true;
16450 }
16451 
16452 /// Check if two standard-layout structs are layout-compatible.
16453 /// (C++11 [class.mem] p17)
16454 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
16455                                      RecordDecl *RD2) {
16456   // If both records are C++ classes, check that base classes match.
16457   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
16458     // If one of records is a CXXRecordDecl we are in C++ mode,
16459     // thus the other one is a CXXRecordDecl, too.
16460     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
16461     // Check number of base classes.
16462     if (D1CXX->getNumBases() != D2CXX->getNumBases())
16463       return false;
16464 
16465     // Check the base classes.
16466     for (CXXRecordDecl::base_class_const_iterator
16467                Base1 = D1CXX->bases_begin(),
16468            BaseEnd1 = D1CXX->bases_end(),
16469               Base2 = D2CXX->bases_begin();
16470          Base1 != BaseEnd1;
16471          ++Base1, ++Base2) {
16472       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16473         return false;
16474     }
16475   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16476     // If only RD2 is a C++ class, it should have zero base classes.
16477     if (D2CXX->getNumBases() > 0)
16478       return false;
16479   }
16480 
16481   // Check the fields.
16482   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16483                              Field2End = RD2->field_end(),
16484                              Field1 = RD1->field_begin(),
16485                              Field1End = RD1->field_end();
16486   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16487     if (!isLayoutCompatible(C, *Field1, *Field2))
16488       return false;
16489   }
16490   if (Field1 != Field1End || Field2 != Field2End)
16491     return false;
16492 
16493   return true;
16494 }
16495 
16496 /// Check if two standard-layout unions are layout-compatible.
16497 /// (C++11 [class.mem] p18)
16498 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16499                                     RecordDecl *RD2) {
16500   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16501   for (auto *Field2 : RD2->fields())
16502     UnmatchedFields.insert(Field2);
16503 
16504   for (auto *Field1 : RD1->fields()) {
16505     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16506         I = UnmatchedFields.begin(),
16507         E = UnmatchedFields.end();
16508 
16509     for ( ; I != E; ++I) {
16510       if (isLayoutCompatible(C, Field1, *I)) {
16511         bool Result = UnmatchedFields.erase(*I);
16512         (void) Result;
16513         assert(Result);
16514         break;
16515       }
16516     }
16517     if (I == E)
16518       return false;
16519   }
16520 
16521   return UnmatchedFields.empty();
16522 }
16523 
16524 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16525                                RecordDecl *RD2) {
16526   if (RD1->isUnion() != RD2->isUnion())
16527     return false;
16528 
16529   if (RD1->isUnion())
16530     return isLayoutCompatibleUnion(C, RD1, RD2);
16531   else
16532     return isLayoutCompatibleStruct(C, RD1, RD2);
16533 }
16534 
16535 /// Check if two types are layout-compatible in C++11 sense.
16536 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16537   if (T1.isNull() || T2.isNull())
16538     return false;
16539 
16540   // C++11 [basic.types] p11:
16541   // If two types T1 and T2 are the same type, then T1 and T2 are
16542   // layout-compatible types.
16543   if (C.hasSameType(T1, T2))
16544     return true;
16545 
16546   T1 = T1.getCanonicalType().getUnqualifiedType();
16547   T2 = T2.getCanonicalType().getUnqualifiedType();
16548 
16549   const Type::TypeClass TC1 = T1->getTypeClass();
16550   const Type::TypeClass TC2 = T2->getTypeClass();
16551 
16552   if (TC1 != TC2)
16553     return false;
16554 
16555   if (TC1 == Type::Enum) {
16556     return isLayoutCompatible(C,
16557                               cast<EnumType>(T1)->getDecl(),
16558                               cast<EnumType>(T2)->getDecl());
16559   } else if (TC1 == Type::Record) {
16560     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16561       return false;
16562 
16563     return isLayoutCompatible(C,
16564                               cast<RecordType>(T1)->getDecl(),
16565                               cast<RecordType>(T2)->getDecl());
16566   }
16567 
16568   return false;
16569 }
16570 
16571 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16572 
16573 /// Given a type tag expression find the type tag itself.
16574 ///
16575 /// \param TypeExpr Type tag expression, as it appears in user's code.
16576 ///
16577 /// \param VD Declaration of an identifier that appears in a type tag.
16578 ///
16579 /// \param MagicValue Type tag magic value.
16580 ///
16581 /// \param isConstantEvaluated whether the evalaution should be performed in
16582 
16583 /// constant context.
16584 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16585                             const ValueDecl **VD, uint64_t *MagicValue,
16586                             bool isConstantEvaluated) {
16587   while(true) {
16588     if (!TypeExpr)
16589       return false;
16590 
16591     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16592 
16593     switch (TypeExpr->getStmtClass()) {
16594     case Stmt::UnaryOperatorClass: {
16595       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16596       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16597         TypeExpr = UO->getSubExpr();
16598         continue;
16599       }
16600       return false;
16601     }
16602 
16603     case Stmt::DeclRefExprClass: {
16604       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16605       *VD = DRE->getDecl();
16606       return true;
16607     }
16608 
16609     case Stmt::IntegerLiteralClass: {
16610       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16611       llvm::APInt MagicValueAPInt = IL->getValue();
16612       if (MagicValueAPInt.getActiveBits() <= 64) {
16613         *MagicValue = MagicValueAPInt.getZExtValue();
16614         return true;
16615       } else
16616         return false;
16617     }
16618 
16619     case Stmt::BinaryConditionalOperatorClass:
16620     case Stmt::ConditionalOperatorClass: {
16621       const AbstractConditionalOperator *ACO =
16622           cast<AbstractConditionalOperator>(TypeExpr);
16623       bool Result;
16624       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16625                                                      isConstantEvaluated)) {
16626         if (Result)
16627           TypeExpr = ACO->getTrueExpr();
16628         else
16629           TypeExpr = ACO->getFalseExpr();
16630         continue;
16631       }
16632       return false;
16633     }
16634 
16635     case Stmt::BinaryOperatorClass: {
16636       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16637       if (BO->getOpcode() == BO_Comma) {
16638         TypeExpr = BO->getRHS();
16639         continue;
16640       }
16641       return false;
16642     }
16643 
16644     default:
16645       return false;
16646     }
16647   }
16648 }
16649 
16650 /// Retrieve the C type corresponding to type tag TypeExpr.
16651 ///
16652 /// \param TypeExpr Expression that specifies a type tag.
16653 ///
16654 /// \param MagicValues Registered magic values.
16655 ///
16656 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16657 ///        kind.
16658 ///
16659 /// \param TypeInfo Information about the corresponding C type.
16660 ///
16661 /// \param isConstantEvaluated whether the evalaution should be performed in
16662 /// constant context.
16663 ///
16664 /// \returns true if the corresponding C type was found.
16665 static bool GetMatchingCType(
16666     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16667     const ASTContext &Ctx,
16668     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16669         *MagicValues,
16670     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16671     bool isConstantEvaluated) {
16672   FoundWrongKind = false;
16673 
16674   // Variable declaration that has type_tag_for_datatype attribute.
16675   const ValueDecl *VD = nullptr;
16676 
16677   uint64_t MagicValue;
16678 
16679   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16680     return false;
16681 
16682   if (VD) {
16683     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16684       if (I->getArgumentKind() != ArgumentKind) {
16685         FoundWrongKind = true;
16686         return false;
16687       }
16688       TypeInfo.Type = I->getMatchingCType();
16689       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16690       TypeInfo.MustBeNull = I->getMustBeNull();
16691       return true;
16692     }
16693     return false;
16694   }
16695 
16696   if (!MagicValues)
16697     return false;
16698 
16699   llvm::DenseMap<Sema::TypeTagMagicValue,
16700                  Sema::TypeTagData>::const_iterator I =
16701       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16702   if (I == MagicValues->end())
16703     return false;
16704 
16705   TypeInfo = I->second;
16706   return true;
16707 }
16708 
16709 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16710                                       uint64_t MagicValue, QualType Type,
16711                                       bool LayoutCompatible,
16712                                       bool MustBeNull) {
16713   if (!TypeTagForDatatypeMagicValues)
16714     TypeTagForDatatypeMagicValues.reset(
16715         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16716 
16717   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16718   (*TypeTagForDatatypeMagicValues)[Magic] =
16719       TypeTagData(Type, LayoutCompatible, MustBeNull);
16720 }
16721 
16722 static bool IsSameCharType(QualType T1, QualType T2) {
16723   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16724   if (!BT1)
16725     return false;
16726 
16727   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16728   if (!BT2)
16729     return false;
16730 
16731   BuiltinType::Kind T1Kind = BT1->getKind();
16732   BuiltinType::Kind T2Kind = BT2->getKind();
16733 
16734   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16735          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16736          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16737          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16738 }
16739 
16740 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16741                                     const ArrayRef<const Expr *> ExprArgs,
16742                                     SourceLocation CallSiteLoc) {
16743   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16744   bool IsPointerAttr = Attr->getIsPointer();
16745 
16746   // Retrieve the argument representing the 'type_tag'.
16747   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16748   if (TypeTagIdxAST >= ExprArgs.size()) {
16749     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16750         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16751     return;
16752   }
16753   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16754   bool FoundWrongKind;
16755   TypeTagData TypeInfo;
16756   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16757                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16758                         TypeInfo, isConstantEvaluated())) {
16759     if (FoundWrongKind)
16760       Diag(TypeTagExpr->getExprLoc(),
16761            diag::warn_type_tag_for_datatype_wrong_kind)
16762         << TypeTagExpr->getSourceRange();
16763     return;
16764   }
16765 
16766   // Retrieve the argument representing the 'arg_idx'.
16767   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16768   if (ArgumentIdxAST >= ExprArgs.size()) {
16769     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16770         << 1 << Attr->getArgumentIdx().getSourceIndex();
16771     return;
16772   }
16773   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16774   if (IsPointerAttr) {
16775     // Skip implicit cast of pointer to `void *' (as a function argument).
16776     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16777       if (ICE->getType()->isVoidPointerType() &&
16778           ICE->getCastKind() == CK_BitCast)
16779         ArgumentExpr = ICE->getSubExpr();
16780   }
16781   QualType ArgumentType = ArgumentExpr->getType();
16782 
16783   // Passing a `void*' pointer shouldn't trigger a warning.
16784   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16785     return;
16786 
16787   if (TypeInfo.MustBeNull) {
16788     // Type tag with matching void type requires a null pointer.
16789     if (!ArgumentExpr->isNullPointerConstant(Context,
16790                                              Expr::NPC_ValueDependentIsNotNull)) {
16791       Diag(ArgumentExpr->getExprLoc(),
16792            diag::warn_type_safety_null_pointer_required)
16793           << ArgumentKind->getName()
16794           << ArgumentExpr->getSourceRange()
16795           << TypeTagExpr->getSourceRange();
16796     }
16797     return;
16798   }
16799 
16800   QualType RequiredType = TypeInfo.Type;
16801   if (IsPointerAttr)
16802     RequiredType = Context.getPointerType(RequiredType);
16803 
16804   bool mismatch = false;
16805   if (!TypeInfo.LayoutCompatible) {
16806     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16807 
16808     // C++11 [basic.fundamental] p1:
16809     // Plain char, signed char, and unsigned char are three distinct types.
16810     //
16811     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16812     // char' depending on the current char signedness mode.
16813     if (mismatch)
16814       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16815                                            RequiredType->getPointeeType())) ||
16816           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16817         mismatch = false;
16818   } else
16819     if (IsPointerAttr)
16820       mismatch = !isLayoutCompatible(Context,
16821                                      ArgumentType->getPointeeType(),
16822                                      RequiredType->getPointeeType());
16823     else
16824       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16825 
16826   if (mismatch)
16827     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16828         << ArgumentType << ArgumentKind
16829         << TypeInfo.LayoutCompatible << RequiredType
16830         << ArgumentExpr->getSourceRange()
16831         << TypeTagExpr->getSourceRange();
16832 }
16833 
16834 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16835                                          CharUnits Alignment) {
16836   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16837 }
16838 
16839 void Sema::DiagnoseMisalignedMembers() {
16840   for (MisalignedMember &m : MisalignedMembers) {
16841     const NamedDecl *ND = m.RD;
16842     if (ND->getName().empty()) {
16843       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16844         ND = TD;
16845     }
16846     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16847         << m.MD << ND << m.E->getSourceRange();
16848   }
16849   MisalignedMembers.clear();
16850 }
16851 
16852 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16853   E = E->IgnoreParens();
16854   if (!T->isPointerType() && !T->isIntegerType())
16855     return;
16856   if (isa<UnaryOperator>(E) &&
16857       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16858     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16859     if (isa<MemberExpr>(Op)) {
16860       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16861       if (MA != MisalignedMembers.end() &&
16862           (T->isIntegerType() ||
16863            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16864                                    Context.getTypeAlignInChars(
16865                                        T->getPointeeType()) <= MA->Alignment))))
16866         MisalignedMembers.erase(MA);
16867     }
16868   }
16869 }
16870 
16871 void Sema::RefersToMemberWithReducedAlignment(
16872     Expr *E,
16873     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16874         Action) {
16875   const auto *ME = dyn_cast<MemberExpr>(E);
16876   if (!ME)
16877     return;
16878 
16879   // No need to check expressions with an __unaligned-qualified type.
16880   if (E->getType().getQualifiers().hasUnaligned())
16881     return;
16882 
16883   // For a chain of MemberExpr like "a.b.c.d" this list
16884   // will keep FieldDecl's like [d, c, b].
16885   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16886   const MemberExpr *TopME = nullptr;
16887   bool AnyIsPacked = false;
16888   do {
16889     QualType BaseType = ME->getBase()->getType();
16890     if (BaseType->isDependentType())
16891       return;
16892     if (ME->isArrow())
16893       BaseType = BaseType->getPointeeType();
16894     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16895     if (RD->isInvalidDecl())
16896       return;
16897 
16898     ValueDecl *MD = ME->getMemberDecl();
16899     auto *FD = dyn_cast<FieldDecl>(MD);
16900     // We do not care about non-data members.
16901     if (!FD || FD->isInvalidDecl())
16902       return;
16903 
16904     AnyIsPacked =
16905         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16906     ReverseMemberChain.push_back(FD);
16907 
16908     TopME = ME;
16909     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16910   } while (ME);
16911   assert(TopME && "We did not compute a topmost MemberExpr!");
16912 
16913   // Not the scope of this diagnostic.
16914   if (!AnyIsPacked)
16915     return;
16916 
16917   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16918   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16919   // TODO: The innermost base of the member expression may be too complicated.
16920   // For now, just disregard these cases. This is left for future
16921   // improvement.
16922   if (!DRE && !isa<CXXThisExpr>(TopBase))
16923       return;
16924 
16925   // Alignment expected by the whole expression.
16926   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16927 
16928   // No need to do anything else with this case.
16929   if (ExpectedAlignment.isOne())
16930     return;
16931 
16932   // Synthesize offset of the whole access.
16933   CharUnits Offset;
16934   for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16935     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16936 
16937   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16938   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16939       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16940 
16941   // The base expression of the innermost MemberExpr may give
16942   // stronger guarantees than the class containing the member.
16943   if (DRE && !TopME->isArrow()) {
16944     const ValueDecl *VD = DRE->getDecl();
16945     if (!VD->getType()->isReferenceType())
16946       CompleteObjectAlignment =
16947           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16948   }
16949 
16950   // Check if the synthesized offset fulfills the alignment.
16951   if (Offset % ExpectedAlignment != 0 ||
16952       // It may fulfill the offset it but the effective alignment may still be
16953       // lower than the expected expression alignment.
16954       CompleteObjectAlignment < ExpectedAlignment) {
16955     // If this happens, we want to determine a sensible culprit of this.
16956     // Intuitively, watching the chain of member expressions from right to
16957     // left, we start with the required alignment (as required by the field
16958     // type) but some packed attribute in that chain has reduced the alignment.
16959     // It may happen that another packed structure increases it again. But if
16960     // we are here such increase has not been enough. So pointing the first
16961     // FieldDecl that either is packed or else its RecordDecl is,
16962     // seems reasonable.
16963     FieldDecl *FD = nullptr;
16964     CharUnits Alignment;
16965     for (FieldDecl *FDI : ReverseMemberChain) {
16966       if (FDI->hasAttr<PackedAttr>() ||
16967           FDI->getParent()->hasAttr<PackedAttr>()) {
16968         FD = FDI;
16969         Alignment = std::min(
16970             Context.getTypeAlignInChars(FD->getType()),
16971             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16972         break;
16973       }
16974     }
16975     assert(FD && "We did not find a packed FieldDecl!");
16976     Action(E, FD->getParent(), FD, Alignment);
16977   }
16978 }
16979 
16980 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16981   using namespace std::placeholders;
16982 
16983   RefersToMemberWithReducedAlignment(
16984       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16985                      _2, _3, _4));
16986 }
16987 
16988 // Check if \p Ty is a valid type for the elementwise math builtins. If it is
16989 // not a valid type, emit an error message and return true. Otherwise return
16990 // false.
16991 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc,
16992                                         QualType Ty) {
16993   if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) {
16994     S.Diag(Loc, diag::err_builtin_invalid_arg_type)
16995         << 1 << /* vector, integer or float ty*/ 0 << Ty;
16996     return true;
16997   }
16998   return false;
16999 }
17000 
17001 bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) {
17002   if (checkArgCount(*this, TheCall, 1))
17003     return true;
17004 
17005   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17006   if (A.isInvalid())
17007     return true;
17008 
17009   TheCall->setArg(0, A.get());
17010   QualType TyA = A.get()->getType();
17011 
17012   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
17013     return true;
17014 
17015   TheCall->setType(TyA);
17016   return false;
17017 }
17018 
17019 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) {
17020   if (checkArgCount(*this, TheCall, 2))
17021     return true;
17022 
17023   ExprResult A = TheCall->getArg(0);
17024   ExprResult B = TheCall->getArg(1);
17025   // Do standard promotions between the two arguments, returning their common
17026   // type.
17027   QualType Res =
17028       UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
17029   if (A.isInvalid() || B.isInvalid())
17030     return true;
17031 
17032   QualType TyA = A.get()->getType();
17033   QualType TyB = B.get()->getType();
17034 
17035   if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
17036     return Diag(A.get()->getBeginLoc(),
17037                 diag::err_typecheck_call_different_arg_types)
17038            << TyA << TyB;
17039 
17040   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
17041     return true;
17042 
17043   TheCall->setArg(0, A.get());
17044   TheCall->setArg(1, B.get());
17045   TheCall->setType(Res);
17046   return false;
17047 }
17048 
17049 bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
17050   if (checkArgCount(*this, TheCall, 1))
17051     return true;
17052 
17053   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17054   if (A.isInvalid())
17055     return true;
17056 
17057   TheCall->setArg(0, A.get());
17058   return false;
17059 }
17060 
17061 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
17062                                             ExprResult CallResult) {
17063   if (checkArgCount(*this, TheCall, 1))
17064     return ExprError();
17065 
17066   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
17067   if (MatrixArg.isInvalid())
17068     return MatrixArg;
17069   Expr *Matrix = MatrixArg.get();
17070 
17071   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17072   if (!MType) {
17073     Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17074         << 1 << /* matrix ty*/ 1 << Matrix->getType();
17075     return ExprError();
17076   }
17077 
17078   // Create returned matrix type by swapping rows and columns of the argument
17079   // matrix type.
17080   QualType ResultType = Context.getConstantMatrixType(
17081       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
17082 
17083   // Change the return type to the type of the returned matrix.
17084   TheCall->setType(ResultType);
17085 
17086   // Update call argument to use the possibly converted matrix argument.
17087   TheCall->setArg(0, Matrix);
17088   return CallResult;
17089 }
17090 
17091 // Get and verify the matrix dimensions.
17092 static llvm::Optional<unsigned>
17093 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
17094   SourceLocation ErrorPos;
17095   Optional<llvm::APSInt> Value =
17096       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
17097   if (!Value) {
17098     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
17099         << Name;
17100     return {};
17101   }
17102   uint64_t Dim = Value->getZExtValue();
17103   if (!ConstantMatrixType::isDimensionValid(Dim)) {
17104     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
17105         << Name << ConstantMatrixType::getMaxElementsPerDimension();
17106     return {};
17107   }
17108   return Dim;
17109 }
17110 
17111 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17112                                                   ExprResult CallResult) {
17113   if (!getLangOpts().MatrixTypes) {
17114     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17115     return ExprError();
17116   }
17117 
17118   if (checkArgCount(*this, TheCall, 4))
17119     return ExprError();
17120 
17121   unsigned PtrArgIdx = 0;
17122   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17123   Expr *RowsExpr = TheCall->getArg(1);
17124   Expr *ColumnsExpr = TheCall->getArg(2);
17125   Expr *StrideExpr = TheCall->getArg(3);
17126 
17127   bool ArgError = false;
17128 
17129   // Check pointer argument.
17130   {
17131     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17132     if (PtrConv.isInvalid())
17133       return PtrConv;
17134     PtrExpr = PtrConv.get();
17135     TheCall->setArg(0, PtrExpr);
17136     if (PtrExpr->isTypeDependent()) {
17137       TheCall->setType(Context.DependentTy);
17138       return TheCall;
17139     }
17140   }
17141 
17142   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17143   QualType ElementTy;
17144   if (!PtrTy) {
17145     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17146         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17147     ArgError = true;
17148   } else {
17149     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17150 
17151     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
17152       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17153           << PtrArgIdx + 1 << /* pointer to element ty*/ 2
17154           << PtrExpr->getType();
17155       ArgError = true;
17156     }
17157   }
17158 
17159   // Apply default Lvalue conversions and convert the expression to size_t.
17160   auto ApplyArgumentConversions = [this](Expr *E) {
17161     ExprResult Conv = DefaultLvalueConversion(E);
17162     if (Conv.isInvalid())
17163       return Conv;
17164 
17165     return tryConvertExprToType(Conv.get(), Context.getSizeType());
17166   };
17167 
17168   // Apply conversion to row and column expressions.
17169   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17170   if (!RowsConv.isInvalid()) {
17171     RowsExpr = RowsConv.get();
17172     TheCall->setArg(1, RowsExpr);
17173   } else
17174     RowsExpr = nullptr;
17175 
17176   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17177   if (!ColumnsConv.isInvalid()) {
17178     ColumnsExpr = ColumnsConv.get();
17179     TheCall->setArg(2, ColumnsExpr);
17180   } else
17181     ColumnsExpr = nullptr;
17182 
17183   // If any any part of the result matrix type is still pending, just use
17184   // Context.DependentTy, until all parts are resolved.
17185   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17186       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17187     TheCall->setType(Context.DependentTy);
17188     return CallResult;
17189   }
17190 
17191   // Check row and column dimensions.
17192   llvm::Optional<unsigned> MaybeRows;
17193   if (RowsExpr)
17194     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17195 
17196   llvm::Optional<unsigned> MaybeColumns;
17197   if (ColumnsExpr)
17198     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17199 
17200   // Check stride argument.
17201   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17202   if (StrideConv.isInvalid())
17203     return ExprError();
17204   StrideExpr = StrideConv.get();
17205   TheCall->setArg(3, StrideExpr);
17206 
17207   if (MaybeRows) {
17208     if (Optional<llvm::APSInt> Value =
17209             StrideExpr->getIntegerConstantExpr(Context)) {
17210       uint64_t Stride = Value->getZExtValue();
17211       if (Stride < *MaybeRows) {
17212         Diag(StrideExpr->getBeginLoc(),
17213              diag::err_builtin_matrix_stride_too_small);
17214         ArgError = true;
17215       }
17216     }
17217   }
17218 
17219   if (ArgError || !MaybeRows || !MaybeColumns)
17220     return ExprError();
17221 
17222   TheCall->setType(
17223       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17224   return CallResult;
17225 }
17226 
17227 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17228                                                    ExprResult CallResult) {
17229   if (checkArgCount(*this, TheCall, 3))
17230     return ExprError();
17231 
17232   unsigned PtrArgIdx = 1;
17233   Expr *MatrixExpr = TheCall->getArg(0);
17234   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17235   Expr *StrideExpr = TheCall->getArg(2);
17236 
17237   bool ArgError = false;
17238 
17239   {
17240     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17241     if (MatrixConv.isInvalid())
17242       return MatrixConv;
17243     MatrixExpr = MatrixConv.get();
17244     TheCall->setArg(0, MatrixExpr);
17245   }
17246   if (MatrixExpr->isTypeDependent()) {
17247     TheCall->setType(Context.DependentTy);
17248     return TheCall;
17249   }
17250 
17251   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17252   if (!MatrixTy) {
17253     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17254         << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
17255     ArgError = true;
17256   }
17257 
17258   {
17259     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17260     if (PtrConv.isInvalid())
17261       return PtrConv;
17262     PtrExpr = PtrConv.get();
17263     TheCall->setArg(1, PtrExpr);
17264     if (PtrExpr->isTypeDependent()) {
17265       TheCall->setType(Context.DependentTy);
17266       return TheCall;
17267     }
17268   }
17269 
17270   // Check pointer argument.
17271   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17272   if (!PtrTy) {
17273     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17274         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17275     ArgError = true;
17276   } else {
17277     QualType ElementTy = PtrTy->getPointeeType();
17278     if (ElementTy.isConstQualified()) {
17279       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17280       ArgError = true;
17281     }
17282     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17283     if (MatrixTy &&
17284         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17285       Diag(PtrExpr->getBeginLoc(),
17286            diag::err_builtin_matrix_pointer_arg_mismatch)
17287           << ElementTy << MatrixTy->getElementType();
17288       ArgError = true;
17289     }
17290   }
17291 
17292   // Apply default Lvalue conversions and convert the stride expression to
17293   // size_t.
17294   {
17295     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17296     if (StrideConv.isInvalid())
17297       return StrideConv;
17298 
17299     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17300     if (StrideConv.isInvalid())
17301       return StrideConv;
17302     StrideExpr = StrideConv.get();
17303     TheCall->setArg(2, StrideExpr);
17304   }
17305 
17306   // Check stride argument.
17307   if (MatrixTy) {
17308     if (Optional<llvm::APSInt> Value =
17309             StrideExpr->getIntegerConstantExpr(Context)) {
17310       uint64_t Stride = Value->getZExtValue();
17311       if (Stride < MatrixTy->getNumRows()) {
17312         Diag(StrideExpr->getBeginLoc(),
17313              diag::err_builtin_matrix_stride_too_small);
17314         ArgError = true;
17315       }
17316     }
17317   }
17318 
17319   if (ArgError)
17320     return ExprError();
17321 
17322   return CallResult;
17323 }
17324 
17325 /// \brief Enforce the bounds of a TCB
17326 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
17327 /// directly calls other functions in the same TCB as marked by the enforce_tcb
17328 /// and enforce_tcb_leaf attributes.
17329 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
17330                                const FunctionDecl *Callee) {
17331   const FunctionDecl *Caller = getCurFunctionDecl();
17332 
17333   // Calls to builtins are not enforced.
17334   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
17335       Callee->getBuiltinID() != 0)
17336     return;
17337 
17338   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17339   // all TCBs the callee is a part of.
17340   llvm::StringSet<> CalleeTCBs;
17341   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
17342            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17343   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
17344            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17345 
17346   // Go through the TCBs the caller is a part of and emit warnings if Caller
17347   // is in a TCB that the Callee is not.
17348   for_each(
17349       Caller->specific_attrs<EnforceTCBAttr>(),
17350       [&](const auto *A) {
17351         StringRef CallerTCB = A->getTCBName();
17352         if (CalleeTCBs.count(CallerTCB) == 0) {
17353           this->Diag(TheCall->getExprLoc(),
17354                      diag::warn_tcb_enforcement_violation) << Callee
17355                                                            << CallerTCB;
17356         }
17357       });
17358 }
17359