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 the number of arguments and set the result type to
199 /// the argument type.
200 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
201   if (checkArgCount(S, TheCall, 1))
202     return true;
203 
204   TheCall->setType(TheCall->getArg(0)->getType());
205   return false;
206 }
207 
208 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
209 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
210 /// type (but not a function pointer) and that the alignment is a power-of-two.
211 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
212   if (checkArgCount(S, TheCall, 2))
213     return true;
214 
215   clang::Expr *Source = TheCall->getArg(0);
216   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
217 
218   auto IsValidIntegerType = [](QualType Ty) {
219     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
220   };
221   QualType SrcTy = Source->getType();
222   // We should also be able to use it with arrays (but not functions!).
223   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
224     SrcTy = S.Context.getDecayedType(SrcTy);
225   }
226   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
227       SrcTy->isFunctionPointerType()) {
228     // FIXME: this is not quite the right error message since we don't allow
229     // floating point types, or member pointers.
230     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
231         << SrcTy;
232     return true;
233   }
234 
235   clang::Expr *AlignOp = TheCall->getArg(1);
236   if (!IsValidIntegerType(AlignOp->getType())) {
237     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
238         << AlignOp->getType();
239     return true;
240   }
241   Expr::EvalResult AlignResult;
242   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
243   // We can't check validity of alignment if it is value dependent.
244   if (!AlignOp->isValueDependent() &&
245       AlignOp->EvaluateAsInt(AlignResult, S.Context,
246                              Expr::SE_AllowSideEffects)) {
247     llvm::APSInt AlignValue = AlignResult.Val.getInt();
248     llvm::APSInt MaxValue(
249         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
250     if (AlignValue < 1) {
251       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
252       return true;
253     }
254     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
255       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
256           << toString(MaxValue, 10);
257       return true;
258     }
259     if (!AlignValue.isPowerOf2()) {
260       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
261       return true;
262     }
263     if (AlignValue == 1) {
264       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
265           << IsBooleanAlignBuiltin;
266     }
267   }
268 
269   ExprResult SrcArg = S.PerformCopyInitialization(
270       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
271       SourceLocation(), Source);
272   if (SrcArg.isInvalid())
273     return true;
274   TheCall->setArg(0, SrcArg.get());
275   ExprResult AlignArg =
276       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
277                                       S.Context, AlignOp->getType(), false),
278                                   SourceLocation(), AlignOp);
279   if (AlignArg.isInvalid())
280     return true;
281   TheCall->setArg(1, AlignArg.get());
282   // For align_up/align_down, the return type is the same as the (potentially
283   // decayed) argument type including qualifiers. For is_aligned(), the result
284   // is always bool.
285   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
286   return false;
287 }
288 
289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
290                                 unsigned BuiltinID) {
291   if (checkArgCount(S, TheCall, 3))
292     return true;
293 
294   // First two arguments should be integers.
295   for (unsigned I = 0; I < 2; ++I) {
296     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
297     if (Arg.isInvalid()) return true;
298     TheCall->setArg(I, Arg.get());
299 
300     QualType Ty = Arg.get()->getType();
301     if (!Ty->isIntegerType()) {
302       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
303           << Ty << Arg.get()->getSourceRange();
304       return true;
305     }
306   }
307 
308   // Third argument should be a pointer to a non-const integer.
309   // IRGen correctly handles volatile, restrict, and address spaces, and
310   // the other qualifiers aren't possible.
311   {
312     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
313     if (Arg.isInvalid()) return true;
314     TheCall->setArg(2, Arg.get());
315 
316     QualType Ty = Arg.get()->getType();
317     const auto *PtrTy = Ty->getAs<PointerType>();
318     if (!PtrTy ||
319         !PtrTy->getPointeeType()->isIntegerType() ||
320         PtrTy->getPointeeType().isConstQualified()) {
321       S.Diag(Arg.get()->getBeginLoc(),
322              diag::err_overflow_builtin_must_be_ptr_int)
323         << Ty << Arg.get()->getSourceRange();
324       return true;
325     }
326   }
327 
328   // Disallow signed ExtIntType args larger than 128 bits to mul function until
329   // we improve backend support.
330   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
331     for (unsigned I = 0; I < 3; ++I) {
332       const auto Arg = TheCall->getArg(I);
333       // Third argument will be a pointer.
334       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
335       if (Ty->isExtIntType() && Ty->isSignedIntegerType() &&
336           S.getASTContext().getIntWidth(Ty) > 128)
337         return S.Diag(Arg->getBeginLoc(),
338                       diag::err_overflow_builtin_ext_int_max_size)
339                << 128;
340     }
341   }
342 
343   return false;
344 }
345 
346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
347   if (checkArgCount(S, BuiltinCall, 2))
348     return true;
349 
350   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
351   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
352   Expr *Call = BuiltinCall->getArg(0);
353   Expr *Chain = BuiltinCall->getArg(1);
354 
355   if (Call->getStmtClass() != Stmt::CallExprClass) {
356     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
357         << Call->getSourceRange();
358     return true;
359   }
360 
361   auto CE = cast<CallExpr>(Call);
362   if (CE->getCallee()->getType()->isBlockPointerType()) {
363     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
364         << Call->getSourceRange();
365     return true;
366   }
367 
368   const Decl *TargetDecl = CE->getCalleeDecl();
369   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
370     if (FD->getBuiltinID()) {
371       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
372           << Call->getSourceRange();
373       return true;
374     }
375 
376   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
377     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
378         << Call->getSourceRange();
379     return true;
380   }
381 
382   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
383   if (ChainResult.isInvalid())
384     return true;
385   if (!ChainResult.get()->getType()->isPointerType()) {
386     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
387         << Chain->getSourceRange();
388     return true;
389   }
390 
391   QualType ReturnTy = CE->getCallReturnType(S.Context);
392   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
393   QualType BuiltinTy = S.Context.getFunctionType(
394       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
395   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
396 
397   Builtin =
398       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
399 
400   BuiltinCall->setType(CE->getType());
401   BuiltinCall->setValueKind(CE->getValueKind());
402   BuiltinCall->setObjectKind(CE->getObjectKind());
403   BuiltinCall->setCallee(Builtin);
404   BuiltinCall->setArg(1, ChainResult.get());
405 
406   return false;
407 }
408 
409 namespace {
410 
411 class ScanfDiagnosticFormatHandler
412     : public analyze_format_string::FormatStringHandler {
413   // Accepts the argument index (relative to the first destination index) of the
414   // argument whose size we want.
415   using ComputeSizeFunction =
416       llvm::function_ref<Optional<llvm::APSInt>(unsigned)>;
417 
418   // Accepts the argument index (relative to the first destination index), the
419   // destination size, and the source size).
420   using DiagnoseFunction =
421       llvm::function_ref<void(unsigned, unsigned, unsigned)>;
422 
423   ComputeSizeFunction ComputeSizeArgument;
424   DiagnoseFunction Diagnose;
425 
426 public:
427   ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
428                                DiagnoseFunction Diagnose)
429       : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
430 
431   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
432                             const char *StartSpecifier,
433                             unsigned specifierLen) override {
434     if (!FS.consumesDataArgument())
435       return true;
436 
437     unsigned NulByte = 0;
438     switch ((FS.getConversionSpecifier().getKind())) {
439     default:
440       return true;
441     case analyze_format_string::ConversionSpecifier::sArg:
442     case analyze_format_string::ConversionSpecifier::ScanListArg:
443       NulByte = 1;
444       break;
445     case analyze_format_string::ConversionSpecifier::cArg:
446       break;
447     }
448 
449     auto OptionalFW = FS.getFieldWidth();
450     if (OptionalFW.getHowSpecified() !=
451         analyze_format_string::OptionalAmount::HowSpecified::Constant)
452       return true;
453 
454     unsigned SourceSize = OptionalFW.getConstantAmount() + NulByte;
455 
456     auto DestSizeAPS = ComputeSizeArgument(FS.getArgIndex());
457     if (!DestSizeAPS)
458       return true;
459 
460     unsigned DestSize = DestSizeAPS->getZExtValue();
461 
462     if (DestSize < SourceSize)
463       Diagnose(FS.getArgIndex(), DestSize, SourceSize);
464 
465     return true;
466   }
467 };
468 
469 class EstimateSizeFormatHandler
470     : public analyze_format_string::FormatStringHandler {
471   size_t Size;
472 
473 public:
474   EstimateSizeFormatHandler(StringRef Format)
475       : Size(std::min(Format.find(0), Format.size()) +
476              1 /* null byte always written by sprintf */) {}
477 
478   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
479                              const char *, unsigned SpecifierLen) override {
480 
481     const size_t FieldWidth = computeFieldWidth(FS);
482     const size_t Precision = computePrecision(FS);
483 
484     // The actual format.
485     switch (FS.getConversionSpecifier().getKind()) {
486     // Just a char.
487     case analyze_format_string::ConversionSpecifier::cArg:
488     case analyze_format_string::ConversionSpecifier::CArg:
489       Size += std::max(FieldWidth, (size_t)1);
490       break;
491     // Just an integer.
492     case analyze_format_string::ConversionSpecifier::dArg:
493     case analyze_format_string::ConversionSpecifier::DArg:
494     case analyze_format_string::ConversionSpecifier::iArg:
495     case analyze_format_string::ConversionSpecifier::oArg:
496     case analyze_format_string::ConversionSpecifier::OArg:
497     case analyze_format_string::ConversionSpecifier::uArg:
498     case analyze_format_string::ConversionSpecifier::UArg:
499     case analyze_format_string::ConversionSpecifier::xArg:
500     case analyze_format_string::ConversionSpecifier::XArg:
501       Size += std::max(FieldWidth, Precision);
502       break;
503 
504     // %g style conversion switches between %f or %e style dynamically.
505     // %f always takes less space, so default to it.
506     case analyze_format_string::ConversionSpecifier::gArg:
507     case analyze_format_string::ConversionSpecifier::GArg:
508 
509     // Floating point number in the form '[+]ddd.ddd'.
510     case analyze_format_string::ConversionSpecifier::fArg:
511     case analyze_format_string::ConversionSpecifier::FArg:
512       Size += std::max(FieldWidth, 1 /* integer part */ +
513                                        (Precision ? 1 + Precision
514                                                   : 0) /* period + decimal */);
515       break;
516 
517     // Floating point number in the form '[-]d.ddde[+-]dd'.
518     case analyze_format_string::ConversionSpecifier::eArg:
519     case analyze_format_string::ConversionSpecifier::EArg:
520       Size +=
521           std::max(FieldWidth,
522                    1 /* integer part */ +
523                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
524                        1 /* e or E letter */ + 2 /* exponent */);
525       break;
526 
527     // Floating point number in the form '[-]0xh.hhhhp±dd'.
528     case analyze_format_string::ConversionSpecifier::aArg:
529     case analyze_format_string::ConversionSpecifier::AArg:
530       Size +=
531           std::max(FieldWidth,
532                    2 /* 0x */ + 1 /* integer part */ +
533                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
534                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
535       break;
536 
537     // Just a string.
538     case analyze_format_string::ConversionSpecifier::sArg:
539     case analyze_format_string::ConversionSpecifier::SArg:
540       Size += FieldWidth;
541       break;
542 
543     // Just a pointer in the form '0xddd'.
544     case analyze_format_string::ConversionSpecifier::pArg:
545       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
546       break;
547 
548     // A plain percent.
549     case analyze_format_string::ConversionSpecifier::PercentArg:
550       Size += 1;
551       break;
552 
553     default:
554       break;
555     }
556 
557     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
558 
559     if (FS.hasAlternativeForm()) {
560       switch (FS.getConversionSpecifier().getKind()) {
561       default:
562         break;
563       // Force a leading '0'.
564       case analyze_format_string::ConversionSpecifier::oArg:
565         Size += 1;
566         break;
567       // Force a leading '0x'.
568       case analyze_format_string::ConversionSpecifier::xArg:
569       case analyze_format_string::ConversionSpecifier::XArg:
570         Size += 2;
571         break;
572       // Force a period '.' before decimal, even if precision is 0.
573       case analyze_format_string::ConversionSpecifier::aArg:
574       case analyze_format_string::ConversionSpecifier::AArg:
575       case analyze_format_string::ConversionSpecifier::eArg:
576       case analyze_format_string::ConversionSpecifier::EArg:
577       case analyze_format_string::ConversionSpecifier::fArg:
578       case analyze_format_string::ConversionSpecifier::FArg:
579       case analyze_format_string::ConversionSpecifier::gArg:
580       case analyze_format_string::ConversionSpecifier::GArg:
581         Size += (Precision ? 0 : 1);
582         break;
583       }
584     }
585     assert(SpecifierLen <= Size && "no underflow");
586     Size -= SpecifierLen;
587     return true;
588   }
589 
590   size_t getSizeLowerBound() const { return Size; }
591 
592 private:
593   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
594     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
595     size_t FieldWidth = 0;
596     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
597       FieldWidth = FW.getConstantAmount();
598     return FieldWidth;
599   }
600 
601   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
602     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
603     size_t Precision = 0;
604 
605     // See man 3 printf for default precision value based on the specifier.
606     switch (FW.getHowSpecified()) {
607     case analyze_format_string::OptionalAmount::NotSpecified:
608       switch (FS.getConversionSpecifier().getKind()) {
609       default:
610         break;
611       case analyze_format_string::ConversionSpecifier::dArg: // %d
612       case analyze_format_string::ConversionSpecifier::DArg: // %D
613       case analyze_format_string::ConversionSpecifier::iArg: // %i
614         Precision = 1;
615         break;
616       case analyze_format_string::ConversionSpecifier::oArg: // %d
617       case analyze_format_string::ConversionSpecifier::OArg: // %D
618       case analyze_format_string::ConversionSpecifier::uArg: // %d
619       case analyze_format_string::ConversionSpecifier::UArg: // %D
620       case analyze_format_string::ConversionSpecifier::xArg: // %d
621       case analyze_format_string::ConversionSpecifier::XArg: // %D
622         Precision = 1;
623         break;
624       case analyze_format_string::ConversionSpecifier::fArg: // %f
625       case analyze_format_string::ConversionSpecifier::FArg: // %F
626       case analyze_format_string::ConversionSpecifier::eArg: // %e
627       case analyze_format_string::ConversionSpecifier::EArg: // %E
628       case analyze_format_string::ConversionSpecifier::gArg: // %g
629       case analyze_format_string::ConversionSpecifier::GArg: // %G
630         Precision = 6;
631         break;
632       case analyze_format_string::ConversionSpecifier::pArg: // %d
633         Precision = 1;
634         break;
635       }
636       break;
637     case analyze_format_string::OptionalAmount::Constant:
638       Precision = FW.getConstantAmount();
639       break;
640     default:
641       break;
642     }
643     return Precision;
644   }
645 };
646 
647 } // namespace
648 
649 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
650                                                CallExpr *TheCall) {
651   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
652       isConstantEvaluated())
653     return;
654 
655   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
656   if (!BuiltinID)
657     return;
658 
659   const TargetInfo &TI = getASTContext().getTargetInfo();
660   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
661 
662   auto ComputeExplicitObjectSizeArgument =
663       [&](unsigned Index) -> Optional<llvm::APSInt> {
664     Expr::EvalResult Result;
665     Expr *SizeArg = TheCall->getArg(Index);
666     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
667       return llvm::None;
668     return Result.Val.getInt();
669   };
670 
671   auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
672     // If the parameter has a pass_object_size attribute, then we should use its
673     // (potentially) more strict checking mode. Otherwise, conservatively assume
674     // type 0.
675     int BOSType = 0;
676     // This check can fail for variadic functions.
677     if (Index < FD->getNumParams()) {
678       if (const auto *POS =
679               FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
680         BOSType = POS->getType();
681     }
682 
683     const Expr *ObjArg = TheCall->getArg(Index);
684     uint64_t Result;
685     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
686       return llvm::None;
687 
688     // Get the object size in the target's size_t width.
689     return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
690   };
691 
692   auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
693     Expr *ObjArg = TheCall->getArg(Index);
694     uint64_t Result;
695     if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
696       return llvm::None;
697     // Add 1 for null byte.
698     return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
699   };
700 
701   Optional<llvm::APSInt> SourceSize;
702   Optional<llvm::APSInt> DestinationSize;
703   unsigned DiagID = 0;
704   bool IsChkVariant = false;
705 
706   auto GetFunctionName = [&]() {
707     StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
708     // Skim off the details of whichever builtin was called to produce a better
709     // diagnostic, as it's unlikely that the user wrote the __builtin
710     // explicitly.
711     if (IsChkVariant) {
712       FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
713       FunctionName = FunctionName.drop_back(std::strlen("_chk"));
714     } else if (FunctionName.startswith("__builtin_")) {
715       FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
716     }
717     return FunctionName;
718   };
719 
720   switch (BuiltinID) {
721   default:
722     return;
723   case Builtin::BI__builtin_strcpy:
724   case Builtin::BIstrcpy: {
725     DiagID = diag::warn_fortify_strlen_overflow;
726     SourceSize = ComputeStrLenArgument(1);
727     DestinationSize = ComputeSizeArgument(0);
728     break;
729   }
730 
731   case Builtin::BI__builtin___strcpy_chk: {
732     DiagID = diag::warn_fortify_strlen_overflow;
733     SourceSize = ComputeStrLenArgument(1);
734     DestinationSize = ComputeExplicitObjectSizeArgument(2);
735     IsChkVariant = true;
736     break;
737   }
738 
739   case Builtin::BIscanf:
740   case Builtin::BIfscanf:
741   case Builtin::BIsscanf: {
742     unsigned FormatIndex = 1;
743     unsigned DataIndex = 2;
744     if (BuiltinID == Builtin::BIscanf) {
745       FormatIndex = 0;
746       DataIndex = 1;
747     }
748 
749     const auto *FormatExpr =
750         TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
751 
752     const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
753     if (!Format)
754       return;
755 
756     if (!Format->isAscii() && !Format->isUTF8())
757       return;
758 
759     auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
760                         unsigned SourceSize) {
761       DiagID = diag::warn_fortify_scanf_overflow;
762       unsigned Index = ArgIndex + DataIndex;
763       StringRef FunctionName = GetFunctionName();
764       DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
765                           PDiag(DiagID) << FunctionName << (Index + 1)
766                                         << DestSize << SourceSize);
767     };
768 
769     StringRef FormatStrRef = Format->getString();
770     auto ShiftedComputeSizeArgument = [&](unsigned Index) {
771       return ComputeSizeArgument(Index + DataIndex);
772     };
773     ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
774     const char *FormatBytes = FormatStrRef.data();
775     const ConstantArrayType *T =
776         Context.getAsConstantArrayType(Format->getType());
777     assert(T && "String literal not of constant array type!");
778     size_t TypeSize = T->getSize().getZExtValue();
779 
780     // In case there's a null byte somewhere.
781     size_t StrLen =
782         std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
783 
784     analyze_format_string::ParseScanfString(H, FormatBytes,
785                                             FormatBytes + StrLen, getLangOpts(),
786                                             Context.getTargetInfo());
787 
788     // Unlike the other cases, in this one we have already issued the diagnostic
789     // here, so no need to continue (because unlike the other cases, here the
790     // diagnostic refers to the argument number).
791     return;
792   }
793 
794   case Builtin::BIsprintf:
795   case Builtin::BI__builtin___sprintf_chk: {
796     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
797     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
798 
799     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
800 
801       if (!Format->isAscii() && !Format->isUTF8())
802         return;
803 
804       StringRef FormatStrRef = Format->getString();
805       EstimateSizeFormatHandler H(FormatStrRef);
806       const char *FormatBytes = FormatStrRef.data();
807       const ConstantArrayType *T =
808           Context.getAsConstantArrayType(Format->getType());
809       assert(T && "String literal not of constant array type!");
810       size_t TypeSize = T->getSize().getZExtValue();
811 
812       // In case there's a null byte somewhere.
813       size_t StrLen =
814           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
815       if (!analyze_format_string::ParsePrintfString(
816               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
817               Context.getTargetInfo(), false)) {
818         DiagID = diag::warn_fortify_source_format_overflow;
819         SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
820                          .extOrTrunc(SizeTypeWidth);
821         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
822           DestinationSize = ComputeExplicitObjectSizeArgument(2);
823           IsChkVariant = true;
824         } else {
825           DestinationSize = ComputeSizeArgument(0);
826         }
827         break;
828       }
829     }
830     return;
831   }
832   case Builtin::BI__builtin___memcpy_chk:
833   case Builtin::BI__builtin___memmove_chk:
834   case Builtin::BI__builtin___memset_chk:
835   case Builtin::BI__builtin___strlcat_chk:
836   case Builtin::BI__builtin___strlcpy_chk:
837   case Builtin::BI__builtin___strncat_chk:
838   case Builtin::BI__builtin___strncpy_chk:
839   case Builtin::BI__builtin___stpncpy_chk:
840   case Builtin::BI__builtin___memccpy_chk:
841   case Builtin::BI__builtin___mempcpy_chk: {
842     DiagID = diag::warn_builtin_chk_overflow;
843     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
844     DestinationSize =
845         ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
846     IsChkVariant = true;
847     break;
848   }
849 
850   case Builtin::BI__builtin___snprintf_chk:
851   case Builtin::BI__builtin___vsnprintf_chk: {
852     DiagID = diag::warn_builtin_chk_overflow;
853     SourceSize = ComputeExplicitObjectSizeArgument(1);
854     DestinationSize = ComputeExplicitObjectSizeArgument(3);
855     IsChkVariant = true;
856     break;
857   }
858 
859   case Builtin::BIstrncat:
860   case Builtin::BI__builtin_strncat:
861   case Builtin::BIstrncpy:
862   case Builtin::BI__builtin_strncpy:
863   case Builtin::BIstpncpy:
864   case Builtin::BI__builtin_stpncpy: {
865     // Whether these functions overflow depends on the runtime strlen of the
866     // string, not just the buffer size, so emitting the "always overflow"
867     // diagnostic isn't quite right. We should still diagnose passing a buffer
868     // size larger than the destination buffer though; this is a runtime abort
869     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
870     DiagID = diag::warn_fortify_source_size_mismatch;
871     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
872     DestinationSize = ComputeSizeArgument(0);
873     break;
874   }
875 
876   case Builtin::BImemcpy:
877   case Builtin::BI__builtin_memcpy:
878   case Builtin::BImemmove:
879   case Builtin::BI__builtin_memmove:
880   case Builtin::BImemset:
881   case Builtin::BI__builtin_memset:
882   case Builtin::BImempcpy:
883   case Builtin::BI__builtin_mempcpy: {
884     DiagID = diag::warn_fortify_source_overflow;
885     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
886     DestinationSize = ComputeSizeArgument(0);
887     break;
888   }
889   case Builtin::BIsnprintf:
890   case Builtin::BI__builtin_snprintf:
891   case Builtin::BIvsnprintf:
892   case Builtin::BI__builtin_vsnprintf: {
893     DiagID = diag::warn_fortify_source_size_mismatch;
894     SourceSize = ComputeExplicitObjectSizeArgument(1);
895     DestinationSize = ComputeSizeArgument(0);
896     break;
897   }
898   }
899 
900   if (!SourceSize || !DestinationSize ||
901       SourceSize.getValue().ule(DestinationSize.getValue()))
902     return;
903 
904   StringRef FunctionName = GetFunctionName();
905 
906   SmallString<16> DestinationStr;
907   SmallString<16> SourceStr;
908   DestinationSize->toString(DestinationStr, /*Radix=*/10);
909   SourceSize->toString(SourceStr, /*Radix=*/10);
910   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
911                       PDiag(DiagID)
912                           << FunctionName << DestinationStr << SourceStr);
913 }
914 
915 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
916                                      Scope::ScopeFlags NeededScopeFlags,
917                                      unsigned DiagID) {
918   // Scopes aren't available during instantiation. Fortunately, builtin
919   // functions cannot be template args so they cannot be formed through template
920   // instantiation. Therefore checking once during the parse is sufficient.
921   if (SemaRef.inTemplateInstantiation())
922     return false;
923 
924   Scope *S = SemaRef.getCurScope();
925   while (S && !S->isSEHExceptScope())
926     S = S->getParent();
927   if (!S || !(S->getFlags() & NeededScopeFlags)) {
928     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
929     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
930         << DRE->getDecl()->getIdentifier();
931     return true;
932   }
933 
934   return false;
935 }
936 
937 static inline bool isBlockPointer(Expr *Arg) {
938   return Arg->getType()->isBlockPointerType();
939 }
940 
941 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
942 /// void*, which is a requirement of device side enqueue.
943 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
944   const BlockPointerType *BPT =
945       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
946   ArrayRef<QualType> Params =
947       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
948   unsigned ArgCounter = 0;
949   bool IllegalParams = false;
950   // Iterate through the block parameters until either one is found that is not
951   // a local void*, or the block is valid.
952   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
953        I != E; ++I, ++ArgCounter) {
954     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
955         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
956             LangAS::opencl_local) {
957       // Get the location of the error. If a block literal has been passed
958       // (BlockExpr) then we can point straight to the offending argument,
959       // else we just point to the variable reference.
960       SourceLocation ErrorLoc;
961       if (isa<BlockExpr>(BlockArg)) {
962         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
963         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
964       } else if (isa<DeclRefExpr>(BlockArg)) {
965         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
966       }
967       S.Diag(ErrorLoc,
968              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
969       IllegalParams = true;
970     }
971   }
972 
973   return IllegalParams;
974 }
975 
976 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
977   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) {
978     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
979         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
980     return true;
981   }
982   return false;
983 }
984 
985 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
986   if (checkArgCount(S, TheCall, 2))
987     return true;
988 
989   if (checkOpenCLSubgroupExt(S, TheCall))
990     return true;
991 
992   // First argument is an ndrange_t type.
993   Expr *NDRangeArg = TheCall->getArg(0);
994   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
995     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
996         << TheCall->getDirectCallee() << "'ndrange_t'";
997     return true;
998   }
999 
1000   Expr *BlockArg = TheCall->getArg(1);
1001   if (!isBlockPointer(BlockArg)) {
1002     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1003         << TheCall->getDirectCallee() << "block";
1004     return true;
1005   }
1006   return checkOpenCLBlockArgs(S, BlockArg);
1007 }
1008 
1009 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
1010 /// get_kernel_work_group_size
1011 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
1012 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
1013   if (checkArgCount(S, TheCall, 1))
1014     return true;
1015 
1016   Expr *BlockArg = TheCall->getArg(0);
1017   if (!isBlockPointer(BlockArg)) {
1018     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1019         << TheCall->getDirectCallee() << "block";
1020     return true;
1021   }
1022   return checkOpenCLBlockArgs(S, BlockArg);
1023 }
1024 
1025 /// Diagnose integer type and any valid implicit conversion to it.
1026 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
1027                                       const QualType &IntType);
1028 
1029 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
1030                                             unsigned Start, unsigned End) {
1031   bool IllegalParams = false;
1032   for (unsigned I = Start; I <= End; ++I)
1033     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
1034                                               S.Context.getSizeType());
1035   return IllegalParams;
1036 }
1037 
1038 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
1039 /// 'local void*' parameter of passed block.
1040 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
1041                                            Expr *BlockArg,
1042                                            unsigned NumNonVarArgs) {
1043   const BlockPointerType *BPT =
1044       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1045   unsigned NumBlockParams =
1046       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
1047   unsigned TotalNumArgs = TheCall->getNumArgs();
1048 
1049   // For each argument passed to the block, a corresponding uint needs to
1050   // be passed to describe the size of the local memory.
1051   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
1052     S.Diag(TheCall->getBeginLoc(),
1053            diag::err_opencl_enqueue_kernel_local_size_args);
1054     return true;
1055   }
1056 
1057   // Check that the sizes of the local memory are specified by integers.
1058   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
1059                                          TotalNumArgs - 1);
1060 }
1061 
1062 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
1063 /// overload formats specified in Table 6.13.17.1.
1064 /// int enqueue_kernel(queue_t queue,
1065 ///                    kernel_enqueue_flags_t flags,
1066 ///                    const ndrange_t ndrange,
1067 ///                    void (^block)(void))
1068 /// int enqueue_kernel(queue_t queue,
1069 ///                    kernel_enqueue_flags_t flags,
1070 ///                    const ndrange_t ndrange,
1071 ///                    uint num_events_in_wait_list,
1072 ///                    clk_event_t *event_wait_list,
1073 ///                    clk_event_t *event_ret,
1074 ///                    void (^block)(void))
1075 /// int enqueue_kernel(queue_t queue,
1076 ///                    kernel_enqueue_flags_t flags,
1077 ///                    const ndrange_t ndrange,
1078 ///                    void (^block)(local void*, ...),
1079 ///                    uint size0, ...)
1080 /// int enqueue_kernel(queue_t queue,
1081 ///                    kernel_enqueue_flags_t flags,
1082 ///                    const ndrange_t ndrange,
1083 ///                    uint num_events_in_wait_list,
1084 ///                    clk_event_t *event_wait_list,
1085 ///                    clk_event_t *event_ret,
1086 ///                    void (^block)(local void*, ...),
1087 ///                    uint size0, ...)
1088 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
1089   unsigned NumArgs = TheCall->getNumArgs();
1090 
1091   if (NumArgs < 4) {
1092     S.Diag(TheCall->getBeginLoc(),
1093            diag::err_typecheck_call_too_few_args_at_least)
1094         << 0 << 4 << NumArgs;
1095     return true;
1096   }
1097 
1098   Expr *Arg0 = TheCall->getArg(0);
1099   Expr *Arg1 = TheCall->getArg(1);
1100   Expr *Arg2 = TheCall->getArg(2);
1101   Expr *Arg3 = TheCall->getArg(3);
1102 
1103   // First argument always needs to be a queue_t type.
1104   if (!Arg0->getType()->isQueueT()) {
1105     S.Diag(TheCall->getArg(0)->getBeginLoc(),
1106            diag::err_opencl_builtin_expected_type)
1107         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
1108     return true;
1109   }
1110 
1111   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
1112   if (!Arg1->getType()->isIntegerType()) {
1113     S.Diag(TheCall->getArg(1)->getBeginLoc(),
1114            diag::err_opencl_builtin_expected_type)
1115         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
1116     return true;
1117   }
1118 
1119   // Third argument is always an ndrange_t type.
1120   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1121     S.Diag(TheCall->getArg(2)->getBeginLoc(),
1122            diag::err_opencl_builtin_expected_type)
1123         << TheCall->getDirectCallee() << "'ndrange_t'";
1124     return true;
1125   }
1126 
1127   // With four arguments, there is only one form that the function could be
1128   // called in: no events and no variable arguments.
1129   if (NumArgs == 4) {
1130     // check that the last argument is the right block type.
1131     if (!isBlockPointer(Arg3)) {
1132       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1133           << TheCall->getDirectCallee() << "block";
1134       return true;
1135     }
1136     // we have a block type, check the prototype
1137     const BlockPointerType *BPT =
1138         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1139     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1140       S.Diag(Arg3->getBeginLoc(),
1141              diag::err_opencl_enqueue_kernel_blocks_no_args);
1142       return true;
1143     }
1144     return false;
1145   }
1146   // we can have block + varargs.
1147   if (isBlockPointer(Arg3))
1148     return (checkOpenCLBlockArgs(S, Arg3) ||
1149             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1150   // last two cases with either exactly 7 args or 7 args and varargs.
1151   if (NumArgs >= 7) {
1152     // check common block argument.
1153     Expr *Arg6 = TheCall->getArg(6);
1154     if (!isBlockPointer(Arg6)) {
1155       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1156           << TheCall->getDirectCallee() << "block";
1157       return true;
1158     }
1159     if (checkOpenCLBlockArgs(S, Arg6))
1160       return true;
1161 
1162     // Forth argument has to be any integer type.
1163     if (!Arg3->getType()->isIntegerType()) {
1164       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1165              diag::err_opencl_builtin_expected_type)
1166           << TheCall->getDirectCallee() << "integer";
1167       return true;
1168     }
1169     // check remaining common arguments.
1170     Expr *Arg4 = TheCall->getArg(4);
1171     Expr *Arg5 = TheCall->getArg(5);
1172 
1173     // Fifth argument is always passed as a pointer to clk_event_t.
1174     if (!Arg4->isNullPointerConstant(S.Context,
1175                                      Expr::NPC_ValueDependentIsNotNull) &&
1176         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1177       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1178              diag::err_opencl_builtin_expected_type)
1179           << TheCall->getDirectCallee()
1180           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1181       return true;
1182     }
1183 
1184     // Sixth argument is always passed as a pointer to clk_event_t.
1185     if (!Arg5->isNullPointerConstant(S.Context,
1186                                      Expr::NPC_ValueDependentIsNotNull) &&
1187         !(Arg5->getType()->isPointerType() &&
1188           Arg5->getType()->getPointeeType()->isClkEventT())) {
1189       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1190              diag::err_opencl_builtin_expected_type)
1191           << TheCall->getDirectCallee()
1192           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1193       return true;
1194     }
1195 
1196     if (NumArgs == 7)
1197       return false;
1198 
1199     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1200   }
1201 
1202   // None of the specific case has been detected, give generic error
1203   S.Diag(TheCall->getBeginLoc(),
1204          diag::err_opencl_enqueue_kernel_incorrect_args);
1205   return true;
1206 }
1207 
1208 /// Returns OpenCL access qual.
1209 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1210     return D->getAttr<OpenCLAccessAttr>();
1211 }
1212 
1213 /// Returns true if pipe element type is different from the pointer.
1214 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1215   const Expr *Arg0 = Call->getArg(0);
1216   // First argument type should always be pipe.
1217   if (!Arg0->getType()->isPipeType()) {
1218     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1219         << Call->getDirectCallee() << Arg0->getSourceRange();
1220     return true;
1221   }
1222   OpenCLAccessAttr *AccessQual =
1223       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1224   // Validates the access qualifier is compatible with the call.
1225   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1226   // read_only and write_only, and assumed to be read_only if no qualifier is
1227   // specified.
1228   switch (Call->getDirectCallee()->getBuiltinID()) {
1229   case Builtin::BIread_pipe:
1230   case Builtin::BIreserve_read_pipe:
1231   case Builtin::BIcommit_read_pipe:
1232   case Builtin::BIwork_group_reserve_read_pipe:
1233   case Builtin::BIsub_group_reserve_read_pipe:
1234   case Builtin::BIwork_group_commit_read_pipe:
1235   case Builtin::BIsub_group_commit_read_pipe:
1236     if (!(!AccessQual || AccessQual->isReadOnly())) {
1237       S.Diag(Arg0->getBeginLoc(),
1238              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1239           << "read_only" << Arg0->getSourceRange();
1240       return true;
1241     }
1242     break;
1243   case Builtin::BIwrite_pipe:
1244   case Builtin::BIreserve_write_pipe:
1245   case Builtin::BIcommit_write_pipe:
1246   case Builtin::BIwork_group_reserve_write_pipe:
1247   case Builtin::BIsub_group_reserve_write_pipe:
1248   case Builtin::BIwork_group_commit_write_pipe:
1249   case Builtin::BIsub_group_commit_write_pipe:
1250     if (!(AccessQual && AccessQual->isWriteOnly())) {
1251       S.Diag(Arg0->getBeginLoc(),
1252              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1253           << "write_only" << Arg0->getSourceRange();
1254       return true;
1255     }
1256     break;
1257   default:
1258     break;
1259   }
1260   return false;
1261 }
1262 
1263 /// Returns true if pipe element type is different from the pointer.
1264 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1265   const Expr *Arg0 = Call->getArg(0);
1266   const Expr *ArgIdx = Call->getArg(Idx);
1267   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1268   const QualType EltTy = PipeTy->getElementType();
1269   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1270   // The Idx argument should be a pointer and the type of the pointer and
1271   // the type of pipe element should also be the same.
1272   if (!ArgTy ||
1273       !S.Context.hasSameType(
1274           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1275     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1276         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1277         << ArgIdx->getType() << ArgIdx->getSourceRange();
1278     return true;
1279   }
1280   return false;
1281 }
1282 
1283 // Performs semantic analysis for the read/write_pipe call.
1284 // \param S Reference to the semantic analyzer.
1285 // \param Call A pointer to the builtin call.
1286 // \return True if a semantic error has been found, false otherwise.
1287 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1288   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1289   // functions have two forms.
1290   switch (Call->getNumArgs()) {
1291   case 2:
1292     if (checkOpenCLPipeArg(S, Call))
1293       return true;
1294     // The call with 2 arguments should be
1295     // read/write_pipe(pipe T, T*).
1296     // Check packet type T.
1297     if (checkOpenCLPipePacketType(S, Call, 1))
1298       return true;
1299     break;
1300 
1301   case 4: {
1302     if (checkOpenCLPipeArg(S, Call))
1303       return true;
1304     // The call with 4 arguments should be
1305     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1306     // Check reserve_id_t.
1307     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1308       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1309           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1310           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1311       return true;
1312     }
1313 
1314     // Check the index.
1315     const Expr *Arg2 = Call->getArg(2);
1316     if (!Arg2->getType()->isIntegerType() &&
1317         !Arg2->getType()->isUnsignedIntegerType()) {
1318       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1319           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1320           << Arg2->getType() << Arg2->getSourceRange();
1321       return true;
1322     }
1323 
1324     // Check packet type T.
1325     if (checkOpenCLPipePacketType(S, Call, 3))
1326       return true;
1327   } break;
1328   default:
1329     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1330         << Call->getDirectCallee() << Call->getSourceRange();
1331     return true;
1332   }
1333 
1334   return false;
1335 }
1336 
1337 // Performs a semantic analysis on the {work_group_/sub_group_
1338 //        /_}reserve_{read/write}_pipe
1339 // \param S Reference to the semantic analyzer.
1340 // \param Call The call to the builtin function to be analyzed.
1341 // \return True if a semantic error was found, false otherwise.
1342 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1343   if (checkArgCount(S, Call, 2))
1344     return true;
1345 
1346   if (checkOpenCLPipeArg(S, Call))
1347     return true;
1348 
1349   // Check the reserve size.
1350   if (!Call->getArg(1)->getType()->isIntegerType() &&
1351       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1352     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1353         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1354         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1355     return true;
1356   }
1357 
1358   // Since return type of reserve_read/write_pipe built-in function is
1359   // reserve_id_t, which is not defined in the builtin def file , we used int
1360   // as return type and need to override the return type of these functions.
1361   Call->setType(S.Context.OCLReserveIDTy);
1362 
1363   return false;
1364 }
1365 
1366 // Performs a semantic analysis on {work_group_/sub_group_
1367 //        /_}commit_{read/write}_pipe
1368 // \param S Reference to the semantic analyzer.
1369 // \param Call The call to the builtin function to be analyzed.
1370 // \return True if a semantic error was found, false otherwise.
1371 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1372   if (checkArgCount(S, Call, 2))
1373     return true;
1374 
1375   if (checkOpenCLPipeArg(S, Call))
1376     return true;
1377 
1378   // Check reserve_id_t.
1379   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1380     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1381         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1382         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1383     return true;
1384   }
1385 
1386   return false;
1387 }
1388 
1389 // Performs a semantic analysis on the call to built-in Pipe
1390 //        Query Functions.
1391 // \param S Reference to the semantic analyzer.
1392 // \param Call The call to the builtin function to be analyzed.
1393 // \return True if a semantic error was found, false otherwise.
1394 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1395   if (checkArgCount(S, Call, 1))
1396     return true;
1397 
1398   if (!Call->getArg(0)->getType()->isPipeType()) {
1399     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1400         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1401     return true;
1402   }
1403 
1404   return false;
1405 }
1406 
1407 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1408 // Performs semantic analysis for the to_global/local/private call.
1409 // \param S Reference to the semantic analyzer.
1410 // \param BuiltinID ID of the builtin function.
1411 // \param Call A pointer to the builtin call.
1412 // \return True if a semantic error has been found, false otherwise.
1413 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1414                                     CallExpr *Call) {
1415   if (checkArgCount(S, Call, 1))
1416     return true;
1417 
1418   auto RT = Call->getArg(0)->getType();
1419   if (!RT->isPointerType() || RT->getPointeeType()
1420       .getAddressSpace() == LangAS::opencl_constant) {
1421     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1422         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1423     return true;
1424   }
1425 
1426   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1427     S.Diag(Call->getArg(0)->getBeginLoc(),
1428            diag::warn_opencl_generic_address_space_arg)
1429         << Call->getDirectCallee()->getNameInfo().getAsString()
1430         << Call->getArg(0)->getSourceRange();
1431   }
1432 
1433   RT = RT->getPointeeType();
1434   auto Qual = RT.getQualifiers();
1435   switch (BuiltinID) {
1436   case Builtin::BIto_global:
1437     Qual.setAddressSpace(LangAS::opencl_global);
1438     break;
1439   case Builtin::BIto_local:
1440     Qual.setAddressSpace(LangAS::opencl_local);
1441     break;
1442   case Builtin::BIto_private:
1443     Qual.setAddressSpace(LangAS::opencl_private);
1444     break;
1445   default:
1446     llvm_unreachable("Invalid builtin function");
1447   }
1448   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1449       RT.getUnqualifiedType(), Qual)));
1450 
1451   return false;
1452 }
1453 
1454 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1455   if (checkArgCount(S, TheCall, 1))
1456     return ExprError();
1457 
1458   // Compute __builtin_launder's parameter type from the argument.
1459   // The parameter type is:
1460   //  * The type of the argument if it's not an array or function type,
1461   //  Otherwise,
1462   //  * The decayed argument type.
1463   QualType ParamTy = [&]() {
1464     QualType ArgTy = TheCall->getArg(0)->getType();
1465     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1466       return S.Context.getPointerType(Ty->getElementType());
1467     if (ArgTy->isFunctionType()) {
1468       return S.Context.getPointerType(ArgTy);
1469     }
1470     return ArgTy;
1471   }();
1472 
1473   TheCall->setType(ParamTy);
1474 
1475   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1476     if (!ParamTy->isPointerType())
1477       return 0;
1478     if (ParamTy->isFunctionPointerType())
1479       return 1;
1480     if (ParamTy->isVoidPointerType())
1481       return 2;
1482     return llvm::Optional<unsigned>{};
1483   }();
1484   if (DiagSelect.hasValue()) {
1485     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1486         << DiagSelect.getValue() << TheCall->getSourceRange();
1487     return ExprError();
1488   }
1489 
1490   // We either have an incomplete class type, or we have a class template
1491   // whose instantiation has not been forced. Example:
1492   //
1493   //   template <class T> struct Foo { T value; };
1494   //   Foo<int> *p = nullptr;
1495   //   auto *d = __builtin_launder(p);
1496   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1497                             diag::err_incomplete_type))
1498     return ExprError();
1499 
1500   assert(ParamTy->getPointeeType()->isObjectType() &&
1501          "Unhandled non-object pointer case");
1502 
1503   InitializedEntity Entity =
1504       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1505   ExprResult Arg =
1506       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1507   if (Arg.isInvalid())
1508     return ExprError();
1509   TheCall->setArg(0, Arg.get());
1510 
1511   return TheCall;
1512 }
1513 
1514 // Emit an error and return true if the current architecture is not in the list
1515 // of supported architectures.
1516 static bool
1517 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1518                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1519   llvm::Triple::ArchType CurArch =
1520       S.getASTContext().getTargetInfo().getTriple().getArch();
1521   if (llvm::is_contained(SupportedArchs, CurArch))
1522     return false;
1523   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1524       << TheCall->getSourceRange();
1525   return true;
1526 }
1527 
1528 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1529                                  SourceLocation CallSiteLoc);
1530 
1531 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1532                                       CallExpr *TheCall) {
1533   switch (TI.getTriple().getArch()) {
1534   default:
1535     // Some builtins don't require additional checking, so just consider these
1536     // acceptable.
1537     return false;
1538   case llvm::Triple::arm:
1539   case llvm::Triple::armeb:
1540   case llvm::Triple::thumb:
1541   case llvm::Triple::thumbeb:
1542     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1543   case llvm::Triple::aarch64:
1544   case llvm::Triple::aarch64_32:
1545   case llvm::Triple::aarch64_be:
1546     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1547   case llvm::Triple::bpfeb:
1548   case llvm::Triple::bpfel:
1549     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1550   case llvm::Triple::hexagon:
1551     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1552   case llvm::Triple::mips:
1553   case llvm::Triple::mipsel:
1554   case llvm::Triple::mips64:
1555   case llvm::Triple::mips64el:
1556     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1557   case llvm::Triple::systemz:
1558     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1559   case llvm::Triple::x86:
1560   case llvm::Triple::x86_64:
1561     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1562   case llvm::Triple::ppc:
1563   case llvm::Triple::ppcle:
1564   case llvm::Triple::ppc64:
1565   case llvm::Triple::ppc64le:
1566     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1567   case llvm::Triple::amdgcn:
1568     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1569   case llvm::Triple::riscv32:
1570   case llvm::Triple::riscv64:
1571     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1572   }
1573 }
1574 
1575 ExprResult
1576 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1577                                CallExpr *TheCall) {
1578   ExprResult TheCallResult(TheCall);
1579 
1580   // Find out if any arguments are required to be integer constant expressions.
1581   unsigned ICEArguments = 0;
1582   ASTContext::GetBuiltinTypeError Error;
1583   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1584   if (Error != ASTContext::GE_None)
1585     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1586 
1587   // If any arguments are required to be ICE's, check and diagnose.
1588   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1589     // Skip arguments not required to be ICE's.
1590     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1591 
1592     llvm::APSInt Result;
1593     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1594       return true;
1595     ICEArguments &= ~(1 << ArgNo);
1596   }
1597 
1598   switch (BuiltinID) {
1599   case Builtin::BI__builtin___CFStringMakeConstantString:
1600     assert(TheCall->getNumArgs() == 1 &&
1601            "Wrong # arguments to builtin CFStringMakeConstantString");
1602     if (CheckObjCString(TheCall->getArg(0)))
1603       return ExprError();
1604     break;
1605   case Builtin::BI__builtin_ms_va_start:
1606   case Builtin::BI__builtin_stdarg_start:
1607   case Builtin::BI__builtin_va_start:
1608     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1609       return ExprError();
1610     break;
1611   case Builtin::BI__va_start: {
1612     switch (Context.getTargetInfo().getTriple().getArch()) {
1613     case llvm::Triple::aarch64:
1614     case llvm::Triple::arm:
1615     case llvm::Triple::thumb:
1616       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1617         return ExprError();
1618       break;
1619     default:
1620       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1621         return ExprError();
1622       break;
1623     }
1624     break;
1625   }
1626 
1627   // The acquire, release, and no fence variants are ARM and AArch64 only.
1628   case Builtin::BI_interlockedbittestandset_acq:
1629   case Builtin::BI_interlockedbittestandset_rel:
1630   case Builtin::BI_interlockedbittestandset_nf:
1631   case Builtin::BI_interlockedbittestandreset_acq:
1632   case Builtin::BI_interlockedbittestandreset_rel:
1633   case Builtin::BI_interlockedbittestandreset_nf:
1634     if (CheckBuiltinTargetSupport(
1635             *this, BuiltinID, TheCall,
1636             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1637       return ExprError();
1638     break;
1639 
1640   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1641   case Builtin::BI_bittest64:
1642   case Builtin::BI_bittestandcomplement64:
1643   case Builtin::BI_bittestandreset64:
1644   case Builtin::BI_bittestandset64:
1645   case Builtin::BI_interlockedbittestandreset64:
1646   case Builtin::BI_interlockedbittestandset64:
1647     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1648                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1649                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1650       return ExprError();
1651     break;
1652 
1653   case Builtin::BI__builtin_isgreater:
1654   case Builtin::BI__builtin_isgreaterequal:
1655   case Builtin::BI__builtin_isless:
1656   case Builtin::BI__builtin_islessequal:
1657   case Builtin::BI__builtin_islessgreater:
1658   case Builtin::BI__builtin_isunordered:
1659     if (SemaBuiltinUnorderedCompare(TheCall))
1660       return ExprError();
1661     break;
1662   case Builtin::BI__builtin_fpclassify:
1663     if (SemaBuiltinFPClassification(TheCall, 6))
1664       return ExprError();
1665     break;
1666   case Builtin::BI__builtin_isfinite:
1667   case Builtin::BI__builtin_isinf:
1668   case Builtin::BI__builtin_isinf_sign:
1669   case Builtin::BI__builtin_isnan:
1670   case Builtin::BI__builtin_isnormal:
1671   case Builtin::BI__builtin_signbit:
1672   case Builtin::BI__builtin_signbitf:
1673   case Builtin::BI__builtin_signbitl:
1674     if (SemaBuiltinFPClassification(TheCall, 1))
1675       return ExprError();
1676     break;
1677   case Builtin::BI__builtin_shufflevector:
1678     return SemaBuiltinShuffleVector(TheCall);
1679     // TheCall will be freed by the smart pointer here, but that's fine, since
1680     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1681   case Builtin::BI__builtin_prefetch:
1682     if (SemaBuiltinPrefetch(TheCall))
1683       return ExprError();
1684     break;
1685   case Builtin::BI__builtin_alloca_with_align:
1686     if (SemaBuiltinAllocaWithAlign(TheCall))
1687       return ExprError();
1688     LLVM_FALLTHROUGH;
1689   case Builtin::BI__builtin_alloca:
1690     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1691         << TheCall->getDirectCallee();
1692     break;
1693   case Builtin::BI__arithmetic_fence:
1694     if (SemaBuiltinArithmeticFence(TheCall))
1695       return ExprError();
1696     break;
1697   case Builtin::BI__assume:
1698   case Builtin::BI__builtin_assume:
1699     if (SemaBuiltinAssume(TheCall))
1700       return ExprError();
1701     break;
1702   case Builtin::BI__builtin_assume_aligned:
1703     if (SemaBuiltinAssumeAligned(TheCall))
1704       return ExprError();
1705     break;
1706   case Builtin::BI__builtin_dynamic_object_size:
1707   case Builtin::BI__builtin_object_size:
1708     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1709       return ExprError();
1710     break;
1711   case Builtin::BI__builtin_longjmp:
1712     if (SemaBuiltinLongjmp(TheCall))
1713       return ExprError();
1714     break;
1715   case Builtin::BI__builtin_setjmp:
1716     if (SemaBuiltinSetjmp(TheCall))
1717       return ExprError();
1718     break;
1719   case Builtin::BI__builtin_classify_type:
1720     if (checkArgCount(*this, TheCall, 1)) return true;
1721     TheCall->setType(Context.IntTy);
1722     break;
1723   case Builtin::BI__builtin_complex:
1724     if (SemaBuiltinComplex(TheCall))
1725       return ExprError();
1726     break;
1727   case Builtin::BI__builtin_constant_p: {
1728     if (checkArgCount(*this, TheCall, 1)) return true;
1729     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1730     if (Arg.isInvalid()) return true;
1731     TheCall->setArg(0, Arg.get());
1732     TheCall->setType(Context.IntTy);
1733     break;
1734   }
1735   case Builtin::BI__builtin_launder:
1736     return SemaBuiltinLaunder(*this, TheCall);
1737   case Builtin::BI__sync_fetch_and_add:
1738   case Builtin::BI__sync_fetch_and_add_1:
1739   case Builtin::BI__sync_fetch_and_add_2:
1740   case Builtin::BI__sync_fetch_and_add_4:
1741   case Builtin::BI__sync_fetch_and_add_8:
1742   case Builtin::BI__sync_fetch_and_add_16:
1743   case Builtin::BI__sync_fetch_and_sub:
1744   case Builtin::BI__sync_fetch_and_sub_1:
1745   case Builtin::BI__sync_fetch_and_sub_2:
1746   case Builtin::BI__sync_fetch_and_sub_4:
1747   case Builtin::BI__sync_fetch_and_sub_8:
1748   case Builtin::BI__sync_fetch_and_sub_16:
1749   case Builtin::BI__sync_fetch_and_or:
1750   case Builtin::BI__sync_fetch_and_or_1:
1751   case Builtin::BI__sync_fetch_and_or_2:
1752   case Builtin::BI__sync_fetch_and_or_4:
1753   case Builtin::BI__sync_fetch_and_or_8:
1754   case Builtin::BI__sync_fetch_and_or_16:
1755   case Builtin::BI__sync_fetch_and_and:
1756   case Builtin::BI__sync_fetch_and_and_1:
1757   case Builtin::BI__sync_fetch_and_and_2:
1758   case Builtin::BI__sync_fetch_and_and_4:
1759   case Builtin::BI__sync_fetch_and_and_8:
1760   case Builtin::BI__sync_fetch_and_and_16:
1761   case Builtin::BI__sync_fetch_and_xor:
1762   case Builtin::BI__sync_fetch_and_xor_1:
1763   case Builtin::BI__sync_fetch_and_xor_2:
1764   case Builtin::BI__sync_fetch_and_xor_4:
1765   case Builtin::BI__sync_fetch_and_xor_8:
1766   case Builtin::BI__sync_fetch_and_xor_16:
1767   case Builtin::BI__sync_fetch_and_nand:
1768   case Builtin::BI__sync_fetch_and_nand_1:
1769   case Builtin::BI__sync_fetch_and_nand_2:
1770   case Builtin::BI__sync_fetch_and_nand_4:
1771   case Builtin::BI__sync_fetch_and_nand_8:
1772   case Builtin::BI__sync_fetch_and_nand_16:
1773   case Builtin::BI__sync_add_and_fetch:
1774   case Builtin::BI__sync_add_and_fetch_1:
1775   case Builtin::BI__sync_add_and_fetch_2:
1776   case Builtin::BI__sync_add_and_fetch_4:
1777   case Builtin::BI__sync_add_and_fetch_8:
1778   case Builtin::BI__sync_add_and_fetch_16:
1779   case Builtin::BI__sync_sub_and_fetch:
1780   case Builtin::BI__sync_sub_and_fetch_1:
1781   case Builtin::BI__sync_sub_and_fetch_2:
1782   case Builtin::BI__sync_sub_and_fetch_4:
1783   case Builtin::BI__sync_sub_and_fetch_8:
1784   case Builtin::BI__sync_sub_and_fetch_16:
1785   case Builtin::BI__sync_and_and_fetch:
1786   case Builtin::BI__sync_and_and_fetch_1:
1787   case Builtin::BI__sync_and_and_fetch_2:
1788   case Builtin::BI__sync_and_and_fetch_4:
1789   case Builtin::BI__sync_and_and_fetch_8:
1790   case Builtin::BI__sync_and_and_fetch_16:
1791   case Builtin::BI__sync_or_and_fetch:
1792   case Builtin::BI__sync_or_and_fetch_1:
1793   case Builtin::BI__sync_or_and_fetch_2:
1794   case Builtin::BI__sync_or_and_fetch_4:
1795   case Builtin::BI__sync_or_and_fetch_8:
1796   case Builtin::BI__sync_or_and_fetch_16:
1797   case Builtin::BI__sync_xor_and_fetch:
1798   case Builtin::BI__sync_xor_and_fetch_1:
1799   case Builtin::BI__sync_xor_and_fetch_2:
1800   case Builtin::BI__sync_xor_and_fetch_4:
1801   case Builtin::BI__sync_xor_and_fetch_8:
1802   case Builtin::BI__sync_xor_and_fetch_16:
1803   case Builtin::BI__sync_nand_and_fetch:
1804   case Builtin::BI__sync_nand_and_fetch_1:
1805   case Builtin::BI__sync_nand_and_fetch_2:
1806   case Builtin::BI__sync_nand_and_fetch_4:
1807   case Builtin::BI__sync_nand_and_fetch_8:
1808   case Builtin::BI__sync_nand_and_fetch_16:
1809   case Builtin::BI__sync_val_compare_and_swap:
1810   case Builtin::BI__sync_val_compare_and_swap_1:
1811   case Builtin::BI__sync_val_compare_and_swap_2:
1812   case Builtin::BI__sync_val_compare_and_swap_4:
1813   case Builtin::BI__sync_val_compare_and_swap_8:
1814   case Builtin::BI__sync_val_compare_and_swap_16:
1815   case Builtin::BI__sync_bool_compare_and_swap:
1816   case Builtin::BI__sync_bool_compare_and_swap_1:
1817   case Builtin::BI__sync_bool_compare_and_swap_2:
1818   case Builtin::BI__sync_bool_compare_and_swap_4:
1819   case Builtin::BI__sync_bool_compare_and_swap_8:
1820   case Builtin::BI__sync_bool_compare_and_swap_16:
1821   case Builtin::BI__sync_lock_test_and_set:
1822   case Builtin::BI__sync_lock_test_and_set_1:
1823   case Builtin::BI__sync_lock_test_and_set_2:
1824   case Builtin::BI__sync_lock_test_and_set_4:
1825   case Builtin::BI__sync_lock_test_and_set_8:
1826   case Builtin::BI__sync_lock_test_and_set_16:
1827   case Builtin::BI__sync_lock_release:
1828   case Builtin::BI__sync_lock_release_1:
1829   case Builtin::BI__sync_lock_release_2:
1830   case Builtin::BI__sync_lock_release_4:
1831   case Builtin::BI__sync_lock_release_8:
1832   case Builtin::BI__sync_lock_release_16:
1833   case Builtin::BI__sync_swap:
1834   case Builtin::BI__sync_swap_1:
1835   case Builtin::BI__sync_swap_2:
1836   case Builtin::BI__sync_swap_4:
1837   case Builtin::BI__sync_swap_8:
1838   case Builtin::BI__sync_swap_16:
1839     return SemaBuiltinAtomicOverloaded(TheCallResult);
1840   case Builtin::BI__sync_synchronize:
1841     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1842         << TheCall->getCallee()->getSourceRange();
1843     break;
1844   case Builtin::BI__builtin_nontemporal_load:
1845   case Builtin::BI__builtin_nontemporal_store:
1846     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1847   case Builtin::BI__builtin_memcpy_inline: {
1848     clang::Expr *SizeOp = TheCall->getArg(2);
1849     // We warn about copying to or from `nullptr` pointers when `size` is
1850     // greater than 0. When `size` is value dependent we cannot evaluate its
1851     // value so we bail out.
1852     if (SizeOp->isValueDependent())
1853       break;
1854     if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
1855       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1856       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1857     }
1858     break;
1859   }
1860 #define BUILTIN(ID, TYPE, ATTRS)
1861 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1862   case Builtin::BI##ID: \
1863     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1864 #include "clang/Basic/Builtins.def"
1865   case Builtin::BI__annotation:
1866     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1867       return ExprError();
1868     break;
1869   case Builtin::BI__builtin_annotation:
1870     if (SemaBuiltinAnnotation(*this, TheCall))
1871       return ExprError();
1872     break;
1873   case Builtin::BI__builtin_addressof:
1874     if (SemaBuiltinAddressof(*this, TheCall))
1875       return ExprError();
1876     break;
1877   case Builtin::BI__builtin_is_aligned:
1878   case Builtin::BI__builtin_align_up:
1879   case Builtin::BI__builtin_align_down:
1880     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1881       return ExprError();
1882     break;
1883   case Builtin::BI__builtin_add_overflow:
1884   case Builtin::BI__builtin_sub_overflow:
1885   case Builtin::BI__builtin_mul_overflow:
1886     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1887       return ExprError();
1888     break;
1889   case Builtin::BI__builtin_operator_new:
1890   case Builtin::BI__builtin_operator_delete: {
1891     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1892     ExprResult Res =
1893         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1894     if (Res.isInvalid())
1895       CorrectDelayedTyposInExpr(TheCallResult.get());
1896     return Res;
1897   }
1898   case Builtin::BI__builtin_dump_struct: {
1899     // We first want to ensure we are called with 2 arguments
1900     if (checkArgCount(*this, TheCall, 2))
1901       return ExprError();
1902     // Ensure that the first argument is of type 'struct XX *'
1903     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1904     const QualType PtrArgType = PtrArg->getType();
1905     if (!PtrArgType->isPointerType() ||
1906         !PtrArgType->getPointeeType()->isRecordType()) {
1907       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1908           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1909           << "structure pointer";
1910       return ExprError();
1911     }
1912 
1913     // Ensure that the second argument is of type 'FunctionType'
1914     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1915     const QualType FnPtrArgType = FnPtrArg->getType();
1916     if (!FnPtrArgType->isPointerType()) {
1917       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1918           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1919           << FnPtrArgType << "'int (*)(const char *, ...)'";
1920       return ExprError();
1921     }
1922 
1923     const auto *FuncType =
1924         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1925 
1926     if (!FuncType) {
1927       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1928           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1929           << FnPtrArgType << "'int (*)(const char *, ...)'";
1930       return ExprError();
1931     }
1932 
1933     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1934       if (!FT->getNumParams()) {
1935         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1936             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1937             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1938         return ExprError();
1939       }
1940       QualType PT = FT->getParamType(0);
1941       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1942           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1943           !PT->getPointeeType().isConstQualified()) {
1944         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1945             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1946             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1947         return ExprError();
1948       }
1949     }
1950 
1951     TheCall->setType(Context.IntTy);
1952     break;
1953   }
1954   case Builtin::BI__builtin_expect_with_probability: {
1955     // We first want to ensure we are called with 3 arguments
1956     if (checkArgCount(*this, TheCall, 3))
1957       return ExprError();
1958     // then check probability is constant float in range [0.0, 1.0]
1959     const Expr *ProbArg = TheCall->getArg(2);
1960     SmallVector<PartialDiagnosticAt, 8> Notes;
1961     Expr::EvalResult Eval;
1962     Eval.Diag = &Notes;
1963     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1964         !Eval.Val.isFloat()) {
1965       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1966           << ProbArg->getSourceRange();
1967       for (const PartialDiagnosticAt &PDiag : Notes)
1968         Diag(PDiag.first, PDiag.second);
1969       return ExprError();
1970     }
1971     llvm::APFloat Probability = Eval.Val.getFloat();
1972     bool LoseInfo = false;
1973     Probability.convert(llvm::APFloat::IEEEdouble(),
1974                         llvm::RoundingMode::Dynamic, &LoseInfo);
1975     if (!(Probability >= llvm::APFloat(0.0) &&
1976           Probability <= llvm::APFloat(1.0))) {
1977       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1978           << ProbArg->getSourceRange();
1979       return ExprError();
1980     }
1981     break;
1982   }
1983   case Builtin::BI__builtin_preserve_access_index:
1984     if (SemaBuiltinPreserveAI(*this, TheCall))
1985       return ExprError();
1986     break;
1987   case Builtin::BI__builtin_call_with_static_chain:
1988     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1989       return ExprError();
1990     break;
1991   case Builtin::BI__exception_code:
1992   case Builtin::BI_exception_code:
1993     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1994                                  diag::err_seh___except_block))
1995       return ExprError();
1996     break;
1997   case Builtin::BI__exception_info:
1998   case Builtin::BI_exception_info:
1999     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
2000                                  diag::err_seh___except_filter))
2001       return ExprError();
2002     break;
2003   case Builtin::BI__GetExceptionInfo:
2004     if (checkArgCount(*this, TheCall, 1))
2005       return ExprError();
2006 
2007     if (CheckCXXThrowOperand(
2008             TheCall->getBeginLoc(),
2009             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
2010             TheCall))
2011       return ExprError();
2012 
2013     TheCall->setType(Context.VoidPtrTy);
2014     break;
2015   // OpenCL v2.0, s6.13.16 - Pipe functions
2016   case Builtin::BIread_pipe:
2017   case Builtin::BIwrite_pipe:
2018     // Since those two functions are declared with var args, we need a semantic
2019     // check for the argument.
2020     if (SemaBuiltinRWPipe(*this, TheCall))
2021       return ExprError();
2022     break;
2023   case Builtin::BIreserve_read_pipe:
2024   case Builtin::BIreserve_write_pipe:
2025   case Builtin::BIwork_group_reserve_read_pipe:
2026   case Builtin::BIwork_group_reserve_write_pipe:
2027     if (SemaBuiltinReserveRWPipe(*this, TheCall))
2028       return ExprError();
2029     break;
2030   case Builtin::BIsub_group_reserve_read_pipe:
2031   case Builtin::BIsub_group_reserve_write_pipe:
2032     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2033         SemaBuiltinReserveRWPipe(*this, TheCall))
2034       return ExprError();
2035     break;
2036   case Builtin::BIcommit_read_pipe:
2037   case Builtin::BIcommit_write_pipe:
2038   case Builtin::BIwork_group_commit_read_pipe:
2039   case Builtin::BIwork_group_commit_write_pipe:
2040     if (SemaBuiltinCommitRWPipe(*this, TheCall))
2041       return ExprError();
2042     break;
2043   case Builtin::BIsub_group_commit_read_pipe:
2044   case Builtin::BIsub_group_commit_write_pipe:
2045     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2046         SemaBuiltinCommitRWPipe(*this, TheCall))
2047       return ExprError();
2048     break;
2049   case Builtin::BIget_pipe_num_packets:
2050   case Builtin::BIget_pipe_max_packets:
2051     if (SemaBuiltinPipePackets(*this, TheCall))
2052       return ExprError();
2053     break;
2054   case Builtin::BIto_global:
2055   case Builtin::BIto_local:
2056   case Builtin::BIto_private:
2057     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
2058       return ExprError();
2059     break;
2060   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
2061   case Builtin::BIenqueue_kernel:
2062     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
2063       return ExprError();
2064     break;
2065   case Builtin::BIget_kernel_work_group_size:
2066   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
2067     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
2068       return ExprError();
2069     break;
2070   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
2071   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
2072     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
2073       return ExprError();
2074     break;
2075   case Builtin::BI__builtin_os_log_format:
2076     Cleanup.setExprNeedsCleanups(true);
2077     LLVM_FALLTHROUGH;
2078   case Builtin::BI__builtin_os_log_format_buffer_size:
2079     if (SemaBuiltinOSLogFormat(TheCall))
2080       return ExprError();
2081     break;
2082   case Builtin::BI__builtin_frame_address:
2083   case Builtin::BI__builtin_return_address: {
2084     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
2085       return ExprError();
2086 
2087     // -Wframe-address warning if non-zero passed to builtin
2088     // return/frame address.
2089     Expr::EvalResult Result;
2090     if (!TheCall->getArg(0)->isValueDependent() &&
2091         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
2092         Result.Val.getInt() != 0)
2093       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
2094           << ((BuiltinID == Builtin::BI__builtin_return_address)
2095                   ? "__builtin_return_address"
2096                   : "__builtin_frame_address")
2097           << TheCall->getSourceRange();
2098     break;
2099   }
2100 
2101   case Builtin::BI__builtin_elementwise_abs:
2102     if (SemaBuiltinElementwiseMathOneArg(TheCall))
2103       return ExprError();
2104     break;
2105   case Builtin::BI__builtin_elementwise_min:
2106   case Builtin::BI__builtin_elementwise_max:
2107     if (SemaBuiltinElementwiseMath(TheCall))
2108       return ExprError();
2109     break;
2110   case Builtin::BI__builtin_reduce_max:
2111   case Builtin::BI__builtin_reduce_min:
2112     if (SemaBuiltinReduceMath(TheCall))
2113       return ExprError();
2114     break;
2115   case Builtin::BI__builtin_matrix_transpose:
2116     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
2117 
2118   case Builtin::BI__builtin_matrix_column_major_load:
2119     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
2120 
2121   case Builtin::BI__builtin_matrix_column_major_store:
2122     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
2123 
2124   case Builtin::BI__builtin_get_device_side_mangled_name: {
2125     auto Check = [](CallExpr *TheCall) {
2126       if (TheCall->getNumArgs() != 1)
2127         return false;
2128       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
2129       if (!DRE)
2130         return false;
2131       auto *D = DRE->getDecl();
2132       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
2133         return false;
2134       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
2135              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2136     };
2137     if (!Check(TheCall)) {
2138       Diag(TheCall->getBeginLoc(),
2139            diag::err_hip_invalid_args_builtin_mangled_name);
2140       return ExprError();
2141     }
2142   }
2143   }
2144 
2145   // Since the target specific builtins for each arch overlap, only check those
2146   // of the arch we are compiling for.
2147   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2148     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2149       assert(Context.getAuxTargetInfo() &&
2150              "Aux Target Builtin, but not an aux target?");
2151 
2152       if (CheckTSBuiltinFunctionCall(
2153               *Context.getAuxTargetInfo(),
2154               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2155         return ExprError();
2156     } else {
2157       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2158                                      TheCall))
2159         return ExprError();
2160     }
2161   }
2162 
2163   return TheCallResult;
2164 }
2165 
2166 // Get the valid immediate range for the specified NEON type code.
2167 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2168   NeonTypeFlags Type(t);
2169   int IsQuad = ForceQuad ? true : Type.isQuad();
2170   switch (Type.getEltType()) {
2171   case NeonTypeFlags::Int8:
2172   case NeonTypeFlags::Poly8:
2173     return shift ? 7 : (8 << IsQuad) - 1;
2174   case NeonTypeFlags::Int16:
2175   case NeonTypeFlags::Poly16:
2176     return shift ? 15 : (4 << IsQuad) - 1;
2177   case NeonTypeFlags::Int32:
2178     return shift ? 31 : (2 << IsQuad) - 1;
2179   case NeonTypeFlags::Int64:
2180   case NeonTypeFlags::Poly64:
2181     return shift ? 63 : (1 << IsQuad) - 1;
2182   case NeonTypeFlags::Poly128:
2183     return shift ? 127 : (1 << IsQuad) - 1;
2184   case NeonTypeFlags::Float16:
2185     assert(!shift && "cannot shift float types!");
2186     return (4 << IsQuad) - 1;
2187   case NeonTypeFlags::Float32:
2188     assert(!shift && "cannot shift float types!");
2189     return (2 << IsQuad) - 1;
2190   case NeonTypeFlags::Float64:
2191     assert(!shift && "cannot shift float types!");
2192     return (1 << IsQuad) - 1;
2193   case NeonTypeFlags::BFloat16:
2194     assert(!shift && "cannot shift float types!");
2195     return (4 << IsQuad) - 1;
2196   }
2197   llvm_unreachable("Invalid NeonTypeFlag!");
2198 }
2199 
2200 /// getNeonEltType - Return the QualType corresponding to the elements of
2201 /// the vector type specified by the NeonTypeFlags.  This is used to check
2202 /// the pointer arguments for Neon load/store intrinsics.
2203 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2204                                bool IsPolyUnsigned, bool IsInt64Long) {
2205   switch (Flags.getEltType()) {
2206   case NeonTypeFlags::Int8:
2207     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2208   case NeonTypeFlags::Int16:
2209     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2210   case NeonTypeFlags::Int32:
2211     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2212   case NeonTypeFlags::Int64:
2213     if (IsInt64Long)
2214       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2215     else
2216       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2217                                 : Context.LongLongTy;
2218   case NeonTypeFlags::Poly8:
2219     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2220   case NeonTypeFlags::Poly16:
2221     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2222   case NeonTypeFlags::Poly64:
2223     if (IsInt64Long)
2224       return Context.UnsignedLongTy;
2225     else
2226       return Context.UnsignedLongLongTy;
2227   case NeonTypeFlags::Poly128:
2228     break;
2229   case NeonTypeFlags::Float16:
2230     return Context.HalfTy;
2231   case NeonTypeFlags::Float32:
2232     return Context.FloatTy;
2233   case NeonTypeFlags::Float64:
2234     return Context.DoubleTy;
2235   case NeonTypeFlags::BFloat16:
2236     return Context.BFloat16Ty;
2237   }
2238   llvm_unreachable("Invalid NeonTypeFlag!");
2239 }
2240 
2241 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2242   // Range check SVE intrinsics that take immediate values.
2243   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2244 
2245   switch (BuiltinID) {
2246   default:
2247     return false;
2248 #define GET_SVE_IMMEDIATE_CHECK
2249 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2250 #undef GET_SVE_IMMEDIATE_CHECK
2251   }
2252 
2253   // Perform all the immediate checks for this builtin call.
2254   bool HasError = false;
2255   for (auto &I : ImmChecks) {
2256     int ArgNum, CheckTy, ElementSizeInBits;
2257     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2258 
2259     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2260 
2261     // Function that checks whether the operand (ArgNum) is an immediate
2262     // that is one of the predefined values.
2263     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2264                                    int ErrDiag) -> bool {
2265       // We can't check the value of a dependent argument.
2266       Expr *Arg = TheCall->getArg(ArgNum);
2267       if (Arg->isTypeDependent() || Arg->isValueDependent())
2268         return false;
2269 
2270       // Check constant-ness first.
2271       llvm::APSInt Imm;
2272       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2273         return true;
2274 
2275       if (!CheckImm(Imm.getSExtValue()))
2276         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2277       return false;
2278     };
2279 
2280     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2281     case SVETypeFlags::ImmCheck0_31:
2282       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2283         HasError = true;
2284       break;
2285     case SVETypeFlags::ImmCheck0_13:
2286       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2287         HasError = true;
2288       break;
2289     case SVETypeFlags::ImmCheck1_16:
2290       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2291         HasError = true;
2292       break;
2293     case SVETypeFlags::ImmCheck0_7:
2294       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2295         HasError = true;
2296       break;
2297     case SVETypeFlags::ImmCheckExtract:
2298       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2299                                       (2048 / ElementSizeInBits) - 1))
2300         HasError = true;
2301       break;
2302     case SVETypeFlags::ImmCheckShiftRight:
2303       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2304         HasError = true;
2305       break;
2306     case SVETypeFlags::ImmCheckShiftRightNarrow:
2307       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2308                                       ElementSizeInBits / 2))
2309         HasError = true;
2310       break;
2311     case SVETypeFlags::ImmCheckShiftLeft:
2312       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2313                                       ElementSizeInBits - 1))
2314         HasError = true;
2315       break;
2316     case SVETypeFlags::ImmCheckLaneIndex:
2317       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2318                                       (128 / (1 * ElementSizeInBits)) - 1))
2319         HasError = true;
2320       break;
2321     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2322       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2323                                       (128 / (2 * ElementSizeInBits)) - 1))
2324         HasError = true;
2325       break;
2326     case SVETypeFlags::ImmCheckLaneIndexDot:
2327       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2328                                       (128 / (4 * ElementSizeInBits)) - 1))
2329         HasError = true;
2330       break;
2331     case SVETypeFlags::ImmCheckComplexRot90_270:
2332       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2333                               diag::err_rotation_argument_to_cadd))
2334         HasError = true;
2335       break;
2336     case SVETypeFlags::ImmCheckComplexRotAll90:
2337       if (CheckImmediateInSet(
2338               [](int64_t V) {
2339                 return V == 0 || V == 90 || V == 180 || V == 270;
2340               },
2341               diag::err_rotation_argument_to_cmla))
2342         HasError = true;
2343       break;
2344     case SVETypeFlags::ImmCheck0_1:
2345       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2346         HasError = true;
2347       break;
2348     case SVETypeFlags::ImmCheck0_2:
2349       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2350         HasError = true;
2351       break;
2352     case SVETypeFlags::ImmCheck0_3:
2353       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2354         HasError = true;
2355       break;
2356     }
2357   }
2358 
2359   return HasError;
2360 }
2361 
2362 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2363                                         unsigned BuiltinID, CallExpr *TheCall) {
2364   llvm::APSInt Result;
2365   uint64_t mask = 0;
2366   unsigned TV = 0;
2367   int PtrArgNum = -1;
2368   bool HasConstPtr = false;
2369   switch (BuiltinID) {
2370 #define GET_NEON_OVERLOAD_CHECK
2371 #include "clang/Basic/arm_neon.inc"
2372 #include "clang/Basic/arm_fp16.inc"
2373 #undef GET_NEON_OVERLOAD_CHECK
2374   }
2375 
2376   // For NEON intrinsics which are overloaded on vector element type, validate
2377   // the immediate which specifies which variant to emit.
2378   unsigned ImmArg = TheCall->getNumArgs()-1;
2379   if (mask) {
2380     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2381       return true;
2382 
2383     TV = Result.getLimitedValue(64);
2384     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2385       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2386              << TheCall->getArg(ImmArg)->getSourceRange();
2387   }
2388 
2389   if (PtrArgNum >= 0) {
2390     // Check that pointer arguments have the specified type.
2391     Expr *Arg = TheCall->getArg(PtrArgNum);
2392     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2393       Arg = ICE->getSubExpr();
2394     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2395     QualType RHSTy = RHS.get()->getType();
2396 
2397     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2398     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2399                           Arch == llvm::Triple::aarch64_32 ||
2400                           Arch == llvm::Triple::aarch64_be;
2401     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2402     QualType EltTy =
2403         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2404     if (HasConstPtr)
2405       EltTy = EltTy.withConst();
2406     QualType LHSTy = Context.getPointerType(EltTy);
2407     AssignConvertType ConvTy;
2408     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2409     if (RHS.isInvalid())
2410       return true;
2411     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2412                                  RHS.get(), AA_Assigning))
2413       return true;
2414   }
2415 
2416   // For NEON intrinsics which take an immediate value as part of the
2417   // instruction, range check them here.
2418   unsigned i = 0, l = 0, u = 0;
2419   switch (BuiltinID) {
2420   default:
2421     return false;
2422   #define GET_NEON_IMMEDIATE_CHECK
2423   #include "clang/Basic/arm_neon.inc"
2424   #include "clang/Basic/arm_fp16.inc"
2425   #undef GET_NEON_IMMEDIATE_CHECK
2426   }
2427 
2428   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2429 }
2430 
2431 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2432   switch (BuiltinID) {
2433   default:
2434     return false;
2435   #include "clang/Basic/arm_mve_builtin_sema.inc"
2436   }
2437 }
2438 
2439 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2440                                        CallExpr *TheCall) {
2441   bool Err = false;
2442   switch (BuiltinID) {
2443   default:
2444     return false;
2445 #include "clang/Basic/arm_cde_builtin_sema.inc"
2446   }
2447 
2448   if (Err)
2449     return true;
2450 
2451   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2452 }
2453 
2454 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2455                                         const Expr *CoprocArg, bool WantCDE) {
2456   if (isConstantEvaluated())
2457     return false;
2458 
2459   // We can't check the value of a dependent argument.
2460   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2461     return false;
2462 
2463   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2464   int64_t CoprocNo = CoprocNoAP.getExtValue();
2465   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2466 
2467   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2468   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2469 
2470   if (IsCDECoproc != WantCDE)
2471     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2472            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2473 
2474   return false;
2475 }
2476 
2477 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2478                                         unsigned MaxWidth) {
2479   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2480           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2481           BuiltinID == ARM::BI__builtin_arm_strex ||
2482           BuiltinID == ARM::BI__builtin_arm_stlex ||
2483           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2484           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2485           BuiltinID == AArch64::BI__builtin_arm_strex ||
2486           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2487          "unexpected ARM builtin");
2488   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2489                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2490                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2491                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2492 
2493   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2494 
2495   // Ensure that we have the proper number of arguments.
2496   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2497     return true;
2498 
2499   // Inspect the pointer argument of the atomic builtin.  This should always be
2500   // a pointer type, whose element is an integral scalar or pointer type.
2501   // Because it is a pointer type, we don't have to worry about any implicit
2502   // casts here.
2503   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2504   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2505   if (PointerArgRes.isInvalid())
2506     return true;
2507   PointerArg = PointerArgRes.get();
2508 
2509   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2510   if (!pointerType) {
2511     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2512         << PointerArg->getType() << PointerArg->getSourceRange();
2513     return true;
2514   }
2515 
2516   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2517   // task is to insert the appropriate casts into the AST. First work out just
2518   // what the appropriate type is.
2519   QualType ValType = pointerType->getPointeeType();
2520   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2521   if (IsLdrex)
2522     AddrType.addConst();
2523 
2524   // Issue a warning if the cast is dodgy.
2525   CastKind CastNeeded = CK_NoOp;
2526   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2527     CastNeeded = CK_BitCast;
2528     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2529         << PointerArg->getType() << Context.getPointerType(AddrType)
2530         << AA_Passing << PointerArg->getSourceRange();
2531   }
2532 
2533   // Finally, do the cast and replace the argument with the corrected version.
2534   AddrType = Context.getPointerType(AddrType);
2535   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2536   if (PointerArgRes.isInvalid())
2537     return true;
2538   PointerArg = PointerArgRes.get();
2539 
2540   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2541 
2542   // In general, we allow ints, floats and pointers to be loaded and stored.
2543   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2544       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2545     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2546         << PointerArg->getType() << PointerArg->getSourceRange();
2547     return true;
2548   }
2549 
2550   // But ARM doesn't have instructions to deal with 128-bit versions.
2551   if (Context.getTypeSize(ValType) > MaxWidth) {
2552     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2553     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2554         << PointerArg->getType() << PointerArg->getSourceRange();
2555     return true;
2556   }
2557 
2558   switch (ValType.getObjCLifetime()) {
2559   case Qualifiers::OCL_None:
2560   case Qualifiers::OCL_ExplicitNone:
2561     // okay
2562     break;
2563 
2564   case Qualifiers::OCL_Weak:
2565   case Qualifiers::OCL_Strong:
2566   case Qualifiers::OCL_Autoreleasing:
2567     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2568         << ValType << PointerArg->getSourceRange();
2569     return true;
2570   }
2571 
2572   if (IsLdrex) {
2573     TheCall->setType(ValType);
2574     return false;
2575   }
2576 
2577   // Initialize the argument to be stored.
2578   ExprResult ValArg = TheCall->getArg(0);
2579   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2580       Context, ValType, /*consume*/ false);
2581   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2582   if (ValArg.isInvalid())
2583     return true;
2584   TheCall->setArg(0, ValArg.get());
2585 
2586   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2587   // but the custom checker bypasses all default analysis.
2588   TheCall->setType(Context.IntTy);
2589   return false;
2590 }
2591 
2592 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2593                                        CallExpr *TheCall) {
2594   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2595       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2596       BuiltinID == ARM::BI__builtin_arm_strex ||
2597       BuiltinID == ARM::BI__builtin_arm_stlex) {
2598     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2599   }
2600 
2601   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2602     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2603       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2604   }
2605 
2606   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2607       BuiltinID == ARM::BI__builtin_arm_wsr64)
2608     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2609 
2610   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2611       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2612       BuiltinID == ARM::BI__builtin_arm_wsr ||
2613       BuiltinID == ARM::BI__builtin_arm_wsrp)
2614     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2615 
2616   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2617     return true;
2618   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2619     return true;
2620   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2621     return true;
2622 
2623   // For intrinsics which take an immediate value as part of the instruction,
2624   // range check them here.
2625   // FIXME: VFP Intrinsics should error if VFP not present.
2626   switch (BuiltinID) {
2627   default: return false;
2628   case ARM::BI__builtin_arm_ssat:
2629     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2630   case ARM::BI__builtin_arm_usat:
2631     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2632   case ARM::BI__builtin_arm_ssat16:
2633     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2634   case ARM::BI__builtin_arm_usat16:
2635     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2636   case ARM::BI__builtin_arm_vcvtr_f:
2637   case ARM::BI__builtin_arm_vcvtr_d:
2638     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2639   case ARM::BI__builtin_arm_dmb:
2640   case ARM::BI__builtin_arm_dsb:
2641   case ARM::BI__builtin_arm_isb:
2642   case ARM::BI__builtin_arm_dbg:
2643     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2644   case ARM::BI__builtin_arm_cdp:
2645   case ARM::BI__builtin_arm_cdp2:
2646   case ARM::BI__builtin_arm_mcr:
2647   case ARM::BI__builtin_arm_mcr2:
2648   case ARM::BI__builtin_arm_mrc:
2649   case ARM::BI__builtin_arm_mrc2:
2650   case ARM::BI__builtin_arm_mcrr:
2651   case ARM::BI__builtin_arm_mcrr2:
2652   case ARM::BI__builtin_arm_mrrc:
2653   case ARM::BI__builtin_arm_mrrc2:
2654   case ARM::BI__builtin_arm_ldc:
2655   case ARM::BI__builtin_arm_ldcl:
2656   case ARM::BI__builtin_arm_ldc2:
2657   case ARM::BI__builtin_arm_ldc2l:
2658   case ARM::BI__builtin_arm_stc:
2659   case ARM::BI__builtin_arm_stcl:
2660   case ARM::BI__builtin_arm_stc2:
2661   case ARM::BI__builtin_arm_stc2l:
2662     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2663            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2664                                         /*WantCDE*/ false);
2665   }
2666 }
2667 
2668 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2669                                            unsigned BuiltinID,
2670                                            CallExpr *TheCall) {
2671   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2672       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2673       BuiltinID == AArch64::BI__builtin_arm_strex ||
2674       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2675     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2676   }
2677 
2678   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2679     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2680       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2681       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2682       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2683   }
2684 
2685   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2686       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2687     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2688 
2689   // Memory Tagging Extensions (MTE) Intrinsics
2690   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2691       BuiltinID == AArch64::BI__builtin_arm_addg ||
2692       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2693       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2694       BuiltinID == AArch64::BI__builtin_arm_stg ||
2695       BuiltinID == AArch64::BI__builtin_arm_subp) {
2696     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2697   }
2698 
2699   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2700       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2701       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2702       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2703     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2704 
2705   // Only check the valid encoding range. Any constant in this range would be
2706   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2707   // an exception for incorrect registers. This matches MSVC behavior.
2708   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2709       BuiltinID == AArch64::BI_WriteStatusReg)
2710     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2711 
2712   if (BuiltinID == AArch64::BI__getReg)
2713     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2714 
2715   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2716     return true;
2717 
2718   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2719     return true;
2720 
2721   // For intrinsics which take an immediate value as part of the instruction,
2722   // range check them here.
2723   unsigned i = 0, l = 0, u = 0;
2724   switch (BuiltinID) {
2725   default: return false;
2726   case AArch64::BI__builtin_arm_dmb:
2727   case AArch64::BI__builtin_arm_dsb:
2728   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2729   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2730   }
2731 
2732   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2733 }
2734 
2735 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2736   if (Arg->getType()->getAsPlaceholderType())
2737     return false;
2738 
2739   // The first argument needs to be a record field access.
2740   // If it is an array element access, we delay decision
2741   // to BPF backend to check whether the access is a
2742   // field access or not.
2743   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2744           isa<MemberExpr>(Arg->IgnoreParens()) ||
2745           isa<ArraySubscriptExpr>(Arg->IgnoreParens()));
2746 }
2747 
2748 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2749                             QualType VectorTy, QualType EltTy) {
2750   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2751   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2752     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2753         << Call->getSourceRange() << VectorEltTy << EltTy;
2754     return false;
2755   }
2756   return true;
2757 }
2758 
2759 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2760   QualType ArgType = Arg->getType();
2761   if (ArgType->getAsPlaceholderType())
2762     return false;
2763 
2764   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2765   // format:
2766   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2767   //   2. <type> var;
2768   //      __builtin_preserve_type_info(var, flag);
2769   if (!isa<DeclRefExpr>(Arg->IgnoreParens()) &&
2770       !isa<UnaryOperator>(Arg->IgnoreParens()))
2771     return false;
2772 
2773   // Typedef type.
2774   if (ArgType->getAs<TypedefType>())
2775     return true;
2776 
2777   // Record type or Enum type.
2778   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2779   if (const auto *RT = Ty->getAs<RecordType>()) {
2780     if (!RT->getDecl()->getDeclName().isEmpty())
2781       return true;
2782   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2783     if (!ET->getDecl()->getDeclName().isEmpty())
2784       return true;
2785   }
2786 
2787   return false;
2788 }
2789 
2790 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2791   QualType ArgType = Arg->getType();
2792   if (ArgType->getAsPlaceholderType())
2793     return false;
2794 
2795   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2796   // format:
2797   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2798   //                                 flag);
2799   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2800   if (!UO)
2801     return false;
2802 
2803   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2804   if (!CE)
2805     return false;
2806   if (CE->getCastKind() != CK_IntegralToPointer &&
2807       CE->getCastKind() != CK_NullToPointer)
2808     return false;
2809 
2810   // The integer must be from an EnumConstantDecl.
2811   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2812   if (!DR)
2813     return false;
2814 
2815   const EnumConstantDecl *Enumerator =
2816       dyn_cast<EnumConstantDecl>(DR->getDecl());
2817   if (!Enumerator)
2818     return false;
2819 
2820   // The type must be EnumType.
2821   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2822   const auto *ET = Ty->getAs<EnumType>();
2823   if (!ET)
2824     return false;
2825 
2826   // The enum value must be supported.
2827   return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
2828 }
2829 
2830 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2831                                        CallExpr *TheCall) {
2832   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2833           BuiltinID == BPF::BI__builtin_btf_type_id ||
2834           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2835           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2836          "unexpected BPF builtin");
2837 
2838   if (checkArgCount(*this, TheCall, 2))
2839     return true;
2840 
2841   // The second argument needs to be a constant int
2842   Expr *Arg = TheCall->getArg(1);
2843   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2844   diag::kind kind;
2845   if (!Value) {
2846     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2847       kind = diag::err_preserve_field_info_not_const;
2848     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2849       kind = diag::err_btf_type_id_not_const;
2850     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2851       kind = diag::err_preserve_type_info_not_const;
2852     else
2853       kind = diag::err_preserve_enum_value_not_const;
2854     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2855     return true;
2856   }
2857 
2858   // The first argument
2859   Arg = TheCall->getArg(0);
2860   bool InvalidArg = false;
2861   bool ReturnUnsignedInt = true;
2862   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2863     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2864       InvalidArg = true;
2865       kind = diag::err_preserve_field_info_not_field;
2866     }
2867   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2868     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2869       InvalidArg = true;
2870       kind = diag::err_preserve_type_info_invalid;
2871     }
2872   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2873     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2874       InvalidArg = true;
2875       kind = diag::err_preserve_enum_value_invalid;
2876     }
2877     ReturnUnsignedInt = false;
2878   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2879     ReturnUnsignedInt = false;
2880   }
2881 
2882   if (InvalidArg) {
2883     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2884     return true;
2885   }
2886 
2887   if (ReturnUnsignedInt)
2888     TheCall->setType(Context.UnsignedIntTy);
2889   else
2890     TheCall->setType(Context.UnsignedLongTy);
2891   return false;
2892 }
2893 
2894 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2895   struct ArgInfo {
2896     uint8_t OpNum;
2897     bool IsSigned;
2898     uint8_t BitWidth;
2899     uint8_t Align;
2900   };
2901   struct BuiltinInfo {
2902     unsigned BuiltinID;
2903     ArgInfo Infos[2];
2904   };
2905 
2906   static BuiltinInfo Infos[] = {
2907     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2908     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2909     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2910     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2911     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2912     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2913     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2914     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2915     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2916     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2917     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2918 
2919     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2922     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2923     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2924     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2925     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2927     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2928     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2929     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2930 
2931     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2934     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2935     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2936     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2937     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2938     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2939     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2940     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2941     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2942     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2943     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2944     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2945     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2946     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2947     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2948     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2949     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2950     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2951     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2952     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2953     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2954     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2955     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2956     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2957     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2958     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2959     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2960     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2961     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2962     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2963     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2964     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2965     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2966     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2967     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2968     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2969     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2970     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2971     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2972     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2973     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2974     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2975     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2976     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2977     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2978     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2979     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2980     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2981     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2982     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2983                                                       {{ 1, false, 6,  0 }} },
2984     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2985     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2986     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2987     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2988     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2989     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2990     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2991                                                       {{ 1, false, 5,  0 }} },
2992     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2993     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2994     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2995     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2996     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2997     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2998                                                        { 2, false, 5,  0 }} },
2999     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
3000                                                        { 2, false, 6,  0 }} },
3001     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
3002                                                        { 3, false, 5,  0 }} },
3003     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
3004                                                        { 3, false, 6,  0 }} },
3005     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
3006     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
3007     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
3008     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
3009     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
3010     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
3011     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
3012     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
3013     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
3014     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
3015     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
3016     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
3017     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
3018     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
3019     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
3020     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
3021                                                       {{ 2, false, 4,  0 },
3022                                                        { 3, false, 5,  0 }} },
3023     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
3024                                                       {{ 2, false, 4,  0 },
3025                                                        { 3, false, 5,  0 }} },
3026     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
3027                                                       {{ 2, false, 4,  0 },
3028                                                        { 3, false, 5,  0 }} },
3029     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
3030                                                       {{ 2, false, 4,  0 },
3031                                                        { 3, false, 5,  0 }} },
3032     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
3033     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
3034     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
3035     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
3036     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
3037     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
3038     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
3039     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
3040     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
3041     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
3042     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
3043                                                        { 2, false, 5,  0 }} },
3044     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
3045                                                        { 2, false, 6,  0 }} },
3046     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
3047     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
3048     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
3049     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
3050     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
3051     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
3052     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
3053     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
3054     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
3055                                                       {{ 1, false, 4,  0 }} },
3056     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
3057     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
3058                                                       {{ 1, false, 4,  0 }} },
3059     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
3060     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
3061     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
3062     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
3063     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
3064     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
3065     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
3066     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
3067     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
3068     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
3069     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
3070     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
3071     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
3072     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
3073     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
3074     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
3075     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
3076     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
3077     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
3078     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
3079                                                       {{ 3, false, 1,  0 }} },
3080     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
3081     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
3082     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
3083     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
3084                                                       {{ 3, false, 1,  0 }} },
3085     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
3086     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
3087     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
3088     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
3089                                                       {{ 3, false, 1,  0 }} },
3090   };
3091 
3092   // Use a dynamically initialized static to sort the table exactly once on
3093   // first run.
3094   static const bool SortOnce =
3095       (llvm::sort(Infos,
3096                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
3097                    return LHS.BuiltinID < RHS.BuiltinID;
3098                  }),
3099        true);
3100   (void)SortOnce;
3101 
3102   const BuiltinInfo *F = llvm::partition_point(
3103       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
3104   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
3105     return false;
3106 
3107   bool Error = false;
3108 
3109   for (const ArgInfo &A : F->Infos) {
3110     // Ignore empty ArgInfo elements.
3111     if (A.BitWidth == 0)
3112       continue;
3113 
3114     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
3115     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
3116     if (!A.Align) {
3117       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3118     } else {
3119       unsigned M = 1 << A.Align;
3120       Min *= M;
3121       Max *= M;
3122       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3123       Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
3124     }
3125   }
3126   return Error;
3127 }
3128 
3129 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
3130                                            CallExpr *TheCall) {
3131   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3132 }
3133 
3134 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
3135                                         unsigned BuiltinID, CallExpr *TheCall) {
3136   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
3137          CheckMipsBuiltinArgument(BuiltinID, TheCall);
3138 }
3139 
3140 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
3141                                CallExpr *TheCall) {
3142 
3143   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3144       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3145     if (!TI.hasFeature("dsp"))
3146       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3147   }
3148 
3149   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3150       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3151     if (!TI.hasFeature("dspr2"))
3152       return Diag(TheCall->getBeginLoc(),
3153                   diag::err_mips_builtin_requires_dspr2);
3154   }
3155 
3156   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3157       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3158     if (!TI.hasFeature("msa"))
3159       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3160   }
3161 
3162   return false;
3163 }
3164 
3165 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3166 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3167 // ordering for DSP is unspecified. MSA is ordered by the data format used
3168 // by the underlying instruction i.e., df/m, df/n and then by size.
3169 //
3170 // FIXME: The size tests here should instead be tablegen'd along with the
3171 //        definitions from include/clang/Basic/BuiltinsMips.def.
3172 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3173 //        be too.
3174 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3175   unsigned i = 0, l = 0, u = 0, m = 0;
3176   switch (BuiltinID) {
3177   default: return false;
3178   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3179   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3180   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3181   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3182   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3183   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3184   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3185   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3186   // df/m field.
3187   // These intrinsics take an unsigned 3 bit immediate.
3188   case Mips::BI__builtin_msa_bclri_b:
3189   case Mips::BI__builtin_msa_bnegi_b:
3190   case Mips::BI__builtin_msa_bseti_b:
3191   case Mips::BI__builtin_msa_sat_s_b:
3192   case Mips::BI__builtin_msa_sat_u_b:
3193   case Mips::BI__builtin_msa_slli_b:
3194   case Mips::BI__builtin_msa_srai_b:
3195   case Mips::BI__builtin_msa_srari_b:
3196   case Mips::BI__builtin_msa_srli_b:
3197   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3198   case Mips::BI__builtin_msa_binsli_b:
3199   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3200   // These intrinsics take an unsigned 4 bit immediate.
3201   case Mips::BI__builtin_msa_bclri_h:
3202   case Mips::BI__builtin_msa_bnegi_h:
3203   case Mips::BI__builtin_msa_bseti_h:
3204   case Mips::BI__builtin_msa_sat_s_h:
3205   case Mips::BI__builtin_msa_sat_u_h:
3206   case Mips::BI__builtin_msa_slli_h:
3207   case Mips::BI__builtin_msa_srai_h:
3208   case Mips::BI__builtin_msa_srari_h:
3209   case Mips::BI__builtin_msa_srli_h:
3210   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3211   case Mips::BI__builtin_msa_binsli_h:
3212   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3213   // These intrinsics take an unsigned 5 bit immediate.
3214   // The first block of intrinsics actually have an unsigned 5 bit field,
3215   // not a df/n field.
3216   case Mips::BI__builtin_msa_cfcmsa:
3217   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3218   case Mips::BI__builtin_msa_clei_u_b:
3219   case Mips::BI__builtin_msa_clei_u_h:
3220   case Mips::BI__builtin_msa_clei_u_w:
3221   case Mips::BI__builtin_msa_clei_u_d:
3222   case Mips::BI__builtin_msa_clti_u_b:
3223   case Mips::BI__builtin_msa_clti_u_h:
3224   case Mips::BI__builtin_msa_clti_u_w:
3225   case Mips::BI__builtin_msa_clti_u_d:
3226   case Mips::BI__builtin_msa_maxi_u_b:
3227   case Mips::BI__builtin_msa_maxi_u_h:
3228   case Mips::BI__builtin_msa_maxi_u_w:
3229   case Mips::BI__builtin_msa_maxi_u_d:
3230   case Mips::BI__builtin_msa_mini_u_b:
3231   case Mips::BI__builtin_msa_mini_u_h:
3232   case Mips::BI__builtin_msa_mini_u_w:
3233   case Mips::BI__builtin_msa_mini_u_d:
3234   case Mips::BI__builtin_msa_addvi_b:
3235   case Mips::BI__builtin_msa_addvi_h:
3236   case Mips::BI__builtin_msa_addvi_w:
3237   case Mips::BI__builtin_msa_addvi_d:
3238   case Mips::BI__builtin_msa_bclri_w:
3239   case Mips::BI__builtin_msa_bnegi_w:
3240   case Mips::BI__builtin_msa_bseti_w:
3241   case Mips::BI__builtin_msa_sat_s_w:
3242   case Mips::BI__builtin_msa_sat_u_w:
3243   case Mips::BI__builtin_msa_slli_w:
3244   case Mips::BI__builtin_msa_srai_w:
3245   case Mips::BI__builtin_msa_srari_w:
3246   case Mips::BI__builtin_msa_srli_w:
3247   case Mips::BI__builtin_msa_srlri_w:
3248   case Mips::BI__builtin_msa_subvi_b:
3249   case Mips::BI__builtin_msa_subvi_h:
3250   case Mips::BI__builtin_msa_subvi_w:
3251   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3252   case Mips::BI__builtin_msa_binsli_w:
3253   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3254   // These intrinsics take an unsigned 6 bit immediate.
3255   case Mips::BI__builtin_msa_bclri_d:
3256   case Mips::BI__builtin_msa_bnegi_d:
3257   case Mips::BI__builtin_msa_bseti_d:
3258   case Mips::BI__builtin_msa_sat_s_d:
3259   case Mips::BI__builtin_msa_sat_u_d:
3260   case Mips::BI__builtin_msa_slli_d:
3261   case Mips::BI__builtin_msa_srai_d:
3262   case Mips::BI__builtin_msa_srari_d:
3263   case Mips::BI__builtin_msa_srli_d:
3264   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3265   case Mips::BI__builtin_msa_binsli_d:
3266   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3267   // These intrinsics take a signed 5 bit immediate.
3268   case Mips::BI__builtin_msa_ceqi_b:
3269   case Mips::BI__builtin_msa_ceqi_h:
3270   case Mips::BI__builtin_msa_ceqi_w:
3271   case Mips::BI__builtin_msa_ceqi_d:
3272   case Mips::BI__builtin_msa_clti_s_b:
3273   case Mips::BI__builtin_msa_clti_s_h:
3274   case Mips::BI__builtin_msa_clti_s_w:
3275   case Mips::BI__builtin_msa_clti_s_d:
3276   case Mips::BI__builtin_msa_clei_s_b:
3277   case Mips::BI__builtin_msa_clei_s_h:
3278   case Mips::BI__builtin_msa_clei_s_w:
3279   case Mips::BI__builtin_msa_clei_s_d:
3280   case Mips::BI__builtin_msa_maxi_s_b:
3281   case Mips::BI__builtin_msa_maxi_s_h:
3282   case Mips::BI__builtin_msa_maxi_s_w:
3283   case Mips::BI__builtin_msa_maxi_s_d:
3284   case Mips::BI__builtin_msa_mini_s_b:
3285   case Mips::BI__builtin_msa_mini_s_h:
3286   case Mips::BI__builtin_msa_mini_s_w:
3287   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3288   // These intrinsics take an unsigned 8 bit immediate.
3289   case Mips::BI__builtin_msa_andi_b:
3290   case Mips::BI__builtin_msa_nori_b:
3291   case Mips::BI__builtin_msa_ori_b:
3292   case Mips::BI__builtin_msa_shf_b:
3293   case Mips::BI__builtin_msa_shf_h:
3294   case Mips::BI__builtin_msa_shf_w:
3295   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3296   case Mips::BI__builtin_msa_bseli_b:
3297   case Mips::BI__builtin_msa_bmnzi_b:
3298   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3299   // df/n format
3300   // These intrinsics take an unsigned 4 bit immediate.
3301   case Mips::BI__builtin_msa_copy_s_b:
3302   case Mips::BI__builtin_msa_copy_u_b:
3303   case Mips::BI__builtin_msa_insve_b:
3304   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3305   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3306   // These intrinsics take an unsigned 3 bit immediate.
3307   case Mips::BI__builtin_msa_copy_s_h:
3308   case Mips::BI__builtin_msa_copy_u_h:
3309   case Mips::BI__builtin_msa_insve_h:
3310   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3311   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3312   // These intrinsics take an unsigned 2 bit immediate.
3313   case Mips::BI__builtin_msa_copy_s_w:
3314   case Mips::BI__builtin_msa_copy_u_w:
3315   case Mips::BI__builtin_msa_insve_w:
3316   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3317   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3318   // These intrinsics take an unsigned 1 bit immediate.
3319   case Mips::BI__builtin_msa_copy_s_d:
3320   case Mips::BI__builtin_msa_copy_u_d:
3321   case Mips::BI__builtin_msa_insve_d:
3322   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3323   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3324   // Memory offsets and immediate loads.
3325   // These intrinsics take a signed 10 bit immediate.
3326   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3327   case Mips::BI__builtin_msa_ldi_h:
3328   case Mips::BI__builtin_msa_ldi_w:
3329   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3330   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3331   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3332   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3333   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3334   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3335   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3336   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3337   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3338   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3339   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3340   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3341   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3342   }
3343 
3344   if (!m)
3345     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3346 
3347   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3348          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3349 }
3350 
3351 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3352 /// advancing the pointer over the consumed characters. The decoded type is
3353 /// returned. If the decoded type represents a constant integer with a
3354 /// constraint on its value then Mask is set to that value. The type descriptors
3355 /// used in Str are specific to PPC MMA builtins and are documented in the file
3356 /// defining the PPC builtins.
3357 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3358                                         unsigned &Mask) {
3359   bool RequireICE = false;
3360   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3361   switch (*Str++) {
3362   case 'V':
3363     return Context.getVectorType(Context.UnsignedCharTy, 16,
3364                                  VectorType::VectorKind::AltiVecVector);
3365   case 'i': {
3366     char *End;
3367     unsigned size = strtoul(Str, &End, 10);
3368     assert(End != Str && "Missing constant parameter constraint");
3369     Str = End;
3370     Mask = size;
3371     return Context.IntTy;
3372   }
3373   case 'W': {
3374     char *End;
3375     unsigned size = strtoul(Str, &End, 10);
3376     assert(End != Str && "Missing PowerPC MMA type size");
3377     Str = End;
3378     QualType Type;
3379     switch (size) {
3380   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3381     case size: Type = Context.Id##Ty; break;
3382   #include "clang/Basic/PPCTypes.def"
3383     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3384     }
3385     bool CheckVectorArgs = false;
3386     while (!CheckVectorArgs) {
3387       switch (*Str++) {
3388       case '*':
3389         Type = Context.getPointerType(Type);
3390         break;
3391       case 'C':
3392         Type = Type.withConst();
3393         break;
3394       default:
3395         CheckVectorArgs = true;
3396         --Str;
3397         break;
3398       }
3399     }
3400     return Type;
3401   }
3402   default:
3403     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3404   }
3405 }
3406 
3407 static bool isPPC_64Builtin(unsigned BuiltinID) {
3408   // These builtins only work on PPC 64bit targets.
3409   switch (BuiltinID) {
3410   case PPC::BI__builtin_divde:
3411   case PPC::BI__builtin_divdeu:
3412   case PPC::BI__builtin_bpermd:
3413   case PPC::BI__builtin_ppc_ldarx:
3414   case PPC::BI__builtin_ppc_stdcx:
3415   case PPC::BI__builtin_ppc_tdw:
3416   case PPC::BI__builtin_ppc_trapd:
3417   case PPC::BI__builtin_ppc_cmpeqb:
3418   case PPC::BI__builtin_ppc_setb:
3419   case PPC::BI__builtin_ppc_mulhd:
3420   case PPC::BI__builtin_ppc_mulhdu:
3421   case PPC::BI__builtin_ppc_maddhd:
3422   case PPC::BI__builtin_ppc_maddhdu:
3423   case PPC::BI__builtin_ppc_maddld:
3424   case PPC::BI__builtin_ppc_load8r:
3425   case PPC::BI__builtin_ppc_store8r:
3426   case PPC::BI__builtin_ppc_insert_exp:
3427   case PPC::BI__builtin_ppc_extract_sig:
3428   case PPC::BI__builtin_ppc_addex:
3429   case PPC::BI__builtin_darn:
3430   case PPC::BI__builtin_darn_raw:
3431   case PPC::BI__builtin_ppc_compare_and_swaplp:
3432   case PPC::BI__builtin_ppc_fetch_and_addlp:
3433   case PPC::BI__builtin_ppc_fetch_and_andlp:
3434   case PPC::BI__builtin_ppc_fetch_and_orlp:
3435   case PPC::BI__builtin_ppc_fetch_and_swaplp:
3436     return true;
3437   }
3438   return false;
3439 }
3440 
3441 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3442                              StringRef FeatureToCheck, unsigned DiagID,
3443                              StringRef DiagArg = "") {
3444   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3445     return false;
3446 
3447   if (DiagArg.empty())
3448     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3449   else
3450     S.Diag(TheCall->getBeginLoc(), DiagID)
3451         << DiagArg << TheCall->getSourceRange();
3452 
3453   return true;
3454 }
3455 
3456 /// Returns true if the argument consists of one contiguous run of 1s with any
3457 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3458 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3459 /// since all 1s are not contiguous.
3460 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3461   llvm::APSInt Result;
3462   // We can't check the value of a dependent argument.
3463   Expr *Arg = TheCall->getArg(ArgNum);
3464   if (Arg->isTypeDependent() || Arg->isValueDependent())
3465     return false;
3466 
3467   // Check constant-ness first.
3468   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3469     return true;
3470 
3471   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3472   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3473     return false;
3474 
3475   return Diag(TheCall->getBeginLoc(),
3476               diag::err_argument_not_contiguous_bit_field)
3477          << ArgNum << Arg->getSourceRange();
3478 }
3479 
3480 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3481                                        CallExpr *TheCall) {
3482   unsigned i = 0, l = 0, u = 0;
3483   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3484   llvm::APSInt Result;
3485 
3486   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3487     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3488            << TheCall->getSourceRange();
3489 
3490   switch (BuiltinID) {
3491   default: return false;
3492   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3493   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3494     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3495            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3496   case PPC::BI__builtin_altivec_dss:
3497     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3498   case PPC::BI__builtin_tbegin:
3499   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3500   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3501   case PPC::BI__builtin_tabortwc:
3502   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3503   case PPC::BI__builtin_tabortwci:
3504   case PPC::BI__builtin_tabortdci:
3505     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3506            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3507   // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05',
3508   // __builtin_(un)pack_longdouble are available only if long double uses IBM
3509   // extended double representation.
3510   case PPC::BI__builtin_unpack_longdouble:
3511     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1))
3512       return true;
3513     LLVM_FALLTHROUGH;
3514   case PPC::BI__builtin_pack_longdouble:
3515     if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble())
3516       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi)
3517              << "ibmlongdouble";
3518     return false;
3519   case PPC::BI__builtin_altivec_dst:
3520   case PPC::BI__builtin_altivec_dstt:
3521   case PPC::BI__builtin_altivec_dstst:
3522   case PPC::BI__builtin_altivec_dststt:
3523     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3524   case PPC::BI__builtin_vsx_xxpermdi:
3525   case PPC::BI__builtin_vsx_xxsldwi:
3526     return SemaBuiltinVSX(TheCall);
3527   case PPC::BI__builtin_divwe:
3528   case PPC::BI__builtin_divweu:
3529   case PPC::BI__builtin_divde:
3530   case PPC::BI__builtin_divdeu:
3531     return SemaFeatureCheck(*this, TheCall, "extdiv",
3532                             diag::err_ppc_builtin_only_on_arch, "7");
3533   case PPC::BI__builtin_bpermd:
3534     return SemaFeatureCheck(*this, TheCall, "bpermd",
3535                             diag::err_ppc_builtin_only_on_arch, "7");
3536   case PPC::BI__builtin_unpack_vector_int128:
3537     return SemaFeatureCheck(*this, TheCall, "vsx",
3538                             diag::err_ppc_builtin_only_on_arch, "7") ||
3539            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3540   case PPC::BI__builtin_pack_vector_int128:
3541     return SemaFeatureCheck(*this, TheCall, "vsx",
3542                             diag::err_ppc_builtin_only_on_arch, "7");
3543   case PPC::BI__builtin_altivec_vgnb:
3544      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3545   case PPC::BI__builtin_altivec_vec_replace_elt:
3546   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3547     QualType VecTy = TheCall->getArg(0)->getType();
3548     QualType EltTy = TheCall->getArg(1)->getType();
3549     unsigned Width = Context.getIntWidth(EltTy);
3550     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3551            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3552   }
3553   case PPC::BI__builtin_vsx_xxeval:
3554      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3555   case PPC::BI__builtin_altivec_vsldbi:
3556      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3557   case PPC::BI__builtin_altivec_vsrdbi:
3558      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3559   case PPC::BI__builtin_vsx_xxpermx:
3560      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3561   case PPC::BI__builtin_ppc_tw:
3562   case PPC::BI__builtin_ppc_tdw:
3563     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3564   case PPC::BI__builtin_ppc_cmpeqb:
3565   case PPC::BI__builtin_ppc_setb:
3566   case PPC::BI__builtin_ppc_maddhd:
3567   case PPC::BI__builtin_ppc_maddhdu:
3568   case PPC::BI__builtin_ppc_maddld:
3569     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3570                             diag::err_ppc_builtin_only_on_arch, "9");
3571   case PPC::BI__builtin_ppc_cmprb:
3572     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3573                             diag::err_ppc_builtin_only_on_arch, "9") ||
3574            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3575   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3576   // be a constant that represents a contiguous bit field.
3577   case PPC::BI__builtin_ppc_rlwnm:
3578     return SemaValueIsRunOfOnes(TheCall, 2);
3579   case PPC::BI__builtin_ppc_rlwimi:
3580   case PPC::BI__builtin_ppc_rldimi:
3581     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3582            SemaValueIsRunOfOnes(TheCall, 3);
3583   case PPC::BI__builtin_ppc_extract_exp:
3584   case PPC::BI__builtin_ppc_extract_sig:
3585   case PPC::BI__builtin_ppc_insert_exp:
3586     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3587                             diag::err_ppc_builtin_only_on_arch, "9");
3588   case PPC::BI__builtin_ppc_addex: {
3589     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3590                          diag::err_ppc_builtin_only_on_arch, "9") ||
3591         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
3592       return true;
3593     // Output warning for reserved values 1 to 3.
3594     int ArgValue =
3595         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
3596     if (ArgValue != 0)
3597       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
3598           << ArgValue;
3599     return false;
3600   }
3601   case PPC::BI__builtin_ppc_mtfsb0:
3602   case PPC::BI__builtin_ppc_mtfsb1:
3603     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3604   case PPC::BI__builtin_ppc_mtfsf:
3605     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3606   case PPC::BI__builtin_ppc_mtfsfi:
3607     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3608            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3609   case PPC::BI__builtin_ppc_alignx:
3610     return SemaBuiltinConstantArgPower2(TheCall, 0);
3611   case PPC::BI__builtin_ppc_rdlam:
3612     return SemaValueIsRunOfOnes(TheCall, 2);
3613   case PPC::BI__builtin_ppc_icbt:
3614   case PPC::BI__builtin_ppc_sthcx:
3615   case PPC::BI__builtin_ppc_stbcx:
3616   case PPC::BI__builtin_ppc_lharx:
3617   case PPC::BI__builtin_ppc_lbarx:
3618     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3619                             diag::err_ppc_builtin_only_on_arch, "8");
3620   case PPC::BI__builtin_vsx_ldrmb:
3621   case PPC::BI__builtin_vsx_strmb:
3622     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3623                             diag::err_ppc_builtin_only_on_arch, "8") ||
3624            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3625   case PPC::BI__builtin_altivec_vcntmbb:
3626   case PPC::BI__builtin_altivec_vcntmbh:
3627   case PPC::BI__builtin_altivec_vcntmbw:
3628   case PPC::BI__builtin_altivec_vcntmbd:
3629     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3630   case PPC::BI__builtin_darn:
3631   case PPC::BI__builtin_darn_raw:
3632   case PPC::BI__builtin_darn_32:
3633     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3634                             diag::err_ppc_builtin_only_on_arch, "9");
3635   case PPC::BI__builtin_vsx_xxgenpcvbm:
3636   case PPC::BI__builtin_vsx_xxgenpcvhm:
3637   case PPC::BI__builtin_vsx_xxgenpcvwm:
3638   case PPC::BI__builtin_vsx_xxgenpcvdm:
3639     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3640   case PPC::BI__builtin_ppc_compare_exp_uo:
3641   case PPC::BI__builtin_ppc_compare_exp_lt:
3642   case PPC::BI__builtin_ppc_compare_exp_gt:
3643   case PPC::BI__builtin_ppc_compare_exp_eq:
3644     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3645                             diag::err_ppc_builtin_only_on_arch, "9") ||
3646            SemaFeatureCheck(*this, TheCall, "vsx",
3647                             diag::err_ppc_builtin_requires_vsx);
3648   case PPC::BI__builtin_ppc_test_data_class: {
3649     // Check if the first argument of the __builtin_ppc_test_data_class call is
3650     // valid. The argument must be either a 'float' or a 'double'.
3651     QualType ArgType = TheCall->getArg(0)->getType();
3652     if (ArgType != QualType(Context.FloatTy) &&
3653         ArgType != QualType(Context.DoubleTy))
3654       return Diag(TheCall->getBeginLoc(),
3655                   diag::err_ppc_invalid_test_data_class_type);
3656     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3657                             diag::err_ppc_builtin_only_on_arch, "9") ||
3658            SemaFeatureCheck(*this, TheCall, "vsx",
3659                             diag::err_ppc_builtin_requires_vsx) ||
3660            SemaBuiltinConstantArgRange(TheCall, 1, 0, 127);
3661   }
3662   case PPC::BI__builtin_ppc_load8r:
3663   case PPC::BI__builtin_ppc_store8r:
3664     return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions",
3665                             diag::err_ppc_builtin_only_on_arch, "7");
3666 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc)                                 \
3667   case PPC::BI__builtin_##Name:                                                \
3668     return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types);
3669 #include "clang/Basic/BuiltinsPPC.def"
3670   }
3671   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3672 }
3673 
3674 // Check if the given type is a non-pointer PPC MMA type. This function is used
3675 // in Sema to prevent invalid uses of restricted PPC MMA types.
3676 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3677   if (Type->isPointerType() || Type->isArrayType())
3678     return false;
3679 
3680   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3681 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3682   if (false
3683 #include "clang/Basic/PPCTypes.def"
3684      ) {
3685     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3686     return true;
3687   }
3688   return false;
3689 }
3690 
3691 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3692                                           CallExpr *TheCall) {
3693   // position of memory order and scope arguments in the builtin
3694   unsigned OrderIndex, ScopeIndex;
3695   switch (BuiltinID) {
3696   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3697   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3698   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3699   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3700     OrderIndex = 2;
3701     ScopeIndex = 3;
3702     break;
3703   case AMDGPU::BI__builtin_amdgcn_fence:
3704     OrderIndex = 0;
3705     ScopeIndex = 1;
3706     break;
3707   default:
3708     return false;
3709   }
3710 
3711   ExprResult Arg = TheCall->getArg(OrderIndex);
3712   auto ArgExpr = Arg.get();
3713   Expr::EvalResult ArgResult;
3714 
3715   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3716     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3717            << ArgExpr->getType();
3718   auto Ord = ArgResult.Val.getInt().getZExtValue();
3719 
3720   // Check validity of memory ordering as per C11 / C++11's memody model.
3721   // Only fence needs check. Atomic dec/inc allow all memory orders.
3722   if (!llvm::isValidAtomicOrderingCABI(Ord))
3723     return Diag(ArgExpr->getBeginLoc(),
3724                 diag::warn_atomic_op_has_invalid_memory_order)
3725            << ArgExpr->getSourceRange();
3726   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3727   case llvm::AtomicOrderingCABI::relaxed:
3728   case llvm::AtomicOrderingCABI::consume:
3729     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3730       return Diag(ArgExpr->getBeginLoc(),
3731                   diag::warn_atomic_op_has_invalid_memory_order)
3732              << ArgExpr->getSourceRange();
3733     break;
3734   case llvm::AtomicOrderingCABI::acquire:
3735   case llvm::AtomicOrderingCABI::release:
3736   case llvm::AtomicOrderingCABI::acq_rel:
3737   case llvm::AtomicOrderingCABI::seq_cst:
3738     break;
3739   }
3740 
3741   Arg = TheCall->getArg(ScopeIndex);
3742   ArgExpr = Arg.get();
3743   Expr::EvalResult ArgResult1;
3744   // Check that sync scope is a constant literal
3745   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3746     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3747            << ArgExpr->getType();
3748 
3749   return false;
3750 }
3751 
3752 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3753   llvm::APSInt Result;
3754 
3755   // We can't check the value of a dependent argument.
3756   Expr *Arg = TheCall->getArg(ArgNum);
3757   if (Arg->isTypeDependent() || Arg->isValueDependent())
3758     return false;
3759 
3760   // Check constant-ness first.
3761   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3762     return true;
3763 
3764   int64_t Val = Result.getSExtValue();
3765   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3766     return false;
3767 
3768   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3769          << Arg->getSourceRange();
3770 }
3771 
3772 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3773                                          unsigned BuiltinID,
3774                                          CallExpr *TheCall) {
3775   // CodeGenFunction can also detect this, but this gives a better error
3776   // message.
3777   bool FeatureMissing = false;
3778   SmallVector<StringRef> ReqFeatures;
3779   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3780   Features.split(ReqFeatures, ',');
3781 
3782   // Check if each required feature is included
3783   for (StringRef F : ReqFeatures) {
3784     if (TI.hasFeature(F))
3785       continue;
3786 
3787     // If the feature is 64bit, alter the string so it will print better in
3788     // the diagnostic.
3789     if (F == "64bit")
3790       F = "RV64";
3791 
3792     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3793     F.consume_front("experimental-");
3794     std::string FeatureStr = F.str();
3795     FeatureStr[0] = std::toupper(FeatureStr[0]);
3796 
3797     // Error message
3798     FeatureMissing = true;
3799     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3800         << TheCall->getSourceRange() << StringRef(FeatureStr);
3801   }
3802 
3803   if (FeatureMissing)
3804     return true;
3805 
3806   switch (BuiltinID) {
3807   case RISCVVector::BI__builtin_rvv_vsetvli:
3808     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3809            CheckRISCVLMUL(TheCall, 2);
3810   case RISCVVector::BI__builtin_rvv_vsetvlimax:
3811     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3812            CheckRISCVLMUL(TheCall, 1);
3813   }
3814 
3815   return false;
3816 }
3817 
3818 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3819                                            CallExpr *TheCall) {
3820   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3821     Expr *Arg = TheCall->getArg(0);
3822     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3823       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3824         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3825                << Arg->getSourceRange();
3826   }
3827 
3828   // For intrinsics which take an immediate value as part of the instruction,
3829   // range check them here.
3830   unsigned i = 0, l = 0, u = 0;
3831   switch (BuiltinID) {
3832   default: return false;
3833   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3834   case SystemZ::BI__builtin_s390_verimb:
3835   case SystemZ::BI__builtin_s390_verimh:
3836   case SystemZ::BI__builtin_s390_verimf:
3837   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3838   case SystemZ::BI__builtin_s390_vfaeb:
3839   case SystemZ::BI__builtin_s390_vfaeh:
3840   case SystemZ::BI__builtin_s390_vfaef:
3841   case SystemZ::BI__builtin_s390_vfaebs:
3842   case SystemZ::BI__builtin_s390_vfaehs:
3843   case SystemZ::BI__builtin_s390_vfaefs:
3844   case SystemZ::BI__builtin_s390_vfaezb:
3845   case SystemZ::BI__builtin_s390_vfaezh:
3846   case SystemZ::BI__builtin_s390_vfaezf:
3847   case SystemZ::BI__builtin_s390_vfaezbs:
3848   case SystemZ::BI__builtin_s390_vfaezhs:
3849   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3850   case SystemZ::BI__builtin_s390_vfisb:
3851   case SystemZ::BI__builtin_s390_vfidb:
3852     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3853            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3854   case SystemZ::BI__builtin_s390_vftcisb:
3855   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3856   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3857   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3858   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3859   case SystemZ::BI__builtin_s390_vstrcb:
3860   case SystemZ::BI__builtin_s390_vstrch:
3861   case SystemZ::BI__builtin_s390_vstrcf:
3862   case SystemZ::BI__builtin_s390_vstrczb:
3863   case SystemZ::BI__builtin_s390_vstrczh:
3864   case SystemZ::BI__builtin_s390_vstrczf:
3865   case SystemZ::BI__builtin_s390_vstrcbs:
3866   case SystemZ::BI__builtin_s390_vstrchs:
3867   case SystemZ::BI__builtin_s390_vstrcfs:
3868   case SystemZ::BI__builtin_s390_vstrczbs:
3869   case SystemZ::BI__builtin_s390_vstrczhs:
3870   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3871   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3872   case SystemZ::BI__builtin_s390_vfminsb:
3873   case SystemZ::BI__builtin_s390_vfmaxsb:
3874   case SystemZ::BI__builtin_s390_vfmindb:
3875   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3876   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3877   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3878   case SystemZ::BI__builtin_s390_vclfnhs:
3879   case SystemZ::BI__builtin_s390_vclfnls:
3880   case SystemZ::BI__builtin_s390_vcfn:
3881   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
3882   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
3883   }
3884   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3885 }
3886 
3887 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3888 /// This checks that the target supports __builtin_cpu_supports and
3889 /// that the string argument is constant and valid.
3890 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3891                                    CallExpr *TheCall) {
3892   Expr *Arg = TheCall->getArg(0);
3893 
3894   // Check if the argument is a string literal.
3895   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3896     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3897            << Arg->getSourceRange();
3898 
3899   // Check the contents of the string.
3900   StringRef Feature =
3901       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3902   if (!TI.validateCpuSupports(Feature))
3903     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3904            << Arg->getSourceRange();
3905   return false;
3906 }
3907 
3908 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3909 /// This checks that the target supports __builtin_cpu_is and
3910 /// that the string argument is constant and valid.
3911 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3912   Expr *Arg = TheCall->getArg(0);
3913 
3914   // Check if the argument is a string literal.
3915   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3916     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3917            << Arg->getSourceRange();
3918 
3919   // Check the contents of the string.
3920   StringRef Feature =
3921       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3922   if (!TI.validateCpuIs(Feature))
3923     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3924            << Arg->getSourceRange();
3925   return false;
3926 }
3927 
3928 // Check if the rounding mode is legal.
3929 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3930   // Indicates if this instruction has rounding control or just SAE.
3931   bool HasRC = false;
3932 
3933   unsigned ArgNum = 0;
3934   switch (BuiltinID) {
3935   default:
3936     return false;
3937   case X86::BI__builtin_ia32_vcvttsd2si32:
3938   case X86::BI__builtin_ia32_vcvttsd2si64:
3939   case X86::BI__builtin_ia32_vcvttsd2usi32:
3940   case X86::BI__builtin_ia32_vcvttsd2usi64:
3941   case X86::BI__builtin_ia32_vcvttss2si32:
3942   case X86::BI__builtin_ia32_vcvttss2si64:
3943   case X86::BI__builtin_ia32_vcvttss2usi32:
3944   case X86::BI__builtin_ia32_vcvttss2usi64:
3945   case X86::BI__builtin_ia32_vcvttsh2si32:
3946   case X86::BI__builtin_ia32_vcvttsh2si64:
3947   case X86::BI__builtin_ia32_vcvttsh2usi32:
3948   case X86::BI__builtin_ia32_vcvttsh2usi64:
3949     ArgNum = 1;
3950     break;
3951   case X86::BI__builtin_ia32_maxpd512:
3952   case X86::BI__builtin_ia32_maxps512:
3953   case X86::BI__builtin_ia32_minpd512:
3954   case X86::BI__builtin_ia32_minps512:
3955   case X86::BI__builtin_ia32_maxph512:
3956   case X86::BI__builtin_ia32_minph512:
3957     ArgNum = 2;
3958     break;
3959   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
3960   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
3961   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3962   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3963   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3964   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3965   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3966   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3967   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3968   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3969   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3970   case X86::BI__builtin_ia32_vcvttph2w512_mask:
3971   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
3972   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
3973   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
3974   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
3975   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
3976   case X86::BI__builtin_ia32_exp2pd_mask:
3977   case X86::BI__builtin_ia32_exp2ps_mask:
3978   case X86::BI__builtin_ia32_getexppd512_mask:
3979   case X86::BI__builtin_ia32_getexpps512_mask:
3980   case X86::BI__builtin_ia32_getexpph512_mask:
3981   case X86::BI__builtin_ia32_rcp28pd_mask:
3982   case X86::BI__builtin_ia32_rcp28ps_mask:
3983   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3984   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3985   case X86::BI__builtin_ia32_vcomisd:
3986   case X86::BI__builtin_ia32_vcomiss:
3987   case X86::BI__builtin_ia32_vcomish:
3988   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3989     ArgNum = 3;
3990     break;
3991   case X86::BI__builtin_ia32_cmppd512_mask:
3992   case X86::BI__builtin_ia32_cmpps512_mask:
3993   case X86::BI__builtin_ia32_cmpsd_mask:
3994   case X86::BI__builtin_ia32_cmpss_mask:
3995   case X86::BI__builtin_ia32_cmpsh_mask:
3996   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
3997   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
3998   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3999   case X86::BI__builtin_ia32_getexpsd128_round_mask:
4000   case X86::BI__builtin_ia32_getexpss128_round_mask:
4001   case X86::BI__builtin_ia32_getexpsh128_round_mask:
4002   case X86::BI__builtin_ia32_getmantpd512_mask:
4003   case X86::BI__builtin_ia32_getmantps512_mask:
4004   case X86::BI__builtin_ia32_getmantph512_mask:
4005   case X86::BI__builtin_ia32_maxsd_round_mask:
4006   case X86::BI__builtin_ia32_maxss_round_mask:
4007   case X86::BI__builtin_ia32_maxsh_round_mask:
4008   case X86::BI__builtin_ia32_minsd_round_mask:
4009   case X86::BI__builtin_ia32_minss_round_mask:
4010   case X86::BI__builtin_ia32_minsh_round_mask:
4011   case X86::BI__builtin_ia32_rcp28sd_round_mask:
4012   case X86::BI__builtin_ia32_rcp28ss_round_mask:
4013   case X86::BI__builtin_ia32_reducepd512_mask:
4014   case X86::BI__builtin_ia32_reduceps512_mask:
4015   case X86::BI__builtin_ia32_reduceph512_mask:
4016   case X86::BI__builtin_ia32_rndscalepd_mask:
4017   case X86::BI__builtin_ia32_rndscaleps_mask:
4018   case X86::BI__builtin_ia32_rndscaleph_mask:
4019   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
4020   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
4021     ArgNum = 4;
4022     break;
4023   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4024   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4025   case X86::BI__builtin_ia32_fixupimmps512_mask:
4026   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4027   case X86::BI__builtin_ia32_fixupimmsd_mask:
4028   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4029   case X86::BI__builtin_ia32_fixupimmss_mask:
4030   case X86::BI__builtin_ia32_fixupimmss_maskz:
4031   case X86::BI__builtin_ia32_getmantsd_round_mask:
4032   case X86::BI__builtin_ia32_getmantss_round_mask:
4033   case X86::BI__builtin_ia32_getmantsh_round_mask:
4034   case X86::BI__builtin_ia32_rangepd512_mask:
4035   case X86::BI__builtin_ia32_rangeps512_mask:
4036   case X86::BI__builtin_ia32_rangesd128_round_mask:
4037   case X86::BI__builtin_ia32_rangess128_round_mask:
4038   case X86::BI__builtin_ia32_reducesd_mask:
4039   case X86::BI__builtin_ia32_reducess_mask:
4040   case X86::BI__builtin_ia32_reducesh_mask:
4041   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4042   case X86::BI__builtin_ia32_rndscaless_round_mask:
4043   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4044     ArgNum = 5;
4045     break;
4046   case X86::BI__builtin_ia32_vcvtsd2si64:
4047   case X86::BI__builtin_ia32_vcvtsd2si32:
4048   case X86::BI__builtin_ia32_vcvtsd2usi32:
4049   case X86::BI__builtin_ia32_vcvtsd2usi64:
4050   case X86::BI__builtin_ia32_vcvtss2si32:
4051   case X86::BI__builtin_ia32_vcvtss2si64:
4052   case X86::BI__builtin_ia32_vcvtss2usi32:
4053   case X86::BI__builtin_ia32_vcvtss2usi64:
4054   case X86::BI__builtin_ia32_vcvtsh2si32:
4055   case X86::BI__builtin_ia32_vcvtsh2si64:
4056   case X86::BI__builtin_ia32_vcvtsh2usi32:
4057   case X86::BI__builtin_ia32_vcvtsh2usi64:
4058   case X86::BI__builtin_ia32_sqrtpd512:
4059   case X86::BI__builtin_ia32_sqrtps512:
4060   case X86::BI__builtin_ia32_sqrtph512:
4061     ArgNum = 1;
4062     HasRC = true;
4063     break;
4064   case X86::BI__builtin_ia32_addph512:
4065   case X86::BI__builtin_ia32_divph512:
4066   case X86::BI__builtin_ia32_mulph512:
4067   case X86::BI__builtin_ia32_subph512:
4068   case X86::BI__builtin_ia32_addpd512:
4069   case X86::BI__builtin_ia32_addps512:
4070   case X86::BI__builtin_ia32_divpd512:
4071   case X86::BI__builtin_ia32_divps512:
4072   case X86::BI__builtin_ia32_mulpd512:
4073   case X86::BI__builtin_ia32_mulps512:
4074   case X86::BI__builtin_ia32_subpd512:
4075   case X86::BI__builtin_ia32_subps512:
4076   case X86::BI__builtin_ia32_cvtsi2sd64:
4077   case X86::BI__builtin_ia32_cvtsi2ss32:
4078   case X86::BI__builtin_ia32_cvtsi2ss64:
4079   case X86::BI__builtin_ia32_cvtusi2sd64:
4080   case X86::BI__builtin_ia32_cvtusi2ss32:
4081   case X86::BI__builtin_ia32_cvtusi2ss64:
4082   case X86::BI__builtin_ia32_vcvtusi2sh:
4083   case X86::BI__builtin_ia32_vcvtusi642sh:
4084   case X86::BI__builtin_ia32_vcvtsi2sh:
4085   case X86::BI__builtin_ia32_vcvtsi642sh:
4086     ArgNum = 2;
4087     HasRC = true;
4088     break;
4089   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
4090   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
4091   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
4092   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
4093   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
4094   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
4095   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
4096   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
4097   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
4098   case X86::BI__builtin_ia32_cvtps2dq512_mask:
4099   case X86::BI__builtin_ia32_cvtps2qq512_mask:
4100   case X86::BI__builtin_ia32_cvtps2udq512_mask:
4101   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
4102   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
4103   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
4104   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
4105   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
4106   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
4107   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
4108   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
4109   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
4110   case X86::BI__builtin_ia32_vcvtph2w512_mask:
4111   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
4112   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
4113   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
4114   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
4115   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
4116   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
4117   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
4118     ArgNum = 3;
4119     HasRC = true;
4120     break;
4121   case X86::BI__builtin_ia32_addsh_round_mask:
4122   case X86::BI__builtin_ia32_addss_round_mask:
4123   case X86::BI__builtin_ia32_addsd_round_mask:
4124   case X86::BI__builtin_ia32_divsh_round_mask:
4125   case X86::BI__builtin_ia32_divss_round_mask:
4126   case X86::BI__builtin_ia32_divsd_round_mask:
4127   case X86::BI__builtin_ia32_mulsh_round_mask:
4128   case X86::BI__builtin_ia32_mulss_round_mask:
4129   case X86::BI__builtin_ia32_mulsd_round_mask:
4130   case X86::BI__builtin_ia32_subsh_round_mask:
4131   case X86::BI__builtin_ia32_subss_round_mask:
4132   case X86::BI__builtin_ia32_subsd_round_mask:
4133   case X86::BI__builtin_ia32_scalefph512_mask:
4134   case X86::BI__builtin_ia32_scalefpd512_mask:
4135   case X86::BI__builtin_ia32_scalefps512_mask:
4136   case X86::BI__builtin_ia32_scalefsd_round_mask:
4137   case X86::BI__builtin_ia32_scalefss_round_mask:
4138   case X86::BI__builtin_ia32_scalefsh_round_mask:
4139   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4140   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4141   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4142   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4143   case X86::BI__builtin_ia32_sqrtss_round_mask:
4144   case X86::BI__builtin_ia32_sqrtsh_round_mask:
4145   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4146   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4147   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4148   case X86::BI__builtin_ia32_vfmaddss3_mask:
4149   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4150   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4151   case X86::BI__builtin_ia32_vfmaddsh3_mask:
4152   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4153   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4154   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4155   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4156   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4157   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4158   case X86::BI__builtin_ia32_vfmaddps512_mask:
4159   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4160   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4161   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4162   case X86::BI__builtin_ia32_vfmaddph512_mask:
4163   case X86::BI__builtin_ia32_vfmaddph512_maskz:
4164   case X86::BI__builtin_ia32_vfmaddph512_mask3:
4165   case X86::BI__builtin_ia32_vfmsubph512_mask3:
4166   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4167   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4168   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4169   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4170   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4171   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4172   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4173   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4174   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4175   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4176   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4177   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4178   case X86::BI__builtin_ia32_vfmaddcsh_mask:
4179   case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
4180   case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
4181   case X86::BI__builtin_ia32_vfmaddcph512_mask:
4182   case X86::BI__builtin_ia32_vfmaddcph512_maskz:
4183   case X86::BI__builtin_ia32_vfmaddcph512_mask3:
4184   case X86::BI__builtin_ia32_vfcmaddcsh_mask:
4185   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
4186   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
4187   case X86::BI__builtin_ia32_vfcmaddcph512_mask:
4188   case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
4189   case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
4190   case X86::BI__builtin_ia32_vfmulcsh_mask:
4191   case X86::BI__builtin_ia32_vfmulcph512_mask:
4192   case X86::BI__builtin_ia32_vfcmulcsh_mask:
4193   case X86::BI__builtin_ia32_vfcmulcph512_mask:
4194     ArgNum = 4;
4195     HasRC = true;
4196     break;
4197   }
4198 
4199   llvm::APSInt Result;
4200 
4201   // We can't check the value of a dependent argument.
4202   Expr *Arg = TheCall->getArg(ArgNum);
4203   if (Arg->isTypeDependent() || Arg->isValueDependent())
4204     return false;
4205 
4206   // Check constant-ness first.
4207   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4208     return true;
4209 
4210   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4211   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4212   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4213   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4214   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4215       Result == 8/*ROUND_NO_EXC*/ ||
4216       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4217       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4218     return false;
4219 
4220   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4221          << Arg->getSourceRange();
4222 }
4223 
4224 // Check if the gather/scatter scale is legal.
4225 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4226                                              CallExpr *TheCall) {
4227   unsigned ArgNum = 0;
4228   switch (BuiltinID) {
4229   default:
4230     return false;
4231   case X86::BI__builtin_ia32_gatherpfdpd:
4232   case X86::BI__builtin_ia32_gatherpfdps:
4233   case X86::BI__builtin_ia32_gatherpfqpd:
4234   case X86::BI__builtin_ia32_gatherpfqps:
4235   case X86::BI__builtin_ia32_scatterpfdpd:
4236   case X86::BI__builtin_ia32_scatterpfdps:
4237   case X86::BI__builtin_ia32_scatterpfqpd:
4238   case X86::BI__builtin_ia32_scatterpfqps:
4239     ArgNum = 3;
4240     break;
4241   case X86::BI__builtin_ia32_gatherd_pd:
4242   case X86::BI__builtin_ia32_gatherd_pd256:
4243   case X86::BI__builtin_ia32_gatherq_pd:
4244   case X86::BI__builtin_ia32_gatherq_pd256:
4245   case X86::BI__builtin_ia32_gatherd_ps:
4246   case X86::BI__builtin_ia32_gatherd_ps256:
4247   case X86::BI__builtin_ia32_gatherq_ps:
4248   case X86::BI__builtin_ia32_gatherq_ps256:
4249   case X86::BI__builtin_ia32_gatherd_q:
4250   case X86::BI__builtin_ia32_gatherd_q256:
4251   case X86::BI__builtin_ia32_gatherq_q:
4252   case X86::BI__builtin_ia32_gatherq_q256:
4253   case X86::BI__builtin_ia32_gatherd_d:
4254   case X86::BI__builtin_ia32_gatherd_d256:
4255   case X86::BI__builtin_ia32_gatherq_d:
4256   case X86::BI__builtin_ia32_gatherq_d256:
4257   case X86::BI__builtin_ia32_gather3div2df:
4258   case X86::BI__builtin_ia32_gather3div2di:
4259   case X86::BI__builtin_ia32_gather3div4df:
4260   case X86::BI__builtin_ia32_gather3div4di:
4261   case X86::BI__builtin_ia32_gather3div4sf:
4262   case X86::BI__builtin_ia32_gather3div4si:
4263   case X86::BI__builtin_ia32_gather3div8sf:
4264   case X86::BI__builtin_ia32_gather3div8si:
4265   case X86::BI__builtin_ia32_gather3siv2df:
4266   case X86::BI__builtin_ia32_gather3siv2di:
4267   case X86::BI__builtin_ia32_gather3siv4df:
4268   case X86::BI__builtin_ia32_gather3siv4di:
4269   case X86::BI__builtin_ia32_gather3siv4sf:
4270   case X86::BI__builtin_ia32_gather3siv4si:
4271   case X86::BI__builtin_ia32_gather3siv8sf:
4272   case X86::BI__builtin_ia32_gather3siv8si:
4273   case X86::BI__builtin_ia32_gathersiv8df:
4274   case X86::BI__builtin_ia32_gathersiv16sf:
4275   case X86::BI__builtin_ia32_gatherdiv8df:
4276   case X86::BI__builtin_ia32_gatherdiv16sf:
4277   case X86::BI__builtin_ia32_gathersiv8di:
4278   case X86::BI__builtin_ia32_gathersiv16si:
4279   case X86::BI__builtin_ia32_gatherdiv8di:
4280   case X86::BI__builtin_ia32_gatherdiv16si:
4281   case X86::BI__builtin_ia32_scatterdiv2df:
4282   case X86::BI__builtin_ia32_scatterdiv2di:
4283   case X86::BI__builtin_ia32_scatterdiv4df:
4284   case X86::BI__builtin_ia32_scatterdiv4di:
4285   case X86::BI__builtin_ia32_scatterdiv4sf:
4286   case X86::BI__builtin_ia32_scatterdiv4si:
4287   case X86::BI__builtin_ia32_scatterdiv8sf:
4288   case X86::BI__builtin_ia32_scatterdiv8si:
4289   case X86::BI__builtin_ia32_scattersiv2df:
4290   case X86::BI__builtin_ia32_scattersiv2di:
4291   case X86::BI__builtin_ia32_scattersiv4df:
4292   case X86::BI__builtin_ia32_scattersiv4di:
4293   case X86::BI__builtin_ia32_scattersiv4sf:
4294   case X86::BI__builtin_ia32_scattersiv4si:
4295   case X86::BI__builtin_ia32_scattersiv8sf:
4296   case X86::BI__builtin_ia32_scattersiv8si:
4297   case X86::BI__builtin_ia32_scattersiv8df:
4298   case X86::BI__builtin_ia32_scattersiv16sf:
4299   case X86::BI__builtin_ia32_scatterdiv8df:
4300   case X86::BI__builtin_ia32_scatterdiv16sf:
4301   case X86::BI__builtin_ia32_scattersiv8di:
4302   case X86::BI__builtin_ia32_scattersiv16si:
4303   case X86::BI__builtin_ia32_scatterdiv8di:
4304   case X86::BI__builtin_ia32_scatterdiv16si:
4305     ArgNum = 4;
4306     break;
4307   }
4308 
4309   llvm::APSInt Result;
4310 
4311   // We can't check the value of a dependent argument.
4312   Expr *Arg = TheCall->getArg(ArgNum);
4313   if (Arg->isTypeDependent() || Arg->isValueDependent())
4314     return false;
4315 
4316   // Check constant-ness first.
4317   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4318     return true;
4319 
4320   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4321     return false;
4322 
4323   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4324          << Arg->getSourceRange();
4325 }
4326 
4327 enum { TileRegLow = 0, TileRegHigh = 7 };
4328 
4329 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4330                                              ArrayRef<int> ArgNums) {
4331   for (int ArgNum : ArgNums) {
4332     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4333       return true;
4334   }
4335   return false;
4336 }
4337 
4338 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4339                                         ArrayRef<int> ArgNums) {
4340   // Because the max number of tile register is TileRegHigh + 1, so here we use
4341   // each bit to represent the usage of them in bitset.
4342   std::bitset<TileRegHigh + 1> ArgValues;
4343   for (int ArgNum : ArgNums) {
4344     Expr *Arg = TheCall->getArg(ArgNum);
4345     if (Arg->isTypeDependent() || Arg->isValueDependent())
4346       continue;
4347 
4348     llvm::APSInt Result;
4349     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4350       return true;
4351     int ArgExtValue = Result.getExtValue();
4352     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4353            "Incorrect tile register num.");
4354     if (ArgValues.test(ArgExtValue))
4355       return Diag(TheCall->getBeginLoc(),
4356                   diag::err_x86_builtin_tile_arg_duplicate)
4357              << TheCall->getArg(ArgNum)->getSourceRange();
4358     ArgValues.set(ArgExtValue);
4359   }
4360   return false;
4361 }
4362 
4363 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4364                                                 ArrayRef<int> ArgNums) {
4365   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4366          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4367 }
4368 
4369 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4370   switch (BuiltinID) {
4371   default:
4372     return false;
4373   case X86::BI__builtin_ia32_tileloadd64:
4374   case X86::BI__builtin_ia32_tileloaddt164:
4375   case X86::BI__builtin_ia32_tilestored64:
4376   case X86::BI__builtin_ia32_tilezero:
4377     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4378   case X86::BI__builtin_ia32_tdpbssd:
4379   case X86::BI__builtin_ia32_tdpbsud:
4380   case X86::BI__builtin_ia32_tdpbusd:
4381   case X86::BI__builtin_ia32_tdpbuud:
4382   case X86::BI__builtin_ia32_tdpbf16ps:
4383     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4384   }
4385 }
4386 static bool isX86_32Builtin(unsigned BuiltinID) {
4387   // These builtins only work on x86-32 targets.
4388   switch (BuiltinID) {
4389   case X86::BI__builtin_ia32_readeflags_u32:
4390   case X86::BI__builtin_ia32_writeeflags_u32:
4391     return true;
4392   }
4393 
4394   return false;
4395 }
4396 
4397 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4398                                        CallExpr *TheCall) {
4399   if (BuiltinID == X86::BI__builtin_cpu_supports)
4400     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4401 
4402   if (BuiltinID == X86::BI__builtin_cpu_is)
4403     return SemaBuiltinCpuIs(*this, TI, TheCall);
4404 
4405   // Check for 32-bit only builtins on a 64-bit target.
4406   const llvm::Triple &TT = TI.getTriple();
4407   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4408     return Diag(TheCall->getCallee()->getBeginLoc(),
4409                 diag::err_32_bit_builtin_64_bit_tgt);
4410 
4411   // If the intrinsic has rounding or SAE make sure its valid.
4412   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4413     return true;
4414 
4415   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4416   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4417     return true;
4418 
4419   // If the intrinsic has a tile arguments, make sure they are valid.
4420   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4421     return true;
4422 
4423   // For intrinsics which take an immediate value as part of the instruction,
4424   // range check them here.
4425   int i = 0, l = 0, u = 0;
4426   switch (BuiltinID) {
4427   default:
4428     return false;
4429   case X86::BI__builtin_ia32_vec_ext_v2si:
4430   case X86::BI__builtin_ia32_vec_ext_v2di:
4431   case X86::BI__builtin_ia32_vextractf128_pd256:
4432   case X86::BI__builtin_ia32_vextractf128_ps256:
4433   case X86::BI__builtin_ia32_vextractf128_si256:
4434   case X86::BI__builtin_ia32_extract128i256:
4435   case X86::BI__builtin_ia32_extractf64x4_mask:
4436   case X86::BI__builtin_ia32_extracti64x4_mask:
4437   case X86::BI__builtin_ia32_extractf32x8_mask:
4438   case X86::BI__builtin_ia32_extracti32x8_mask:
4439   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4440   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4441   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4442   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4443     i = 1; l = 0; u = 1;
4444     break;
4445   case X86::BI__builtin_ia32_vec_set_v2di:
4446   case X86::BI__builtin_ia32_vinsertf128_pd256:
4447   case X86::BI__builtin_ia32_vinsertf128_ps256:
4448   case X86::BI__builtin_ia32_vinsertf128_si256:
4449   case X86::BI__builtin_ia32_insert128i256:
4450   case X86::BI__builtin_ia32_insertf32x8:
4451   case X86::BI__builtin_ia32_inserti32x8:
4452   case X86::BI__builtin_ia32_insertf64x4:
4453   case X86::BI__builtin_ia32_inserti64x4:
4454   case X86::BI__builtin_ia32_insertf64x2_256:
4455   case X86::BI__builtin_ia32_inserti64x2_256:
4456   case X86::BI__builtin_ia32_insertf32x4_256:
4457   case X86::BI__builtin_ia32_inserti32x4_256:
4458     i = 2; l = 0; u = 1;
4459     break;
4460   case X86::BI__builtin_ia32_vpermilpd:
4461   case X86::BI__builtin_ia32_vec_ext_v4hi:
4462   case X86::BI__builtin_ia32_vec_ext_v4si:
4463   case X86::BI__builtin_ia32_vec_ext_v4sf:
4464   case X86::BI__builtin_ia32_vec_ext_v4di:
4465   case X86::BI__builtin_ia32_extractf32x4_mask:
4466   case X86::BI__builtin_ia32_extracti32x4_mask:
4467   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4468   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4469     i = 1; l = 0; u = 3;
4470     break;
4471   case X86::BI_mm_prefetch:
4472   case X86::BI__builtin_ia32_vec_ext_v8hi:
4473   case X86::BI__builtin_ia32_vec_ext_v8si:
4474     i = 1; l = 0; u = 7;
4475     break;
4476   case X86::BI__builtin_ia32_sha1rnds4:
4477   case X86::BI__builtin_ia32_blendpd:
4478   case X86::BI__builtin_ia32_shufpd:
4479   case X86::BI__builtin_ia32_vec_set_v4hi:
4480   case X86::BI__builtin_ia32_vec_set_v4si:
4481   case X86::BI__builtin_ia32_vec_set_v4di:
4482   case X86::BI__builtin_ia32_shuf_f32x4_256:
4483   case X86::BI__builtin_ia32_shuf_f64x2_256:
4484   case X86::BI__builtin_ia32_shuf_i32x4_256:
4485   case X86::BI__builtin_ia32_shuf_i64x2_256:
4486   case X86::BI__builtin_ia32_insertf64x2_512:
4487   case X86::BI__builtin_ia32_inserti64x2_512:
4488   case X86::BI__builtin_ia32_insertf32x4:
4489   case X86::BI__builtin_ia32_inserti32x4:
4490     i = 2; l = 0; u = 3;
4491     break;
4492   case X86::BI__builtin_ia32_vpermil2pd:
4493   case X86::BI__builtin_ia32_vpermil2pd256:
4494   case X86::BI__builtin_ia32_vpermil2ps:
4495   case X86::BI__builtin_ia32_vpermil2ps256:
4496     i = 3; l = 0; u = 3;
4497     break;
4498   case X86::BI__builtin_ia32_cmpb128_mask:
4499   case X86::BI__builtin_ia32_cmpw128_mask:
4500   case X86::BI__builtin_ia32_cmpd128_mask:
4501   case X86::BI__builtin_ia32_cmpq128_mask:
4502   case X86::BI__builtin_ia32_cmpb256_mask:
4503   case X86::BI__builtin_ia32_cmpw256_mask:
4504   case X86::BI__builtin_ia32_cmpd256_mask:
4505   case X86::BI__builtin_ia32_cmpq256_mask:
4506   case X86::BI__builtin_ia32_cmpb512_mask:
4507   case X86::BI__builtin_ia32_cmpw512_mask:
4508   case X86::BI__builtin_ia32_cmpd512_mask:
4509   case X86::BI__builtin_ia32_cmpq512_mask:
4510   case X86::BI__builtin_ia32_ucmpb128_mask:
4511   case X86::BI__builtin_ia32_ucmpw128_mask:
4512   case X86::BI__builtin_ia32_ucmpd128_mask:
4513   case X86::BI__builtin_ia32_ucmpq128_mask:
4514   case X86::BI__builtin_ia32_ucmpb256_mask:
4515   case X86::BI__builtin_ia32_ucmpw256_mask:
4516   case X86::BI__builtin_ia32_ucmpd256_mask:
4517   case X86::BI__builtin_ia32_ucmpq256_mask:
4518   case X86::BI__builtin_ia32_ucmpb512_mask:
4519   case X86::BI__builtin_ia32_ucmpw512_mask:
4520   case X86::BI__builtin_ia32_ucmpd512_mask:
4521   case X86::BI__builtin_ia32_ucmpq512_mask:
4522   case X86::BI__builtin_ia32_vpcomub:
4523   case X86::BI__builtin_ia32_vpcomuw:
4524   case X86::BI__builtin_ia32_vpcomud:
4525   case X86::BI__builtin_ia32_vpcomuq:
4526   case X86::BI__builtin_ia32_vpcomb:
4527   case X86::BI__builtin_ia32_vpcomw:
4528   case X86::BI__builtin_ia32_vpcomd:
4529   case X86::BI__builtin_ia32_vpcomq:
4530   case X86::BI__builtin_ia32_vec_set_v8hi:
4531   case X86::BI__builtin_ia32_vec_set_v8si:
4532     i = 2; l = 0; u = 7;
4533     break;
4534   case X86::BI__builtin_ia32_vpermilpd256:
4535   case X86::BI__builtin_ia32_roundps:
4536   case X86::BI__builtin_ia32_roundpd:
4537   case X86::BI__builtin_ia32_roundps256:
4538   case X86::BI__builtin_ia32_roundpd256:
4539   case X86::BI__builtin_ia32_getmantpd128_mask:
4540   case X86::BI__builtin_ia32_getmantpd256_mask:
4541   case X86::BI__builtin_ia32_getmantps128_mask:
4542   case X86::BI__builtin_ia32_getmantps256_mask:
4543   case X86::BI__builtin_ia32_getmantpd512_mask:
4544   case X86::BI__builtin_ia32_getmantps512_mask:
4545   case X86::BI__builtin_ia32_getmantph128_mask:
4546   case X86::BI__builtin_ia32_getmantph256_mask:
4547   case X86::BI__builtin_ia32_getmantph512_mask:
4548   case X86::BI__builtin_ia32_vec_ext_v16qi:
4549   case X86::BI__builtin_ia32_vec_ext_v16hi:
4550     i = 1; l = 0; u = 15;
4551     break;
4552   case X86::BI__builtin_ia32_pblendd128:
4553   case X86::BI__builtin_ia32_blendps:
4554   case X86::BI__builtin_ia32_blendpd256:
4555   case X86::BI__builtin_ia32_shufpd256:
4556   case X86::BI__builtin_ia32_roundss:
4557   case X86::BI__builtin_ia32_roundsd:
4558   case X86::BI__builtin_ia32_rangepd128_mask:
4559   case X86::BI__builtin_ia32_rangepd256_mask:
4560   case X86::BI__builtin_ia32_rangepd512_mask:
4561   case X86::BI__builtin_ia32_rangeps128_mask:
4562   case X86::BI__builtin_ia32_rangeps256_mask:
4563   case X86::BI__builtin_ia32_rangeps512_mask:
4564   case X86::BI__builtin_ia32_getmantsd_round_mask:
4565   case X86::BI__builtin_ia32_getmantss_round_mask:
4566   case X86::BI__builtin_ia32_getmantsh_round_mask:
4567   case X86::BI__builtin_ia32_vec_set_v16qi:
4568   case X86::BI__builtin_ia32_vec_set_v16hi:
4569     i = 2; l = 0; u = 15;
4570     break;
4571   case X86::BI__builtin_ia32_vec_ext_v32qi:
4572     i = 1; l = 0; u = 31;
4573     break;
4574   case X86::BI__builtin_ia32_cmpps:
4575   case X86::BI__builtin_ia32_cmpss:
4576   case X86::BI__builtin_ia32_cmppd:
4577   case X86::BI__builtin_ia32_cmpsd:
4578   case X86::BI__builtin_ia32_cmpps256:
4579   case X86::BI__builtin_ia32_cmppd256:
4580   case X86::BI__builtin_ia32_cmpps128_mask:
4581   case X86::BI__builtin_ia32_cmppd128_mask:
4582   case X86::BI__builtin_ia32_cmpps256_mask:
4583   case X86::BI__builtin_ia32_cmppd256_mask:
4584   case X86::BI__builtin_ia32_cmpps512_mask:
4585   case X86::BI__builtin_ia32_cmppd512_mask:
4586   case X86::BI__builtin_ia32_cmpsd_mask:
4587   case X86::BI__builtin_ia32_cmpss_mask:
4588   case X86::BI__builtin_ia32_vec_set_v32qi:
4589     i = 2; l = 0; u = 31;
4590     break;
4591   case X86::BI__builtin_ia32_permdf256:
4592   case X86::BI__builtin_ia32_permdi256:
4593   case X86::BI__builtin_ia32_permdf512:
4594   case X86::BI__builtin_ia32_permdi512:
4595   case X86::BI__builtin_ia32_vpermilps:
4596   case X86::BI__builtin_ia32_vpermilps256:
4597   case X86::BI__builtin_ia32_vpermilpd512:
4598   case X86::BI__builtin_ia32_vpermilps512:
4599   case X86::BI__builtin_ia32_pshufd:
4600   case X86::BI__builtin_ia32_pshufd256:
4601   case X86::BI__builtin_ia32_pshufd512:
4602   case X86::BI__builtin_ia32_pshufhw:
4603   case X86::BI__builtin_ia32_pshufhw256:
4604   case X86::BI__builtin_ia32_pshufhw512:
4605   case X86::BI__builtin_ia32_pshuflw:
4606   case X86::BI__builtin_ia32_pshuflw256:
4607   case X86::BI__builtin_ia32_pshuflw512:
4608   case X86::BI__builtin_ia32_vcvtps2ph:
4609   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4610   case X86::BI__builtin_ia32_vcvtps2ph256:
4611   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4612   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4613   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4614   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4615   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4616   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4617   case X86::BI__builtin_ia32_rndscaleps_mask:
4618   case X86::BI__builtin_ia32_rndscalepd_mask:
4619   case X86::BI__builtin_ia32_rndscaleph_mask:
4620   case X86::BI__builtin_ia32_reducepd128_mask:
4621   case X86::BI__builtin_ia32_reducepd256_mask:
4622   case X86::BI__builtin_ia32_reducepd512_mask:
4623   case X86::BI__builtin_ia32_reduceps128_mask:
4624   case X86::BI__builtin_ia32_reduceps256_mask:
4625   case X86::BI__builtin_ia32_reduceps512_mask:
4626   case X86::BI__builtin_ia32_reduceph128_mask:
4627   case X86::BI__builtin_ia32_reduceph256_mask:
4628   case X86::BI__builtin_ia32_reduceph512_mask:
4629   case X86::BI__builtin_ia32_prold512:
4630   case X86::BI__builtin_ia32_prolq512:
4631   case X86::BI__builtin_ia32_prold128:
4632   case X86::BI__builtin_ia32_prold256:
4633   case X86::BI__builtin_ia32_prolq128:
4634   case X86::BI__builtin_ia32_prolq256:
4635   case X86::BI__builtin_ia32_prord512:
4636   case X86::BI__builtin_ia32_prorq512:
4637   case X86::BI__builtin_ia32_prord128:
4638   case X86::BI__builtin_ia32_prord256:
4639   case X86::BI__builtin_ia32_prorq128:
4640   case X86::BI__builtin_ia32_prorq256:
4641   case X86::BI__builtin_ia32_fpclasspd128_mask:
4642   case X86::BI__builtin_ia32_fpclasspd256_mask:
4643   case X86::BI__builtin_ia32_fpclassps128_mask:
4644   case X86::BI__builtin_ia32_fpclassps256_mask:
4645   case X86::BI__builtin_ia32_fpclassps512_mask:
4646   case X86::BI__builtin_ia32_fpclasspd512_mask:
4647   case X86::BI__builtin_ia32_fpclassph128_mask:
4648   case X86::BI__builtin_ia32_fpclassph256_mask:
4649   case X86::BI__builtin_ia32_fpclassph512_mask:
4650   case X86::BI__builtin_ia32_fpclasssd_mask:
4651   case X86::BI__builtin_ia32_fpclassss_mask:
4652   case X86::BI__builtin_ia32_fpclasssh_mask:
4653   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4654   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4655   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4656   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4657   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4658   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4659   case X86::BI__builtin_ia32_kshiftliqi:
4660   case X86::BI__builtin_ia32_kshiftlihi:
4661   case X86::BI__builtin_ia32_kshiftlisi:
4662   case X86::BI__builtin_ia32_kshiftlidi:
4663   case X86::BI__builtin_ia32_kshiftriqi:
4664   case X86::BI__builtin_ia32_kshiftrihi:
4665   case X86::BI__builtin_ia32_kshiftrisi:
4666   case X86::BI__builtin_ia32_kshiftridi:
4667     i = 1; l = 0; u = 255;
4668     break;
4669   case X86::BI__builtin_ia32_vperm2f128_pd256:
4670   case X86::BI__builtin_ia32_vperm2f128_ps256:
4671   case X86::BI__builtin_ia32_vperm2f128_si256:
4672   case X86::BI__builtin_ia32_permti256:
4673   case X86::BI__builtin_ia32_pblendw128:
4674   case X86::BI__builtin_ia32_pblendw256:
4675   case X86::BI__builtin_ia32_blendps256:
4676   case X86::BI__builtin_ia32_pblendd256:
4677   case X86::BI__builtin_ia32_palignr128:
4678   case X86::BI__builtin_ia32_palignr256:
4679   case X86::BI__builtin_ia32_palignr512:
4680   case X86::BI__builtin_ia32_alignq512:
4681   case X86::BI__builtin_ia32_alignd512:
4682   case X86::BI__builtin_ia32_alignd128:
4683   case X86::BI__builtin_ia32_alignd256:
4684   case X86::BI__builtin_ia32_alignq128:
4685   case X86::BI__builtin_ia32_alignq256:
4686   case X86::BI__builtin_ia32_vcomisd:
4687   case X86::BI__builtin_ia32_vcomiss:
4688   case X86::BI__builtin_ia32_shuf_f32x4:
4689   case X86::BI__builtin_ia32_shuf_f64x2:
4690   case X86::BI__builtin_ia32_shuf_i32x4:
4691   case X86::BI__builtin_ia32_shuf_i64x2:
4692   case X86::BI__builtin_ia32_shufpd512:
4693   case X86::BI__builtin_ia32_shufps:
4694   case X86::BI__builtin_ia32_shufps256:
4695   case X86::BI__builtin_ia32_shufps512:
4696   case X86::BI__builtin_ia32_dbpsadbw128:
4697   case X86::BI__builtin_ia32_dbpsadbw256:
4698   case X86::BI__builtin_ia32_dbpsadbw512:
4699   case X86::BI__builtin_ia32_vpshldd128:
4700   case X86::BI__builtin_ia32_vpshldd256:
4701   case X86::BI__builtin_ia32_vpshldd512:
4702   case X86::BI__builtin_ia32_vpshldq128:
4703   case X86::BI__builtin_ia32_vpshldq256:
4704   case X86::BI__builtin_ia32_vpshldq512:
4705   case X86::BI__builtin_ia32_vpshldw128:
4706   case X86::BI__builtin_ia32_vpshldw256:
4707   case X86::BI__builtin_ia32_vpshldw512:
4708   case X86::BI__builtin_ia32_vpshrdd128:
4709   case X86::BI__builtin_ia32_vpshrdd256:
4710   case X86::BI__builtin_ia32_vpshrdd512:
4711   case X86::BI__builtin_ia32_vpshrdq128:
4712   case X86::BI__builtin_ia32_vpshrdq256:
4713   case X86::BI__builtin_ia32_vpshrdq512:
4714   case X86::BI__builtin_ia32_vpshrdw128:
4715   case X86::BI__builtin_ia32_vpshrdw256:
4716   case X86::BI__builtin_ia32_vpshrdw512:
4717     i = 2; l = 0; u = 255;
4718     break;
4719   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4720   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4721   case X86::BI__builtin_ia32_fixupimmps512_mask:
4722   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4723   case X86::BI__builtin_ia32_fixupimmsd_mask:
4724   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4725   case X86::BI__builtin_ia32_fixupimmss_mask:
4726   case X86::BI__builtin_ia32_fixupimmss_maskz:
4727   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4728   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4729   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4730   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4731   case X86::BI__builtin_ia32_fixupimmps128_mask:
4732   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4733   case X86::BI__builtin_ia32_fixupimmps256_mask:
4734   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4735   case X86::BI__builtin_ia32_pternlogd512_mask:
4736   case X86::BI__builtin_ia32_pternlogd512_maskz:
4737   case X86::BI__builtin_ia32_pternlogq512_mask:
4738   case X86::BI__builtin_ia32_pternlogq512_maskz:
4739   case X86::BI__builtin_ia32_pternlogd128_mask:
4740   case X86::BI__builtin_ia32_pternlogd128_maskz:
4741   case X86::BI__builtin_ia32_pternlogd256_mask:
4742   case X86::BI__builtin_ia32_pternlogd256_maskz:
4743   case X86::BI__builtin_ia32_pternlogq128_mask:
4744   case X86::BI__builtin_ia32_pternlogq128_maskz:
4745   case X86::BI__builtin_ia32_pternlogq256_mask:
4746   case X86::BI__builtin_ia32_pternlogq256_maskz:
4747     i = 3; l = 0; u = 255;
4748     break;
4749   case X86::BI__builtin_ia32_gatherpfdpd:
4750   case X86::BI__builtin_ia32_gatherpfdps:
4751   case X86::BI__builtin_ia32_gatherpfqpd:
4752   case X86::BI__builtin_ia32_gatherpfqps:
4753   case X86::BI__builtin_ia32_scatterpfdpd:
4754   case X86::BI__builtin_ia32_scatterpfdps:
4755   case X86::BI__builtin_ia32_scatterpfqpd:
4756   case X86::BI__builtin_ia32_scatterpfqps:
4757     i = 4; l = 2; u = 3;
4758     break;
4759   case X86::BI__builtin_ia32_reducesd_mask:
4760   case X86::BI__builtin_ia32_reducess_mask:
4761   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4762   case X86::BI__builtin_ia32_rndscaless_round_mask:
4763   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4764   case X86::BI__builtin_ia32_reducesh_mask:
4765     i = 4; l = 0; u = 255;
4766     break;
4767   }
4768 
4769   // Note that we don't force a hard error on the range check here, allowing
4770   // template-generated or macro-generated dead code to potentially have out-of-
4771   // range values. These need to code generate, but don't need to necessarily
4772   // make any sense. We use a warning that defaults to an error.
4773   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4774 }
4775 
4776 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4777 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4778 /// Returns true when the format fits the function and the FormatStringInfo has
4779 /// been populated.
4780 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4781                                FormatStringInfo *FSI) {
4782   FSI->HasVAListArg = Format->getFirstArg() == 0;
4783   FSI->FormatIdx = Format->getFormatIdx() - 1;
4784   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4785 
4786   // The way the format attribute works in GCC, the implicit this argument
4787   // of member functions is counted. However, it doesn't appear in our own
4788   // lists, so decrement format_idx in that case.
4789   if (IsCXXMember) {
4790     if(FSI->FormatIdx == 0)
4791       return false;
4792     --FSI->FormatIdx;
4793     if (FSI->FirstDataArg != 0)
4794       --FSI->FirstDataArg;
4795   }
4796   return true;
4797 }
4798 
4799 /// Checks if a the given expression evaluates to null.
4800 ///
4801 /// Returns true if the value evaluates to null.
4802 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4803   // If the expression has non-null type, it doesn't evaluate to null.
4804   if (auto nullability
4805         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4806     if (*nullability == NullabilityKind::NonNull)
4807       return false;
4808   }
4809 
4810   // As a special case, transparent unions initialized with zero are
4811   // considered null for the purposes of the nonnull attribute.
4812   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4813     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4814       if (const CompoundLiteralExpr *CLE =
4815           dyn_cast<CompoundLiteralExpr>(Expr))
4816         if (const InitListExpr *ILE =
4817             dyn_cast<InitListExpr>(CLE->getInitializer()))
4818           Expr = ILE->getInit(0);
4819   }
4820 
4821   bool Result;
4822   return (!Expr->isValueDependent() &&
4823           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4824           !Result);
4825 }
4826 
4827 static void CheckNonNullArgument(Sema &S,
4828                                  const Expr *ArgExpr,
4829                                  SourceLocation CallSiteLoc) {
4830   if (CheckNonNullExpr(S, ArgExpr))
4831     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4832                           S.PDiag(diag::warn_null_arg)
4833                               << ArgExpr->getSourceRange());
4834 }
4835 
4836 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4837   FormatStringInfo FSI;
4838   if ((GetFormatStringType(Format) == FST_NSString) &&
4839       getFormatStringInfo(Format, false, &FSI)) {
4840     Idx = FSI.FormatIdx;
4841     return true;
4842   }
4843   return false;
4844 }
4845 
4846 /// Diagnose use of %s directive in an NSString which is being passed
4847 /// as formatting string to formatting method.
4848 static void
4849 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4850                                         const NamedDecl *FDecl,
4851                                         Expr **Args,
4852                                         unsigned NumArgs) {
4853   unsigned Idx = 0;
4854   bool Format = false;
4855   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4856   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4857     Idx = 2;
4858     Format = true;
4859   }
4860   else
4861     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4862       if (S.GetFormatNSStringIdx(I, Idx)) {
4863         Format = true;
4864         break;
4865       }
4866     }
4867   if (!Format || NumArgs <= Idx)
4868     return;
4869   const Expr *FormatExpr = Args[Idx];
4870   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4871     FormatExpr = CSCE->getSubExpr();
4872   const StringLiteral *FormatString;
4873   if (const ObjCStringLiteral *OSL =
4874       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4875     FormatString = OSL->getString();
4876   else
4877     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4878   if (!FormatString)
4879     return;
4880   if (S.FormatStringHasSArg(FormatString)) {
4881     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4882       << "%s" << 1 << 1;
4883     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4884       << FDecl->getDeclName();
4885   }
4886 }
4887 
4888 /// Determine whether the given type has a non-null nullability annotation.
4889 static bool isNonNullType(ASTContext &ctx, QualType type) {
4890   if (auto nullability = type->getNullability(ctx))
4891     return *nullability == NullabilityKind::NonNull;
4892 
4893   return false;
4894 }
4895 
4896 static void CheckNonNullArguments(Sema &S,
4897                                   const NamedDecl *FDecl,
4898                                   const FunctionProtoType *Proto,
4899                                   ArrayRef<const Expr *> Args,
4900                                   SourceLocation CallSiteLoc) {
4901   assert((FDecl || Proto) && "Need a function declaration or prototype");
4902 
4903   // Already checked by by constant evaluator.
4904   if (S.isConstantEvaluated())
4905     return;
4906   // Check the attributes attached to the method/function itself.
4907   llvm::SmallBitVector NonNullArgs;
4908   if (FDecl) {
4909     // Handle the nonnull attribute on the function/method declaration itself.
4910     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4911       if (!NonNull->args_size()) {
4912         // Easy case: all pointer arguments are nonnull.
4913         for (const auto *Arg : Args)
4914           if (S.isValidPointerAttrType(Arg->getType()))
4915             CheckNonNullArgument(S, Arg, CallSiteLoc);
4916         return;
4917       }
4918 
4919       for (const ParamIdx &Idx : NonNull->args()) {
4920         unsigned IdxAST = Idx.getASTIndex();
4921         if (IdxAST >= Args.size())
4922           continue;
4923         if (NonNullArgs.empty())
4924           NonNullArgs.resize(Args.size());
4925         NonNullArgs.set(IdxAST);
4926       }
4927     }
4928   }
4929 
4930   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4931     // Handle the nonnull attribute on the parameters of the
4932     // function/method.
4933     ArrayRef<ParmVarDecl*> parms;
4934     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4935       parms = FD->parameters();
4936     else
4937       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4938 
4939     unsigned ParamIndex = 0;
4940     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4941          I != E; ++I, ++ParamIndex) {
4942       const ParmVarDecl *PVD = *I;
4943       if (PVD->hasAttr<NonNullAttr>() ||
4944           isNonNullType(S.Context, PVD->getType())) {
4945         if (NonNullArgs.empty())
4946           NonNullArgs.resize(Args.size());
4947 
4948         NonNullArgs.set(ParamIndex);
4949       }
4950     }
4951   } else {
4952     // If we have a non-function, non-method declaration but no
4953     // function prototype, try to dig out the function prototype.
4954     if (!Proto) {
4955       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4956         QualType type = VD->getType().getNonReferenceType();
4957         if (auto pointerType = type->getAs<PointerType>())
4958           type = pointerType->getPointeeType();
4959         else if (auto blockType = type->getAs<BlockPointerType>())
4960           type = blockType->getPointeeType();
4961         // FIXME: data member pointers?
4962 
4963         // Dig out the function prototype, if there is one.
4964         Proto = type->getAs<FunctionProtoType>();
4965       }
4966     }
4967 
4968     // Fill in non-null argument information from the nullability
4969     // information on the parameter types (if we have them).
4970     if (Proto) {
4971       unsigned Index = 0;
4972       for (auto paramType : Proto->getParamTypes()) {
4973         if (isNonNullType(S.Context, paramType)) {
4974           if (NonNullArgs.empty())
4975             NonNullArgs.resize(Args.size());
4976 
4977           NonNullArgs.set(Index);
4978         }
4979 
4980         ++Index;
4981       }
4982     }
4983   }
4984 
4985   // Check for non-null arguments.
4986   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4987        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4988     if (NonNullArgs[ArgIndex])
4989       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4990   }
4991 }
4992 
4993 /// Warn if a pointer or reference argument passed to a function points to an
4994 /// object that is less aligned than the parameter. This can happen when
4995 /// creating a typedef with a lower alignment than the original type and then
4996 /// calling functions defined in terms of the original type.
4997 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4998                              StringRef ParamName, QualType ArgTy,
4999                              QualType ParamTy) {
5000 
5001   // If a function accepts a pointer or reference type
5002   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
5003     return;
5004 
5005   // If the parameter is a pointer type, get the pointee type for the
5006   // argument too. If the parameter is a reference type, don't try to get
5007   // the pointee type for the argument.
5008   if (ParamTy->isPointerType())
5009     ArgTy = ArgTy->getPointeeType();
5010 
5011   // Remove reference or pointer
5012   ParamTy = ParamTy->getPointeeType();
5013 
5014   // Find expected alignment, and the actual alignment of the passed object.
5015   // getTypeAlignInChars requires complete types
5016   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
5017       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
5018       ArgTy->isUndeducedType())
5019     return;
5020 
5021   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
5022   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
5023 
5024   // If the argument is less aligned than the parameter, there is a
5025   // potential alignment issue.
5026   if (ArgAlign < ParamAlign)
5027     Diag(Loc, diag::warn_param_mismatched_alignment)
5028         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
5029         << ParamName << (FDecl != nullptr) << FDecl;
5030 }
5031 
5032 /// Handles the checks for format strings, non-POD arguments to vararg
5033 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
5034 /// attributes.
5035 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
5036                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
5037                      bool IsMemberFunction, SourceLocation Loc,
5038                      SourceRange Range, VariadicCallType CallType) {
5039   // FIXME: We should check as much as we can in the template definition.
5040   if (CurContext->isDependentContext())
5041     return;
5042 
5043   // Printf and scanf checking.
5044   llvm::SmallBitVector CheckedVarArgs;
5045   if (FDecl) {
5046     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5047       // Only create vector if there are format attributes.
5048       CheckedVarArgs.resize(Args.size());
5049 
5050       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
5051                            CheckedVarArgs);
5052     }
5053   }
5054 
5055   // Refuse POD arguments that weren't caught by the format string
5056   // checks above.
5057   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
5058   if (CallType != VariadicDoesNotApply &&
5059       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
5060     unsigned NumParams = Proto ? Proto->getNumParams()
5061                        : FDecl && isa<FunctionDecl>(FDecl)
5062                            ? cast<FunctionDecl>(FDecl)->getNumParams()
5063                        : FDecl && isa<ObjCMethodDecl>(FDecl)
5064                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
5065                        : 0;
5066 
5067     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
5068       // Args[ArgIdx] can be null in malformed code.
5069       if (const Expr *Arg = Args[ArgIdx]) {
5070         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
5071           checkVariadicArgument(Arg, CallType);
5072       }
5073     }
5074   }
5075 
5076   if (FDecl || Proto) {
5077     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
5078 
5079     // Type safety checking.
5080     if (FDecl) {
5081       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
5082         CheckArgumentWithTypeTag(I, Args, Loc);
5083     }
5084   }
5085 
5086   // Check that passed arguments match the alignment of original arguments.
5087   // Try to get the missing prototype from the declaration.
5088   if (!Proto && FDecl) {
5089     const auto *FT = FDecl->getFunctionType();
5090     if (isa_and_nonnull<FunctionProtoType>(FT))
5091       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
5092   }
5093   if (Proto) {
5094     // For variadic functions, we may have more args than parameters.
5095     // For some K&R functions, we may have less args than parameters.
5096     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
5097     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
5098       // Args[ArgIdx] can be null in malformed code.
5099       if (const Expr *Arg = Args[ArgIdx]) {
5100         if (Arg->containsErrors())
5101           continue;
5102 
5103         QualType ParamTy = Proto->getParamType(ArgIdx);
5104         QualType ArgTy = Arg->getType();
5105         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
5106                           ArgTy, ParamTy);
5107       }
5108     }
5109   }
5110 
5111   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
5112     auto *AA = FDecl->getAttr<AllocAlignAttr>();
5113     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
5114     if (!Arg->isValueDependent()) {
5115       Expr::EvalResult Align;
5116       if (Arg->EvaluateAsInt(Align, Context)) {
5117         const llvm::APSInt &I = Align.Val.getInt();
5118         if (!I.isPowerOf2())
5119           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
5120               << Arg->getSourceRange();
5121 
5122         if (I > Sema::MaximumAlignment)
5123           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
5124               << Arg->getSourceRange() << Sema::MaximumAlignment;
5125       }
5126     }
5127   }
5128 
5129   if (FD)
5130     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
5131 }
5132 
5133 /// CheckConstructorCall - Check a constructor call for correctness and safety
5134 /// properties not enforced by the C type system.
5135 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5136                                 ArrayRef<const Expr *> Args,
5137                                 const FunctionProtoType *Proto,
5138                                 SourceLocation Loc) {
5139   VariadicCallType CallType =
5140       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5141 
5142   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5143   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5144                     Context.getPointerType(Ctor->getThisObjectType()));
5145 
5146   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5147             Loc, SourceRange(), CallType);
5148 }
5149 
5150 /// CheckFunctionCall - Check a direct function call for various correctness
5151 /// and safety properties not strictly enforced by the C type system.
5152 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5153                              const FunctionProtoType *Proto) {
5154   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5155                               isa<CXXMethodDecl>(FDecl);
5156   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5157                           IsMemberOperatorCall;
5158   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5159                                                   TheCall->getCallee());
5160   Expr** Args = TheCall->getArgs();
5161   unsigned NumArgs = TheCall->getNumArgs();
5162 
5163   Expr *ImplicitThis = nullptr;
5164   if (IsMemberOperatorCall) {
5165     // If this is a call to a member operator, hide the first argument
5166     // from checkCall.
5167     // FIXME: Our choice of AST representation here is less than ideal.
5168     ImplicitThis = Args[0];
5169     ++Args;
5170     --NumArgs;
5171   } else if (IsMemberFunction)
5172     ImplicitThis =
5173         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5174 
5175   if (ImplicitThis) {
5176     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5177     // used.
5178     QualType ThisType = ImplicitThis->getType();
5179     if (!ThisType->isPointerType()) {
5180       assert(!ThisType->isReferenceType());
5181       ThisType = Context.getPointerType(ThisType);
5182     }
5183 
5184     QualType ThisTypeFromDecl =
5185         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5186 
5187     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5188                       ThisTypeFromDecl);
5189   }
5190 
5191   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5192             IsMemberFunction, TheCall->getRParenLoc(),
5193             TheCall->getCallee()->getSourceRange(), CallType);
5194 
5195   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5196   // None of the checks below are needed for functions that don't have
5197   // simple names (e.g., C++ conversion functions).
5198   if (!FnInfo)
5199     return false;
5200 
5201   CheckTCBEnforcement(TheCall, FDecl);
5202 
5203   CheckAbsoluteValueFunction(TheCall, FDecl);
5204   CheckMaxUnsignedZero(TheCall, FDecl);
5205 
5206   if (getLangOpts().ObjC)
5207     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5208 
5209   unsigned CMId = FDecl->getMemoryFunctionKind();
5210 
5211   // Handle memory setting and copying functions.
5212   switch (CMId) {
5213   case 0:
5214     return false;
5215   case Builtin::BIstrlcpy: // fallthrough
5216   case Builtin::BIstrlcat:
5217     CheckStrlcpycatArguments(TheCall, FnInfo);
5218     break;
5219   case Builtin::BIstrncat:
5220     CheckStrncatArguments(TheCall, FnInfo);
5221     break;
5222   case Builtin::BIfree:
5223     CheckFreeArguments(TheCall);
5224     break;
5225   default:
5226     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5227   }
5228 
5229   return false;
5230 }
5231 
5232 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5233                                ArrayRef<const Expr *> Args) {
5234   VariadicCallType CallType =
5235       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5236 
5237   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5238             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5239             CallType);
5240 
5241   return false;
5242 }
5243 
5244 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5245                             const FunctionProtoType *Proto) {
5246   QualType Ty;
5247   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5248     Ty = V->getType().getNonReferenceType();
5249   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5250     Ty = F->getType().getNonReferenceType();
5251   else
5252     return false;
5253 
5254   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5255       !Ty->isFunctionProtoType())
5256     return false;
5257 
5258   VariadicCallType CallType;
5259   if (!Proto || !Proto->isVariadic()) {
5260     CallType = VariadicDoesNotApply;
5261   } else if (Ty->isBlockPointerType()) {
5262     CallType = VariadicBlock;
5263   } else { // Ty->isFunctionPointerType()
5264     CallType = VariadicFunction;
5265   }
5266 
5267   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5268             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5269             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5270             TheCall->getCallee()->getSourceRange(), CallType);
5271 
5272   return false;
5273 }
5274 
5275 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5276 /// such as function pointers returned from functions.
5277 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5278   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5279                                                   TheCall->getCallee());
5280   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5281             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5282             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5283             TheCall->getCallee()->getSourceRange(), CallType);
5284 
5285   return false;
5286 }
5287 
5288 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5289   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5290     return false;
5291 
5292   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5293   switch (Op) {
5294   case AtomicExpr::AO__c11_atomic_init:
5295   case AtomicExpr::AO__opencl_atomic_init:
5296     llvm_unreachable("There is no ordering argument for an init");
5297 
5298   case AtomicExpr::AO__c11_atomic_load:
5299   case AtomicExpr::AO__opencl_atomic_load:
5300   case AtomicExpr::AO__atomic_load_n:
5301   case AtomicExpr::AO__atomic_load:
5302     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5303            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5304 
5305   case AtomicExpr::AO__c11_atomic_store:
5306   case AtomicExpr::AO__opencl_atomic_store:
5307   case AtomicExpr::AO__atomic_store:
5308   case AtomicExpr::AO__atomic_store_n:
5309     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5310            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5311            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5312 
5313   default:
5314     return true;
5315   }
5316 }
5317 
5318 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5319                                          AtomicExpr::AtomicOp Op) {
5320   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5321   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5322   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5323   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5324                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5325                          Op);
5326 }
5327 
5328 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5329                                  SourceLocation RParenLoc, MultiExprArg Args,
5330                                  AtomicExpr::AtomicOp Op,
5331                                  AtomicArgumentOrder ArgOrder) {
5332   // All the non-OpenCL operations take one of the following forms.
5333   // The OpenCL operations take the __c11 forms with one extra argument for
5334   // synchronization scope.
5335   enum {
5336     // C    __c11_atomic_init(A *, C)
5337     Init,
5338 
5339     // C    __c11_atomic_load(A *, int)
5340     Load,
5341 
5342     // void __atomic_load(A *, CP, int)
5343     LoadCopy,
5344 
5345     // void __atomic_store(A *, CP, int)
5346     Copy,
5347 
5348     // C    __c11_atomic_add(A *, M, int)
5349     Arithmetic,
5350 
5351     // C    __atomic_exchange_n(A *, CP, int)
5352     Xchg,
5353 
5354     // void __atomic_exchange(A *, C *, CP, int)
5355     GNUXchg,
5356 
5357     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5358     C11CmpXchg,
5359 
5360     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5361     GNUCmpXchg
5362   } Form = Init;
5363 
5364   const unsigned NumForm = GNUCmpXchg + 1;
5365   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5366   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5367   // where:
5368   //   C is an appropriate type,
5369   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5370   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5371   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5372   //   the int parameters are for orderings.
5373 
5374   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5375       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5376       "need to update code for modified forms");
5377   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5378                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5379                         AtomicExpr::AO__atomic_load,
5380                 "need to update code for modified C11 atomics");
5381   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5382                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5383   bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
5384                Op <= AtomicExpr::AO__hip_atomic_fetch_max;
5385   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5386                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5387                IsOpenCL;
5388   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5389              Op == AtomicExpr::AO__atomic_store_n ||
5390              Op == AtomicExpr::AO__atomic_exchange_n ||
5391              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5392   bool IsAddSub = false;
5393 
5394   switch (Op) {
5395   case AtomicExpr::AO__c11_atomic_init:
5396   case AtomicExpr::AO__opencl_atomic_init:
5397     Form = Init;
5398     break;
5399 
5400   case AtomicExpr::AO__c11_atomic_load:
5401   case AtomicExpr::AO__opencl_atomic_load:
5402   case AtomicExpr::AO__atomic_load_n:
5403     Form = Load;
5404     break;
5405 
5406   case AtomicExpr::AO__atomic_load:
5407     Form = LoadCopy;
5408     break;
5409 
5410   case AtomicExpr::AO__c11_atomic_store:
5411   case AtomicExpr::AO__opencl_atomic_store:
5412   case AtomicExpr::AO__atomic_store:
5413   case AtomicExpr::AO__atomic_store_n:
5414     Form = Copy;
5415     break;
5416   case AtomicExpr::AO__hip_atomic_fetch_add:
5417   case AtomicExpr::AO__hip_atomic_fetch_min:
5418   case AtomicExpr::AO__hip_atomic_fetch_max:
5419   case AtomicExpr::AO__c11_atomic_fetch_add:
5420   case AtomicExpr::AO__c11_atomic_fetch_sub:
5421   case AtomicExpr::AO__opencl_atomic_fetch_add:
5422   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5423   case AtomicExpr::AO__atomic_fetch_add:
5424   case AtomicExpr::AO__atomic_fetch_sub:
5425   case AtomicExpr::AO__atomic_add_fetch:
5426   case AtomicExpr::AO__atomic_sub_fetch:
5427     IsAddSub = true;
5428     Form = Arithmetic;
5429     break;
5430   case AtomicExpr::AO__c11_atomic_fetch_and:
5431   case AtomicExpr::AO__c11_atomic_fetch_or:
5432   case AtomicExpr::AO__c11_atomic_fetch_xor:
5433   case AtomicExpr::AO__hip_atomic_fetch_and:
5434   case AtomicExpr::AO__hip_atomic_fetch_or:
5435   case AtomicExpr::AO__hip_atomic_fetch_xor:
5436   case AtomicExpr::AO__c11_atomic_fetch_nand:
5437   case AtomicExpr::AO__opencl_atomic_fetch_and:
5438   case AtomicExpr::AO__opencl_atomic_fetch_or:
5439   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5440   case AtomicExpr::AO__atomic_fetch_and:
5441   case AtomicExpr::AO__atomic_fetch_or:
5442   case AtomicExpr::AO__atomic_fetch_xor:
5443   case AtomicExpr::AO__atomic_fetch_nand:
5444   case AtomicExpr::AO__atomic_and_fetch:
5445   case AtomicExpr::AO__atomic_or_fetch:
5446   case AtomicExpr::AO__atomic_xor_fetch:
5447   case AtomicExpr::AO__atomic_nand_fetch:
5448     Form = Arithmetic;
5449     break;
5450   case AtomicExpr::AO__c11_atomic_fetch_min:
5451   case AtomicExpr::AO__c11_atomic_fetch_max:
5452   case AtomicExpr::AO__opencl_atomic_fetch_min:
5453   case AtomicExpr::AO__opencl_atomic_fetch_max:
5454   case AtomicExpr::AO__atomic_min_fetch:
5455   case AtomicExpr::AO__atomic_max_fetch:
5456   case AtomicExpr::AO__atomic_fetch_min:
5457   case AtomicExpr::AO__atomic_fetch_max:
5458     Form = Arithmetic;
5459     break;
5460 
5461   case AtomicExpr::AO__c11_atomic_exchange:
5462   case AtomicExpr::AO__hip_atomic_exchange:
5463   case AtomicExpr::AO__opencl_atomic_exchange:
5464   case AtomicExpr::AO__atomic_exchange_n:
5465     Form = Xchg;
5466     break;
5467 
5468   case AtomicExpr::AO__atomic_exchange:
5469     Form = GNUXchg;
5470     break;
5471 
5472   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5473   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5474   case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5475   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5476   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5477     Form = C11CmpXchg;
5478     break;
5479 
5480   case AtomicExpr::AO__atomic_compare_exchange:
5481   case AtomicExpr::AO__atomic_compare_exchange_n:
5482     Form = GNUCmpXchg;
5483     break;
5484   }
5485 
5486   unsigned AdjustedNumArgs = NumArgs[Form];
5487   if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init)
5488     ++AdjustedNumArgs;
5489   // Check we have the right number of arguments.
5490   if (Args.size() < AdjustedNumArgs) {
5491     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5492         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5493         << ExprRange;
5494     return ExprError();
5495   } else if (Args.size() > AdjustedNumArgs) {
5496     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5497          diag::err_typecheck_call_too_many_args)
5498         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5499         << ExprRange;
5500     return ExprError();
5501   }
5502 
5503   // Inspect the first argument of the atomic operation.
5504   Expr *Ptr = Args[0];
5505   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5506   if (ConvertedPtr.isInvalid())
5507     return ExprError();
5508 
5509   Ptr = ConvertedPtr.get();
5510   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5511   if (!pointerType) {
5512     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5513         << Ptr->getType() << Ptr->getSourceRange();
5514     return ExprError();
5515   }
5516 
5517   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5518   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5519   QualType ValType = AtomTy; // 'C'
5520   if (IsC11) {
5521     if (!AtomTy->isAtomicType()) {
5522       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5523           << Ptr->getType() << Ptr->getSourceRange();
5524       return ExprError();
5525     }
5526     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5527         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5528       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5529           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5530           << Ptr->getSourceRange();
5531       return ExprError();
5532     }
5533     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5534   } else if (Form != Load && Form != LoadCopy) {
5535     if (ValType.isConstQualified()) {
5536       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5537           << Ptr->getType() << Ptr->getSourceRange();
5538       return ExprError();
5539     }
5540   }
5541 
5542   // For an arithmetic operation, the implied arithmetic must be well-formed.
5543   if (Form == Arithmetic) {
5544     // GCC does not enforce these rules for GNU atomics, but we do, because if
5545     // we didn't it would be very confusing. FIXME:  For whom? How so?
5546     auto IsAllowedValueType = [&](QualType ValType) {
5547       if (ValType->isIntegerType())
5548         return true;
5549       if (ValType->isPointerType())
5550         return true;
5551       if (!ValType->isFloatingType())
5552         return false;
5553       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5554       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5555           &Context.getTargetInfo().getLongDoubleFormat() ==
5556               &llvm::APFloat::x87DoubleExtended())
5557         return false;
5558       return true;
5559     };
5560     if (IsAddSub && !IsAllowedValueType(ValType)) {
5561       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5562           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5563       return ExprError();
5564     }
5565     if (!IsAddSub && !ValType->isIntegerType()) {
5566       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5567           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5568       return ExprError();
5569     }
5570     if (IsC11 && ValType->isPointerType() &&
5571         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5572                             diag::err_incomplete_type)) {
5573       return ExprError();
5574     }
5575   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5576     // For __atomic_*_n operations, the value type must be a scalar integral or
5577     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5578     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5579         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5580     return ExprError();
5581   }
5582 
5583   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5584       !AtomTy->isScalarType()) {
5585     // For GNU atomics, require a trivially-copyable type. This is not part of
5586     // the GNU atomics specification, but we enforce it, because if we didn't it
5587     // would be very confusing. FIXME:  For whom? How so?
5588     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5589         << Ptr->getType() << Ptr->getSourceRange();
5590     return ExprError();
5591   }
5592 
5593   switch (ValType.getObjCLifetime()) {
5594   case Qualifiers::OCL_None:
5595   case Qualifiers::OCL_ExplicitNone:
5596     // okay
5597     break;
5598 
5599   case Qualifiers::OCL_Weak:
5600   case Qualifiers::OCL_Strong:
5601   case Qualifiers::OCL_Autoreleasing:
5602     // FIXME: Can this happen? By this point, ValType should be known
5603     // to be trivially copyable.
5604     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5605         << ValType << Ptr->getSourceRange();
5606     return ExprError();
5607   }
5608 
5609   // All atomic operations have an overload which takes a pointer to a volatile
5610   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5611   // into the result or the other operands. Similarly atomic_load takes a
5612   // pointer to a const 'A'.
5613   ValType.removeLocalVolatile();
5614   ValType.removeLocalConst();
5615   QualType ResultType = ValType;
5616   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5617       Form == Init)
5618     ResultType = Context.VoidTy;
5619   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5620     ResultType = Context.BoolTy;
5621 
5622   // The type of a parameter passed 'by value'. In the GNU atomics, such
5623   // arguments are actually passed as pointers.
5624   QualType ByValType = ValType; // 'CP'
5625   bool IsPassedByAddress = false;
5626   if (!IsC11 && !IsHIP && !IsN) {
5627     ByValType = Ptr->getType();
5628     IsPassedByAddress = true;
5629   }
5630 
5631   SmallVector<Expr *, 5> APIOrderedArgs;
5632   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5633     APIOrderedArgs.push_back(Args[0]);
5634     switch (Form) {
5635     case Init:
5636     case Load:
5637       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5638       break;
5639     case LoadCopy:
5640     case Copy:
5641     case Arithmetic:
5642     case Xchg:
5643       APIOrderedArgs.push_back(Args[2]); // Val1
5644       APIOrderedArgs.push_back(Args[1]); // Order
5645       break;
5646     case GNUXchg:
5647       APIOrderedArgs.push_back(Args[2]); // Val1
5648       APIOrderedArgs.push_back(Args[3]); // Val2
5649       APIOrderedArgs.push_back(Args[1]); // Order
5650       break;
5651     case C11CmpXchg:
5652       APIOrderedArgs.push_back(Args[2]); // Val1
5653       APIOrderedArgs.push_back(Args[4]); // Val2
5654       APIOrderedArgs.push_back(Args[1]); // Order
5655       APIOrderedArgs.push_back(Args[3]); // OrderFail
5656       break;
5657     case GNUCmpXchg:
5658       APIOrderedArgs.push_back(Args[2]); // Val1
5659       APIOrderedArgs.push_back(Args[4]); // Val2
5660       APIOrderedArgs.push_back(Args[5]); // Weak
5661       APIOrderedArgs.push_back(Args[1]); // Order
5662       APIOrderedArgs.push_back(Args[3]); // OrderFail
5663       break;
5664     }
5665   } else
5666     APIOrderedArgs.append(Args.begin(), Args.end());
5667 
5668   // The first argument's non-CV pointer type is used to deduce the type of
5669   // subsequent arguments, except for:
5670   //  - weak flag (always converted to bool)
5671   //  - memory order (always converted to int)
5672   //  - scope  (always converted to int)
5673   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5674     QualType Ty;
5675     if (i < NumVals[Form] + 1) {
5676       switch (i) {
5677       case 0:
5678         // The first argument is always a pointer. It has a fixed type.
5679         // It is always dereferenced, a nullptr is undefined.
5680         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5681         // Nothing else to do: we already know all we want about this pointer.
5682         continue;
5683       case 1:
5684         // The second argument is the non-atomic operand. For arithmetic, this
5685         // is always passed by value, and for a compare_exchange it is always
5686         // passed by address. For the rest, GNU uses by-address and C11 uses
5687         // by-value.
5688         assert(Form != Load);
5689         if (Form == Arithmetic && ValType->isPointerType())
5690           Ty = Context.getPointerDiffType();
5691         else if (Form == Init || Form == Arithmetic)
5692           Ty = ValType;
5693         else if (Form == Copy || Form == Xchg) {
5694           if (IsPassedByAddress) {
5695             // The value pointer is always dereferenced, a nullptr is undefined.
5696             CheckNonNullArgument(*this, APIOrderedArgs[i],
5697                                  ExprRange.getBegin());
5698           }
5699           Ty = ByValType;
5700         } else {
5701           Expr *ValArg = APIOrderedArgs[i];
5702           // The value pointer is always dereferenced, a nullptr is undefined.
5703           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5704           LangAS AS = LangAS::Default;
5705           // Keep address space of non-atomic pointer type.
5706           if (const PointerType *PtrTy =
5707                   ValArg->getType()->getAs<PointerType>()) {
5708             AS = PtrTy->getPointeeType().getAddressSpace();
5709           }
5710           Ty = Context.getPointerType(
5711               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5712         }
5713         break;
5714       case 2:
5715         // The third argument to compare_exchange / GNU exchange is the desired
5716         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5717         if (IsPassedByAddress)
5718           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5719         Ty = ByValType;
5720         break;
5721       case 3:
5722         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5723         Ty = Context.BoolTy;
5724         break;
5725       }
5726     } else {
5727       // The order(s) and scope are always converted to int.
5728       Ty = Context.IntTy;
5729     }
5730 
5731     InitializedEntity Entity =
5732         InitializedEntity::InitializeParameter(Context, Ty, false);
5733     ExprResult Arg = APIOrderedArgs[i];
5734     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5735     if (Arg.isInvalid())
5736       return true;
5737     APIOrderedArgs[i] = Arg.get();
5738   }
5739 
5740   // Permute the arguments into a 'consistent' order.
5741   SmallVector<Expr*, 5> SubExprs;
5742   SubExprs.push_back(Ptr);
5743   switch (Form) {
5744   case Init:
5745     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5746     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5747     break;
5748   case Load:
5749     SubExprs.push_back(APIOrderedArgs[1]); // Order
5750     break;
5751   case LoadCopy:
5752   case Copy:
5753   case Arithmetic:
5754   case Xchg:
5755     SubExprs.push_back(APIOrderedArgs[2]); // Order
5756     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5757     break;
5758   case GNUXchg:
5759     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5760     SubExprs.push_back(APIOrderedArgs[3]); // Order
5761     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5762     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5763     break;
5764   case C11CmpXchg:
5765     SubExprs.push_back(APIOrderedArgs[3]); // Order
5766     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5767     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5768     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5769     break;
5770   case GNUCmpXchg:
5771     SubExprs.push_back(APIOrderedArgs[4]); // Order
5772     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5773     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5774     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5775     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5776     break;
5777   }
5778 
5779   if (SubExprs.size() >= 2 && Form != Init) {
5780     if (Optional<llvm::APSInt> Result =
5781             SubExprs[1]->getIntegerConstantExpr(Context))
5782       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5783         Diag(SubExprs[1]->getBeginLoc(),
5784              diag::warn_atomic_op_has_invalid_memory_order)
5785             << SubExprs[1]->getSourceRange();
5786   }
5787 
5788   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5789     auto *Scope = Args[Args.size() - 1];
5790     if (Optional<llvm::APSInt> Result =
5791             Scope->getIntegerConstantExpr(Context)) {
5792       if (!ScopeModel->isValid(Result->getZExtValue()))
5793         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5794             << Scope->getSourceRange();
5795     }
5796     SubExprs.push_back(Scope);
5797   }
5798 
5799   AtomicExpr *AE = new (Context)
5800       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5801 
5802   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5803        Op == AtomicExpr::AO__c11_atomic_store ||
5804        Op == AtomicExpr::AO__opencl_atomic_load ||
5805        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5806       Context.AtomicUsesUnsupportedLibcall(AE))
5807     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5808         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5809              Op == AtomicExpr::AO__opencl_atomic_load)
5810                 ? 0
5811                 : 1);
5812 
5813   if (ValType->isExtIntType()) {
5814     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5815     return ExprError();
5816   }
5817 
5818   return AE;
5819 }
5820 
5821 /// checkBuiltinArgument - Given a call to a builtin function, perform
5822 /// normal type-checking on the given argument, updating the call in
5823 /// place.  This is useful when a builtin function requires custom
5824 /// type-checking for some of its arguments but not necessarily all of
5825 /// them.
5826 ///
5827 /// Returns true on error.
5828 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5829   FunctionDecl *Fn = E->getDirectCallee();
5830   assert(Fn && "builtin call without direct callee!");
5831 
5832   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5833   InitializedEntity Entity =
5834     InitializedEntity::InitializeParameter(S.Context, Param);
5835 
5836   ExprResult Arg = E->getArg(0);
5837   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5838   if (Arg.isInvalid())
5839     return true;
5840 
5841   E->setArg(ArgIndex, Arg.get());
5842   return false;
5843 }
5844 
5845 /// We have a call to a function like __sync_fetch_and_add, which is an
5846 /// overloaded function based on the pointer type of its first argument.
5847 /// The main BuildCallExpr routines have already promoted the types of
5848 /// arguments because all of these calls are prototyped as void(...).
5849 ///
5850 /// This function goes through and does final semantic checking for these
5851 /// builtins, as well as generating any warnings.
5852 ExprResult
5853 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5854   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5855   Expr *Callee = TheCall->getCallee();
5856   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5857   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5858 
5859   // Ensure that we have at least one argument to do type inference from.
5860   if (TheCall->getNumArgs() < 1) {
5861     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5862         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5863     return ExprError();
5864   }
5865 
5866   // Inspect the first argument of the atomic builtin.  This should always be
5867   // a pointer type, whose element is an integral scalar or pointer type.
5868   // Because it is a pointer type, we don't have to worry about any implicit
5869   // casts here.
5870   // FIXME: We don't allow floating point scalars as input.
5871   Expr *FirstArg = TheCall->getArg(0);
5872   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5873   if (FirstArgResult.isInvalid())
5874     return ExprError();
5875   FirstArg = FirstArgResult.get();
5876   TheCall->setArg(0, FirstArg);
5877 
5878   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5879   if (!pointerType) {
5880     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5881         << FirstArg->getType() << FirstArg->getSourceRange();
5882     return ExprError();
5883   }
5884 
5885   QualType ValType = pointerType->getPointeeType();
5886   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5887       !ValType->isBlockPointerType()) {
5888     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5889         << FirstArg->getType() << FirstArg->getSourceRange();
5890     return ExprError();
5891   }
5892 
5893   if (ValType.isConstQualified()) {
5894     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5895         << FirstArg->getType() << FirstArg->getSourceRange();
5896     return ExprError();
5897   }
5898 
5899   switch (ValType.getObjCLifetime()) {
5900   case Qualifiers::OCL_None:
5901   case Qualifiers::OCL_ExplicitNone:
5902     // okay
5903     break;
5904 
5905   case Qualifiers::OCL_Weak:
5906   case Qualifiers::OCL_Strong:
5907   case Qualifiers::OCL_Autoreleasing:
5908     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5909         << ValType << FirstArg->getSourceRange();
5910     return ExprError();
5911   }
5912 
5913   // Strip any qualifiers off ValType.
5914   ValType = ValType.getUnqualifiedType();
5915 
5916   // The majority of builtins return a value, but a few have special return
5917   // types, so allow them to override appropriately below.
5918   QualType ResultType = ValType;
5919 
5920   // We need to figure out which concrete builtin this maps onto.  For example,
5921   // __sync_fetch_and_add with a 2 byte object turns into
5922   // __sync_fetch_and_add_2.
5923 #define BUILTIN_ROW(x) \
5924   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5925     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5926 
5927   static const unsigned BuiltinIndices[][5] = {
5928     BUILTIN_ROW(__sync_fetch_and_add),
5929     BUILTIN_ROW(__sync_fetch_and_sub),
5930     BUILTIN_ROW(__sync_fetch_and_or),
5931     BUILTIN_ROW(__sync_fetch_and_and),
5932     BUILTIN_ROW(__sync_fetch_and_xor),
5933     BUILTIN_ROW(__sync_fetch_and_nand),
5934 
5935     BUILTIN_ROW(__sync_add_and_fetch),
5936     BUILTIN_ROW(__sync_sub_and_fetch),
5937     BUILTIN_ROW(__sync_and_and_fetch),
5938     BUILTIN_ROW(__sync_or_and_fetch),
5939     BUILTIN_ROW(__sync_xor_and_fetch),
5940     BUILTIN_ROW(__sync_nand_and_fetch),
5941 
5942     BUILTIN_ROW(__sync_val_compare_and_swap),
5943     BUILTIN_ROW(__sync_bool_compare_and_swap),
5944     BUILTIN_ROW(__sync_lock_test_and_set),
5945     BUILTIN_ROW(__sync_lock_release),
5946     BUILTIN_ROW(__sync_swap)
5947   };
5948 #undef BUILTIN_ROW
5949 
5950   // Determine the index of the size.
5951   unsigned SizeIndex;
5952   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5953   case 1: SizeIndex = 0; break;
5954   case 2: SizeIndex = 1; break;
5955   case 4: SizeIndex = 2; break;
5956   case 8: SizeIndex = 3; break;
5957   case 16: SizeIndex = 4; break;
5958   default:
5959     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5960         << FirstArg->getType() << FirstArg->getSourceRange();
5961     return ExprError();
5962   }
5963 
5964   // Each of these builtins has one pointer argument, followed by some number of
5965   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5966   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5967   // as the number of fixed args.
5968   unsigned BuiltinID = FDecl->getBuiltinID();
5969   unsigned BuiltinIndex, NumFixed = 1;
5970   bool WarnAboutSemanticsChange = false;
5971   switch (BuiltinID) {
5972   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5973   case Builtin::BI__sync_fetch_and_add:
5974   case Builtin::BI__sync_fetch_and_add_1:
5975   case Builtin::BI__sync_fetch_and_add_2:
5976   case Builtin::BI__sync_fetch_and_add_4:
5977   case Builtin::BI__sync_fetch_and_add_8:
5978   case Builtin::BI__sync_fetch_and_add_16:
5979     BuiltinIndex = 0;
5980     break;
5981 
5982   case Builtin::BI__sync_fetch_and_sub:
5983   case Builtin::BI__sync_fetch_and_sub_1:
5984   case Builtin::BI__sync_fetch_and_sub_2:
5985   case Builtin::BI__sync_fetch_and_sub_4:
5986   case Builtin::BI__sync_fetch_and_sub_8:
5987   case Builtin::BI__sync_fetch_and_sub_16:
5988     BuiltinIndex = 1;
5989     break;
5990 
5991   case Builtin::BI__sync_fetch_and_or:
5992   case Builtin::BI__sync_fetch_and_or_1:
5993   case Builtin::BI__sync_fetch_and_or_2:
5994   case Builtin::BI__sync_fetch_and_or_4:
5995   case Builtin::BI__sync_fetch_and_or_8:
5996   case Builtin::BI__sync_fetch_and_or_16:
5997     BuiltinIndex = 2;
5998     break;
5999 
6000   case Builtin::BI__sync_fetch_and_and:
6001   case Builtin::BI__sync_fetch_and_and_1:
6002   case Builtin::BI__sync_fetch_and_and_2:
6003   case Builtin::BI__sync_fetch_and_and_4:
6004   case Builtin::BI__sync_fetch_and_and_8:
6005   case Builtin::BI__sync_fetch_and_and_16:
6006     BuiltinIndex = 3;
6007     break;
6008 
6009   case Builtin::BI__sync_fetch_and_xor:
6010   case Builtin::BI__sync_fetch_and_xor_1:
6011   case Builtin::BI__sync_fetch_and_xor_2:
6012   case Builtin::BI__sync_fetch_and_xor_4:
6013   case Builtin::BI__sync_fetch_and_xor_8:
6014   case Builtin::BI__sync_fetch_and_xor_16:
6015     BuiltinIndex = 4;
6016     break;
6017 
6018   case Builtin::BI__sync_fetch_and_nand:
6019   case Builtin::BI__sync_fetch_and_nand_1:
6020   case Builtin::BI__sync_fetch_and_nand_2:
6021   case Builtin::BI__sync_fetch_and_nand_4:
6022   case Builtin::BI__sync_fetch_and_nand_8:
6023   case Builtin::BI__sync_fetch_and_nand_16:
6024     BuiltinIndex = 5;
6025     WarnAboutSemanticsChange = true;
6026     break;
6027 
6028   case Builtin::BI__sync_add_and_fetch:
6029   case Builtin::BI__sync_add_and_fetch_1:
6030   case Builtin::BI__sync_add_and_fetch_2:
6031   case Builtin::BI__sync_add_and_fetch_4:
6032   case Builtin::BI__sync_add_and_fetch_8:
6033   case Builtin::BI__sync_add_and_fetch_16:
6034     BuiltinIndex = 6;
6035     break;
6036 
6037   case Builtin::BI__sync_sub_and_fetch:
6038   case Builtin::BI__sync_sub_and_fetch_1:
6039   case Builtin::BI__sync_sub_and_fetch_2:
6040   case Builtin::BI__sync_sub_and_fetch_4:
6041   case Builtin::BI__sync_sub_and_fetch_8:
6042   case Builtin::BI__sync_sub_and_fetch_16:
6043     BuiltinIndex = 7;
6044     break;
6045 
6046   case Builtin::BI__sync_and_and_fetch:
6047   case Builtin::BI__sync_and_and_fetch_1:
6048   case Builtin::BI__sync_and_and_fetch_2:
6049   case Builtin::BI__sync_and_and_fetch_4:
6050   case Builtin::BI__sync_and_and_fetch_8:
6051   case Builtin::BI__sync_and_and_fetch_16:
6052     BuiltinIndex = 8;
6053     break;
6054 
6055   case Builtin::BI__sync_or_and_fetch:
6056   case Builtin::BI__sync_or_and_fetch_1:
6057   case Builtin::BI__sync_or_and_fetch_2:
6058   case Builtin::BI__sync_or_and_fetch_4:
6059   case Builtin::BI__sync_or_and_fetch_8:
6060   case Builtin::BI__sync_or_and_fetch_16:
6061     BuiltinIndex = 9;
6062     break;
6063 
6064   case Builtin::BI__sync_xor_and_fetch:
6065   case Builtin::BI__sync_xor_and_fetch_1:
6066   case Builtin::BI__sync_xor_and_fetch_2:
6067   case Builtin::BI__sync_xor_and_fetch_4:
6068   case Builtin::BI__sync_xor_and_fetch_8:
6069   case Builtin::BI__sync_xor_and_fetch_16:
6070     BuiltinIndex = 10;
6071     break;
6072 
6073   case Builtin::BI__sync_nand_and_fetch:
6074   case Builtin::BI__sync_nand_and_fetch_1:
6075   case Builtin::BI__sync_nand_and_fetch_2:
6076   case Builtin::BI__sync_nand_and_fetch_4:
6077   case Builtin::BI__sync_nand_and_fetch_8:
6078   case Builtin::BI__sync_nand_and_fetch_16:
6079     BuiltinIndex = 11;
6080     WarnAboutSemanticsChange = true;
6081     break;
6082 
6083   case Builtin::BI__sync_val_compare_and_swap:
6084   case Builtin::BI__sync_val_compare_and_swap_1:
6085   case Builtin::BI__sync_val_compare_and_swap_2:
6086   case Builtin::BI__sync_val_compare_and_swap_4:
6087   case Builtin::BI__sync_val_compare_and_swap_8:
6088   case Builtin::BI__sync_val_compare_and_swap_16:
6089     BuiltinIndex = 12;
6090     NumFixed = 2;
6091     break;
6092 
6093   case Builtin::BI__sync_bool_compare_and_swap:
6094   case Builtin::BI__sync_bool_compare_and_swap_1:
6095   case Builtin::BI__sync_bool_compare_and_swap_2:
6096   case Builtin::BI__sync_bool_compare_and_swap_4:
6097   case Builtin::BI__sync_bool_compare_and_swap_8:
6098   case Builtin::BI__sync_bool_compare_and_swap_16:
6099     BuiltinIndex = 13;
6100     NumFixed = 2;
6101     ResultType = Context.BoolTy;
6102     break;
6103 
6104   case Builtin::BI__sync_lock_test_and_set:
6105   case Builtin::BI__sync_lock_test_and_set_1:
6106   case Builtin::BI__sync_lock_test_and_set_2:
6107   case Builtin::BI__sync_lock_test_and_set_4:
6108   case Builtin::BI__sync_lock_test_and_set_8:
6109   case Builtin::BI__sync_lock_test_and_set_16:
6110     BuiltinIndex = 14;
6111     break;
6112 
6113   case Builtin::BI__sync_lock_release:
6114   case Builtin::BI__sync_lock_release_1:
6115   case Builtin::BI__sync_lock_release_2:
6116   case Builtin::BI__sync_lock_release_4:
6117   case Builtin::BI__sync_lock_release_8:
6118   case Builtin::BI__sync_lock_release_16:
6119     BuiltinIndex = 15;
6120     NumFixed = 0;
6121     ResultType = Context.VoidTy;
6122     break;
6123 
6124   case Builtin::BI__sync_swap:
6125   case Builtin::BI__sync_swap_1:
6126   case Builtin::BI__sync_swap_2:
6127   case Builtin::BI__sync_swap_4:
6128   case Builtin::BI__sync_swap_8:
6129   case Builtin::BI__sync_swap_16:
6130     BuiltinIndex = 16;
6131     break;
6132   }
6133 
6134   // Now that we know how many fixed arguments we expect, first check that we
6135   // have at least that many.
6136   if (TheCall->getNumArgs() < 1+NumFixed) {
6137     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6138         << 0 << 1 + NumFixed << TheCall->getNumArgs()
6139         << Callee->getSourceRange();
6140     return ExprError();
6141   }
6142 
6143   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6144       << Callee->getSourceRange();
6145 
6146   if (WarnAboutSemanticsChange) {
6147     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6148         << Callee->getSourceRange();
6149   }
6150 
6151   // Get the decl for the concrete builtin from this, we can tell what the
6152   // concrete integer type we should convert to is.
6153   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6154   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6155   FunctionDecl *NewBuiltinDecl;
6156   if (NewBuiltinID == BuiltinID)
6157     NewBuiltinDecl = FDecl;
6158   else {
6159     // Perform builtin lookup to avoid redeclaring it.
6160     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6161     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6162     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6163     assert(Res.getFoundDecl());
6164     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6165     if (!NewBuiltinDecl)
6166       return ExprError();
6167   }
6168 
6169   // The first argument --- the pointer --- has a fixed type; we
6170   // deduce the types of the rest of the arguments accordingly.  Walk
6171   // the remaining arguments, converting them to the deduced value type.
6172   for (unsigned i = 0; i != NumFixed; ++i) {
6173     ExprResult Arg = TheCall->getArg(i+1);
6174 
6175     // GCC does an implicit conversion to the pointer or integer ValType.  This
6176     // can fail in some cases (1i -> int**), check for this error case now.
6177     // Initialize the argument.
6178     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6179                                                    ValType, /*consume*/ false);
6180     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6181     if (Arg.isInvalid())
6182       return ExprError();
6183 
6184     // Okay, we have something that *can* be converted to the right type.  Check
6185     // to see if there is a potentially weird extension going on here.  This can
6186     // happen when you do an atomic operation on something like an char* and
6187     // pass in 42.  The 42 gets converted to char.  This is even more strange
6188     // for things like 45.123 -> char, etc.
6189     // FIXME: Do this check.
6190     TheCall->setArg(i+1, Arg.get());
6191   }
6192 
6193   // Create a new DeclRefExpr to refer to the new decl.
6194   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6195       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6196       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6197       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6198 
6199   // Set the callee in the CallExpr.
6200   // FIXME: This loses syntactic information.
6201   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6202   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6203                                               CK_BuiltinFnToFnPtr);
6204   TheCall->setCallee(PromotedCall.get());
6205 
6206   // Change the result type of the call to match the original value type. This
6207   // is arbitrary, but the codegen for these builtins ins design to handle it
6208   // gracefully.
6209   TheCall->setType(ResultType);
6210 
6211   // Prohibit use of _ExtInt with atomic builtins.
6212   // The arguments would have already been converted to the first argument's
6213   // type, so only need to check the first argument.
6214   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
6215   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
6216     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6217     return ExprError();
6218   }
6219 
6220   return TheCallResult;
6221 }
6222 
6223 /// SemaBuiltinNontemporalOverloaded - We have a call to
6224 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6225 /// overloaded function based on the pointer type of its last argument.
6226 ///
6227 /// This function goes through and does final semantic checking for these
6228 /// builtins.
6229 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6230   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6231   DeclRefExpr *DRE =
6232       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6233   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6234   unsigned BuiltinID = FDecl->getBuiltinID();
6235   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6236           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6237          "Unexpected nontemporal load/store builtin!");
6238   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6239   unsigned numArgs = isStore ? 2 : 1;
6240 
6241   // Ensure that we have the proper number of arguments.
6242   if (checkArgCount(*this, TheCall, numArgs))
6243     return ExprError();
6244 
6245   // Inspect the last argument of the nontemporal builtin.  This should always
6246   // be a pointer type, from which we imply the type of the memory access.
6247   // Because it is a pointer type, we don't have to worry about any implicit
6248   // casts here.
6249   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6250   ExprResult PointerArgResult =
6251       DefaultFunctionArrayLvalueConversion(PointerArg);
6252 
6253   if (PointerArgResult.isInvalid())
6254     return ExprError();
6255   PointerArg = PointerArgResult.get();
6256   TheCall->setArg(numArgs - 1, PointerArg);
6257 
6258   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6259   if (!pointerType) {
6260     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6261         << PointerArg->getType() << PointerArg->getSourceRange();
6262     return ExprError();
6263   }
6264 
6265   QualType ValType = pointerType->getPointeeType();
6266 
6267   // Strip any qualifiers off ValType.
6268   ValType = ValType.getUnqualifiedType();
6269   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6270       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6271       !ValType->isVectorType()) {
6272     Diag(DRE->getBeginLoc(),
6273          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6274         << PointerArg->getType() << PointerArg->getSourceRange();
6275     return ExprError();
6276   }
6277 
6278   if (!isStore) {
6279     TheCall->setType(ValType);
6280     return TheCallResult;
6281   }
6282 
6283   ExprResult ValArg = TheCall->getArg(0);
6284   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6285       Context, ValType, /*consume*/ false);
6286   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6287   if (ValArg.isInvalid())
6288     return ExprError();
6289 
6290   TheCall->setArg(0, ValArg.get());
6291   TheCall->setType(Context.VoidTy);
6292   return TheCallResult;
6293 }
6294 
6295 /// CheckObjCString - Checks that the argument to the builtin
6296 /// CFString constructor is correct
6297 /// Note: It might also make sense to do the UTF-16 conversion here (would
6298 /// simplify the backend).
6299 bool Sema::CheckObjCString(Expr *Arg) {
6300   Arg = Arg->IgnoreParenCasts();
6301   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6302 
6303   if (!Literal || !Literal->isAscii()) {
6304     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6305         << Arg->getSourceRange();
6306     return true;
6307   }
6308 
6309   if (Literal->containsNonAsciiOrNull()) {
6310     StringRef String = Literal->getString();
6311     unsigned NumBytes = String.size();
6312     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6313     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6314     llvm::UTF16 *ToPtr = &ToBuf[0];
6315 
6316     llvm::ConversionResult Result =
6317         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6318                                  ToPtr + NumBytes, llvm::strictConversion);
6319     // Check for conversion failure.
6320     if (Result != llvm::conversionOK)
6321       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6322           << Arg->getSourceRange();
6323   }
6324   return false;
6325 }
6326 
6327 /// CheckObjCString - Checks that the format string argument to the os_log()
6328 /// and os_trace() functions is correct, and converts it to const char *.
6329 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6330   Arg = Arg->IgnoreParenCasts();
6331   auto *Literal = dyn_cast<StringLiteral>(Arg);
6332   if (!Literal) {
6333     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6334       Literal = ObjcLiteral->getString();
6335     }
6336   }
6337 
6338   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6339     return ExprError(
6340         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6341         << Arg->getSourceRange());
6342   }
6343 
6344   ExprResult Result(Literal);
6345   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6346   InitializedEntity Entity =
6347       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6348   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6349   return Result;
6350 }
6351 
6352 /// Check that the user is calling the appropriate va_start builtin for the
6353 /// target and calling convention.
6354 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6355   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6356   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6357   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6358                     TT.getArch() == llvm::Triple::aarch64_32);
6359   bool IsWindows = TT.isOSWindows();
6360   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6361   if (IsX64 || IsAArch64) {
6362     CallingConv CC = CC_C;
6363     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6364       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6365     if (IsMSVAStart) {
6366       // Don't allow this in System V ABI functions.
6367       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6368         return S.Diag(Fn->getBeginLoc(),
6369                       diag::err_ms_va_start_used_in_sysv_function);
6370     } else {
6371       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6372       // On x64 Windows, don't allow this in System V ABI functions.
6373       // (Yes, that means there's no corresponding way to support variadic
6374       // System V ABI functions on Windows.)
6375       if ((IsWindows && CC == CC_X86_64SysV) ||
6376           (!IsWindows && CC == CC_Win64))
6377         return S.Diag(Fn->getBeginLoc(),
6378                       diag::err_va_start_used_in_wrong_abi_function)
6379                << !IsWindows;
6380     }
6381     return false;
6382   }
6383 
6384   if (IsMSVAStart)
6385     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6386   return false;
6387 }
6388 
6389 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6390                                              ParmVarDecl **LastParam = nullptr) {
6391   // Determine whether the current function, block, or obj-c method is variadic
6392   // and get its parameter list.
6393   bool IsVariadic = false;
6394   ArrayRef<ParmVarDecl *> Params;
6395   DeclContext *Caller = S.CurContext;
6396   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6397     IsVariadic = Block->isVariadic();
6398     Params = Block->parameters();
6399   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6400     IsVariadic = FD->isVariadic();
6401     Params = FD->parameters();
6402   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6403     IsVariadic = MD->isVariadic();
6404     // FIXME: This isn't correct for methods (results in bogus warning).
6405     Params = MD->parameters();
6406   } else if (isa<CapturedDecl>(Caller)) {
6407     // We don't support va_start in a CapturedDecl.
6408     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6409     return true;
6410   } else {
6411     // This must be some other declcontext that parses exprs.
6412     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6413     return true;
6414   }
6415 
6416   if (!IsVariadic) {
6417     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6418     return true;
6419   }
6420 
6421   if (LastParam)
6422     *LastParam = Params.empty() ? nullptr : Params.back();
6423 
6424   return false;
6425 }
6426 
6427 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6428 /// for validity.  Emit an error and return true on failure; return false
6429 /// on success.
6430 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6431   Expr *Fn = TheCall->getCallee();
6432 
6433   if (checkVAStartABI(*this, BuiltinID, Fn))
6434     return true;
6435 
6436   if (checkArgCount(*this, TheCall, 2))
6437     return true;
6438 
6439   // Type-check the first argument normally.
6440   if (checkBuiltinArgument(*this, TheCall, 0))
6441     return true;
6442 
6443   // Check that the current function is variadic, and get its last parameter.
6444   ParmVarDecl *LastParam;
6445   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6446     return true;
6447 
6448   // Verify that the second argument to the builtin is the last argument of the
6449   // current function or method.
6450   bool SecondArgIsLastNamedArgument = false;
6451   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6452 
6453   // These are valid if SecondArgIsLastNamedArgument is false after the next
6454   // block.
6455   QualType Type;
6456   SourceLocation ParamLoc;
6457   bool IsCRegister = false;
6458 
6459   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6460     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6461       SecondArgIsLastNamedArgument = PV == LastParam;
6462 
6463       Type = PV->getType();
6464       ParamLoc = PV->getLocation();
6465       IsCRegister =
6466           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6467     }
6468   }
6469 
6470   if (!SecondArgIsLastNamedArgument)
6471     Diag(TheCall->getArg(1)->getBeginLoc(),
6472          diag::warn_second_arg_of_va_start_not_last_named_param);
6473   else if (IsCRegister || Type->isReferenceType() ||
6474            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6475              // Promotable integers are UB, but enumerations need a bit of
6476              // extra checking to see what their promotable type actually is.
6477              if (!Type->isPromotableIntegerType())
6478                return false;
6479              if (!Type->isEnumeralType())
6480                return true;
6481              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6482              return !(ED &&
6483                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6484            }()) {
6485     unsigned Reason = 0;
6486     if (Type->isReferenceType())  Reason = 1;
6487     else if (IsCRegister)         Reason = 2;
6488     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6489     Diag(ParamLoc, diag::note_parameter_type) << Type;
6490   }
6491 
6492   TheCall->setType(Context.VoidTy);
6493   return false;
6494 }
6495 
6496 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6497   auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6498     const LangOptions &LO = getLangOpts();
6499 
6500     if (LO.CPlusPlus)
6501       return Arg->getType()
6502                  .getCanonicalType()
6503                  .getTypePtr()
6504                  ->getPointeeType()
6505                  .withoutLocalFastQualifiers() == Context.CharTy;
6506 
6507     // In C, allow aliasing through `char *`, this is required for AArch64 at
6508     // least.
6509     return true;
6510   };
6511 
6512   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6513   //                 const char *named_addr);
6514 
6515   Expr *Func = Call->getCallee();
6516 
6517   if (Call->getNumArgs() < 3)
6518     return Diag(Call->getEndLoc(),
6519                 diag::err_typecheck_call_too_few_args_at_least)
6520            << 0 /*function call*/ << 3 << Call->getNumArgs();
6521 
6522   // Type-check the first argument normally.
6523   if (checkBuiltinArgument(*this, Call, 0))
6524     return true;
6525 
6526   // Check that the current function is variadic.
6527   if (checkVAStartIsInVariadicFunction(*this, Func))
6528     return true;
6529 
6530   // __va_start on Windows does not validate the parameter qualifiers
6531 
6532   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6533   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6534 
6535   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6536   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6537 
6538   const QualType &ConstCharPtrTy =
6539       Context.getPointerType(Context.CharTy.withConst());
6540   if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6541     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6542         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6543         << 0                                      /* qualifier difference */
6544         << 3                                      /* parameter mismatch */
6545         << 2 << Arg1->getType() << ConstCharPtrTy;
6546 
6547   const QualType SizeTy = Context.getSizeType();
6548   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6549     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6550         << Arg2->getType() << SizeTy << 1 /* different class */
6551         << 0                              /* qualifier difference */
6552         << 3                              /* parameter mismatch */
6553         << 3 << Arg2->getType() << SizeTy;
6554 
6555   return false;
6556 }
6557 
6558 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6559 /// friends.  This is declared to take (...), so we have to check everything.
6560 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6561   if (checkArgCount(*this, TheCall, 2))
6562     return true;
6563 
6564   ExprResult OrigArg0 = TheCall->getArg(0);
6565   ExprResult OrigArg1 = TheCall->getArg(1);
6566 
6567   // Do standard promotions between the two arguments, returning their common
6568   // type.
6569   QualType Res = UsualArithmeticConversions(
6570       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6571   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6572     return true;
6573 
6574   // Make sure any conversions are pushed back into the call; this is
6575   // type safe since unordered compare builtins are declared as "_Bool
6576   // foo(...)".
6577   TheCall->setArg(0, OrigArg0.get());
6578   TheCall->setArg(1, OrigArg1.get());
6579 
6580   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6581     return false;
6582 
6583   // If the common type isn't a real floating type, then the arguments were
6584   // invalid for this operation.
6585   if (Res.isNull() || !Res->isRealFloatingType())
6586     return Diag(OrigArg0.get()->getBeginLoc(),
6587                 diag::err_typecheck_call_invalid_ordered_compare)
6588            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6589            << SourceRange(OrigArg0.get()->getBeginLoc(),
6590                           OrigArg1.get()->getEndLoc());
6591 
6592   return false;
6593 }
6594 
6595 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6596 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6597 /// to check everything. We expect the last argument to be a floating point
6598 /// value.
6599 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6600   if (checkArgCount(*this, TheCall, NumArgs))
6601     return true;
6602 
6603   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6604   // on all preceding parameters just being int.  Try all of those.
6605   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6606     Expr *Arg = TheCall->getArg(i);
6607 
6608     if (Arg->isTypeDependent())
6609       return false;
6610 
6611     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6612 
6613     if (Res.isInvalid())
6614       return true;
6615     TheCall->setArg(i, Res.get());
6616   }
6617 
6618   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6619 
6620   if (OrigArg->isTypeDependent())
6621     return false;
6622 
6623   // Usual Unary Conversions will convert half to float, which we want for
6624   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6625   // type how it is, but do normal L->Rvalue conversions.
6626   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6627     OrigArg = UsualUnaryConversions(OrigArg).get();
6628   else
6629     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6630   TheCall->setArg(NumArgs - 1, OrigArg);
6631 
6632   // This operation requires a non-_Complex floating-point number.
6633   if (!OrigArg->getType()->isRealFloatingType())
6634     return Diag(OrigArg->getBeginLoc(),
6635                 diag::err_typecheck_call_invalid_unary_fp)
6636            << OrigArg->getType() << OrigArg->getSourceRange();
6637 
6638   return false;
6639 }
6640 
6641 /// Perform semantic analysis for a call to __builtin_complex.
6642 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6643   if (checkArgCount(*this, TheCall, 2))
6644     return true;
6645 
6646   bool Dependent = false;
6647   for (unsigned I = 0; I != 2; ++I) {
6648     Expr *Arg = TheCall->getArg(I);
6649     QualType T = Arg->getType();
6650     if (T->isDependentType()) {
6651       Dependent = true;
6652       continue;
6653     }
6654 
6655     // Despite supporting _Complex int, GCC requires a real floating point type
6656     // for the operands of __builtin_complex.
6657     if (!T->isRealFloatingType()) {
6658       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6659              << Arg->getType() << Arg->getSourceRange();
6660     }
6661 
6662     ExprResult Converted = DefaultLvalueConversion(Arg);
6663     if (Converted.isInvalid())
6664       return true;
6665     TheCall->setArg(I, Converted.get());
6666   }
6667 
6668   if (Dependent) {
6669     TheCall->setType(Context.DependentTy);
6670     return false;
6671   }
6672 
6673   Expr *Real = TheCall->getArg(0);
6674   Expr *Imag = TheCall->getArg(1);
6675   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6676     return Diag(Real->getBeginLoc(),
6677                 diag::err_typecheck_call_different_arg_types)
6678            << Real->getType() << Imag->getType()
6679            << Real->getSourceRange() << Imag->getSourceRange();
6680   }
6681 
6682   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6683   // don't allow this builtin to form those types either.
6684   // FIXME: Should we allow these types?
6685   if (Real->getType()->isFloat16Type())
6686     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6687            << "_Float16";
6688   if (Real->getType()->isHalfType())
6689     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6690            << "half";
6691 
6692   TheCall->setType(Context.getComplexType(Real->getType()));
6693   return false;
6694 }
6695 
6696 // Customized Sema Checking for VSX builtins that have the following signature:
6697 // vector [...] builtinName(vector [...], vector [...], const int);
6698 // Which takes the same type of vectors (any legal vector type) for the first
6699 // two arguments and takes compile time constant for the third argument.
6700 // Example builtins are :
6701 // vector double vec_xxpermdi(vector double, vector double, int);
6702 // vector short vec_xxsldwi(vector short, vector short, int);
6703 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6704   unsigned ExpectedNumArgs = 3;
6705   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6706     return true;
6707 
6708   // Check the third argument is a compile time constant
6709   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6710     return Diag(TheCall->getBeginLoc(),
6711                 diag::err_vsx_builtin_nonconstant_argument)
6712            << 3 /* argument index */ << TheCall->getDirectCallee()
6713            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6714                           TheCall->getArg(2)->getEndLoc());
6715 
6716   QualType Arg1Ty = TheCall->getArg(0)->getType();
6717   QualType Arg2Ty = TheCall->getArg(1)->getType();
6718 
6719   // Check the type of argument 1 and argument 2 are vectors.
6720   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6721   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6722       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6723     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6724            << TheCall->getDirectCallee()
6725            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6726                           TheCall->getArg(1)->getEndLoc());
6727   }
6728 
6729   // Check the first two arguments are the same type.
6730   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6731     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6732            << TheCall->getDirectCallee()
6733            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6734                           TheCall->getArg(1)->getEndLoc());
6735   }
6736 
6737   // When default clang type checking is turned off and the customized type
6738   // checking is used, the returning type of the function must be explicitly
6739   // set. Otherwise it is _Bool by default.
6740   TheCall->setType(Arg1Ty);
6741 
6742   return false;
6743 }
6744 
6745 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6746 // This is declared to take (...), so we have to check everything.
6747 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6748   if (TheCall->getNumArgs() < 2)
6749     return ExprError(Diag(TheCall->getEndLoc(),
6750                           diag::err_typecheck_call_too_few_args_at_least)
6751                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6752                      << TheCall->getSourceRange());
6753 
6754   // Determine which of the following types of shufflevector we're checking:
6755   // 1) unary, vector mask: (lhs, mask)
6756   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6757   QualType resType = TheCall->getArg(0)->getType();
6758   unsigned numElements = 0;
6759 
6760   if (!TheCall->getArg(0)->isTypeDependent() &&
6761       !TheCall->getArg(1)->isTypeDependent()) {
6762     QualType LHSType = TheCall->getArg(0)->getType();
6763     QualType RHSType = TheCall->getArg(1)->getType();
6764 
6765     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6766       return ExprError(
6767           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6768           << TheCall->getDirectCallee()
6769           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6770                          TheCall->getArg(1)->getEndLoc()));
6771 
6772     numElements = LHSType->castAs<VectorType>()->getNumElements();
6773     unsigned numResElements = TheCall->getNumArgs() - 2;
6774 
6775     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6776     // with mask.  If so, verify that RHS is an integer vector type with the
6777     // same number of elts as lhs.
6778     if (TheCall->getNumArgs() == 2) {
6779       if (!RHSType->hasIntegerRepresentation() ||
6780           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6781         return ExprError(Diag(TheCall->getBeginLoc(),
6782                               diag::err_vec_builtin_incompatible_vector)
6783                          << TheCall->getDirectCallee()
6784                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6785                                         TheCall->getArg(1)->getEndLoc()));
6786     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6787       return ExprError(Diag(TheCall->getBeginLoc(),
6788                             diag::err_vec_builtin_incompatible_vector)
6789                        << TheCall->getDirectCallee()
6790                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6791                                       TheCall->getArg(1)->getEndLoc()));
6792     } else if (numElements != numResElements) {
6793       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6794       resType = Context.getVectorType(eltType, numResElements,
6795                                       VectorType::GenericVector);
6796     }
6797   }
6798 
6799   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6800     if (TheCall->getArg(i)->isTypeDependent() ||
6801         TheCall->getArg(i)->isValueDependent())
6802       continue;
6803 
6804     Optional<llvm::APSInt> Result;
6805     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6806       return ExprError(Diag(TheCall->getBeginLoc(),
6807                             diag::err_shufflevector_nonconstant_argument)
6808                        << TheCall->getArg(i)->getSourceRange());
6809 
6810     // Allow -1 which will be translated to undef in the IR.
6811     if (Result->isSigned() && Result->isAllOnes())
6812       continue;
6813 
6814     if (Result->getActiveBits() > 64 ||
6815         Result->getZExtValue() >= numElements * 2)
6816       return ExprError(Diag(TheCall->getBeginLoc(),
6817                             diag::err_shufflevector_argument_too_large)
6818                        << TheCall->getArg(i)->getSourceRange());
6819   }
6820 
6821   SmallVector<Expr*, 32> exprs;
6822 
6823   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6824     exprs.push_back(TheCall->getArg(i));
6825     TheCall->setArg(i, nullptr);
6826   }
6827 
6828   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6829                                          TheCall->getCallee()->getBeginLoc(),
6830                                          TheCall->getRParenLoc());
6831 }
6832 
6833 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6834 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6835                                        SourceLocation BuiltinLoc,
6836                                        SourceLocation RParenLoc) {
6837   ExprValueKind VK = VK_PRValue;
6838   ExprObjectKind OK = OK_Ordinary;
6839   QualType DstTy = TInfo->getType();
6840   QualType SrcTy = E->getType();
6841 
6842   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6843     return ExprError(Diag(BuiltinLoc,
6844                           diag::err_convertvector_non_vector)
6845                      << E->getSourceRange());
6846   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6847     return ExprError(Diag(BuiltinLoc,
6848                           diag::err_convertvector_non_vector_type));
6849 
6850   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6851     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6852     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6853     if (SrcElts != DstElts)
6854       return ExprError(Diag(BuiltinLoc,
6855                             diag::err_convertvector_incompatible_vector)
6856                        << E->getSourceRange());
6857   }
6858 
6859   return new (Context)
6860       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6861 }
6862 
6863 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6864 // This is declared to take (const void*, ...) and can take two
6865 // optional constant int args.
6866 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6867   unsigned NumArgs = TheCall->getNumArgs();
6868 
6869   if (NumArgs > 3)
6870     return Diag(TheCall->getEndLoc(),
6871                 diag::err_typecheck_call_too_many_args_at_most)
6872            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6873 
6874   // Argument 0 is checked for us and the remaining arguments must be
6875   // constant integers.
6876   for (unsigned i = 1; i != NumArgs; ++i)
6877     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6878       return true;
6879 
6880   return false;
6881 }
6882 
6883 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
6884 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
6885   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6886     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6887            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6888   if (checkArgCount(*this, TheCall, 1))
6889     return true;
6890   Expr *Arg = TheCall->getArg(0);
6891   if (Arg->isInstantiationDependent())
6892     return false;
6893 
6894   QualType ArgTy = Arg->getType();
6895   if (!ArgTy->hasFloatingRepresentation())
6896     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6897            << ArgTy;
6898   if (Arg->isLValue()) {
6899     ExprResult FirstArg = DefaultLvalueConversion(Arg);
6900     TheCall->setArg(0, FirstArg.get());
6901   }
6902   TheCall->setType(TheCall->getArg(0)->getType());
6903   return false;
6904 }
6905 
6906 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6907 // __assume does not evaluate its arguments, and should warn if its argument
6908 // has side effects.
6909 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6910   Expr *Arg = TheCall->getArg(0);
6911   if (Arg->isInstantiationDependent()) return false;
6912 
6913   if (Arg->HasSideEffects(Context))
6914     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6915         << Arg->getSourceRange()
6916         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6917 
6918   return false;
6919 }
6920 
6921 /// Handle __builtin_alloca_with_align. This is declared
6922 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6923 /// than 8.
6924 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6925   // The alignment must be a constant integer.
6926   Expr *Arg = TheCall->getArg(1);
6927 
6928   // We can't check the value of a dependent argument.
6929   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6930     if (const auto *UE =
6931             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6932       if (UE->getKind() == UETT_AlignOf ||
6933           UE->getKind() == UETT_PreferredAlignOf)
6934         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6935             << Arg->getSourceRange();
6936 
6937     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6938 
6939     if (!Result.isPowerOf2())
6940       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6941              << Arg->getSourceRange();
6942 
6943     if (Result < Context.getCharWidth())
6944       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6945              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6946 
6947     if (Result > std::numeric_limits<int32_t>::max())
6948       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6949              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6950   }
6951 
6952   return false;
6953 }
6954 
6955 /// Handle __builtin_assume_aligned. This is declared
6956 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6957 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6958   unsigned NumArgs = TheCall->getNumArgs();
6959 
6960   if (NumArgs > 3)
6961     return Diag(TheCall->getEndLoc(),
6962                 diag::err_typecheck_call_too_many_args_at_most)
6963            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6964 
6965   // The alignment must be a constant integer.
6966   Expr *Arg = TheCall->getArg(1);
6967 
6968   // We can't check the value of a dependent argument.
6969   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6970     llvm::APSInt Result;
6971     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6972       return true;
6973 
6974     if (!Result.isPowerOf2())
6975       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6976              << Arg->getSourceRange();
6977 
6978     if (Result > Sema::MaximumAlignment)
6979       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6980           << Arg->getSourceRange() << Sema::MaximumAlignment;
6981   }
6982 
6983   if (NumArgs > 2) {
6984     ExprResult Arg(TheCall->getArg(2));
6985     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6986       Context.getSizeType(), false);
6987     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6988     if (Arg.isInvalid()) return true;
6989     TheCall->setArg(2, Arg.get());
6990   }
6991 
6992   return false;
6993 }
6994 
6995 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6996   unsigned BuiltinID =
6997       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6998   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6999 
7000   unsigned NumArgs = TheCall->getNumArgs();
7001   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
7002   if (NumArgs < NumRequiredArgs) {
7003     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
7004            << 0 /* function call */ << NumRequiredArgs << NumArgs
7005            << TheCall->getSourceRange();
7006   }
7007   if (NumArgs >= NumRequiredArgs + 0x100) {
7008     return Diag(TheCall->getEndLoc(),
7009                 diag::err_typecheck_call_too_many_args_at_most)
7010            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
7011            << TheCall->getSourceRange();
7012   }
7013   unsigned i = 0;
7014 
7015   // For formatting call, check buffer arg.
7016   if (!IsSizeCall) {
7017     ExprResult Arg(TheCall->getArg(i));
7018     InitializedEntity Entity = InitializedEntity::InitializeParameter(
7019         Context, Context.VoidPtrTy, false);
7020     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7021     if (Arg.isInvalid())
7022       return true;
7023     TheCall->setArg(i, Arg.get());
7024     i++;
7025   }
7026 
7027   // Check string literal arg.
7028   unsigned FormatIdx = i;
7029   {
7030     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
7031     if (Arg.isInvalid())
7032       return true;
7033     TheCall->setArg(i, Arg.get());
7034     i++;
7035   }
7036 
7037   // Make sure variadic args are scalar.
7038   unsigned FirstDataArg = i;
7039   while (i < NumArgs) {
7040     ExprResult Arg = DefaultVariadicArgumentPromotion(
7041         TheCall->getArg(i), VariadicFunction, nullptr);
7042     if (Arg.isInvalid())
7043       return true;
7044     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
7045     if (ArgSize.getQuantity() >= 0x100) {
7046       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
7047              << i << (int)ArgSize.getQuantity() << 0xff
7048              << TheCall->getSourceRange();
7049     }
7050     TheCall->setArg(i, Arg.get());
7051     i++;
7052   }
7053 
7054   // Check formatting specifiers. NOTE: We're only doing this for the non-size
7055   // call to avoid duplicate diagnostics.
7056   if (!IsSizeCall) {
7057     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
7058     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
7059     bool Success = CheckFormatArguments(
7060         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
7061         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
7062         CheckedVarArgs);
7063     if (!Success)
7064       return true;
7065   }
7066 
7067   if (IsSizeCall) {
7068     TheCall->setType(Context.getSizeType());
7069   } else {
7070     TheCall->setType(Context.VoidPtrTy);
7071   }
7072   return false;
7073 }
7074 
7075 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
7076 /// TheCall is a constant expression.
7077 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7078                                   llvm::APSInt &Result) {
7079   Expr *Arg = TheCall->getArg(ArgNum);
7080   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
7081   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
7082 
7083   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
7084 
7085   Optional<llvm::APSInt> R;
7086   if (!(R = Arg->getIntegerConstantExpr(Context)))
7087     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
7088            << FDecl->getDeclName() << Arg->getSourceRange();
7089   Result = *R;
7090   return false;
7091 }
7092 
7093 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
7094 /// TheCall is a constant expression in the range [Low, High].
7095 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
7096                                        int Low, int High, bool RangeIsError) {
7097   if (isConstantEvaluated())
7098     return false;
7099   llvm::APSInt Result;
7100 
7101   // We can't check the value of a dependent argument.
7102   Expr *Arg = TheCall->getArg(ArgNum);
7103   if (Arg->isTypeDependent() || Arg->isValueDependent())
7104     return false;
7105 
7106   // Check constant-ness first.
7107   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7108     return true;
7109 
7110   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7111     if (RangeIsError)
7112       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
7113              << toString(Result, 10) << Low << High << Arg->getSourceRange();
7114     else
7115       // Defer the warning until we know if the code will be emitted so that
7116       // dead code can ignore this.
7117       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
7118                           PDiag(diag::warn_argument_invalid_range)
7119                               << toString(Result, 10) << Low << High
7120                               << Arg->getSourceRange());
7121   }
7122 
7123   return false;
7124 }
7125 
7126 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
7127 /// TheCall is a constant expression is a multiple of Num..
7128 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
7129                                           unsigned Num) {
7130   llvm::APSInt Result;
7131 
7132   // We can't check the value of a dependent argument.
7133   Expr *Arg = TheCall->getArg(ArgNum);
7134   if (Arg->isTypeDependent() || Arg->isValueDependent())
7135     return false;
7136 
7137   // Check constant-ness first.
7138   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7139     return true;
7140 
7141   if (Result.getSExtValue() % Num != 0)
7142     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7143            << Num << Arg->getSourceRange();
7144 
7145   return false;
7146 }
7147 
7148 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7149 /// constant expression representing a power of 2.
7150 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7151   llvm::APSInt Result;
7152 
7153   // We can't check the value of a dependent argument.
7154   Expr *Arg = TheCall->getArg(ArgNum);
7155   if (Arg->isTypeDependent() || Arg->isValueDependent())
7156     return false;
7157 
7158   // Check constant-ness first.
7159   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7160     return true;
7161 
7162   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7163   // and only if x is a power of 2.
7164   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7165     return false;
7166 
7167   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7168          << Arg->getSourceRange();
7169 }
7170 
7171 static bool IsShiftedByte(llvm::APSInt Value) {
7172   if (Value.isNegative())
7173     return false;
7174 
7175   // Check if it's a shifted byte, by shifting it down
7176   while (true) {
7177     // If the value fits in the bottom byte, the check passes.
7178     if (Value < 0x100)
7179       return true;
7180 
7181     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7182     // fails.
7183     if ((Value & 0xFF) != 0)
7184       return false;
7185 
7186     // If the bottom 8 bits are all 0, but something above that is nonzero,
7187     // then shifting the value right by 8 bits won't affect whether it's a
7188     // shifted byte or not. So do that, and go round again.
7189     Value >>= 8;
7190   }
7191 }
7192 
7193 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7194 /// a constant expression representing an arbitrary byte value shifted left by
7195 /// a multiple of 8 bits.
7196 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7197                                              unsigned ArgBits) {
7198   llvm::APSInt Result;
7199 
7200   // We can't check the value of a dependent argument.
7201   Expr *Arg = TheCall->getArg(ArgNum);
7202   if (Arg->isTypeDependent() || Arg->isValueDependent())
7203     return false;
7204 
7205   // Check constant-ness first.
7206   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7207     return true;
7208 
7209   // Truncate to the given size.
7210   Result = Result.getLoBits(ArgBits);
7211   Result.setIsUnsigned(true);
7212 
7213   if (IsShiftedByte(Result))
7214     return false;
7215 
7216   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7217          << Arg->getSourceRange();
7218 }
7219 
7220 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7221 /// TheCall is a constant expression representing either a shifted byte value,
7222 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7223 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7224 /// Arm MVE intrinsics.
7225 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7226                                                    int ArgNum,
7227                                                    unsigned ArgBits) {
7228   llvm::APSInt Result;
7229 
7230   // We can't check the value of a dependent argument.
7231   Expr *Arg = TheCall->getArg(ArgNum);
7232   if (Arg->isTypeDependent() || Arg->isValueDependent())
7233     return false;
7234 
7235   // Check constant-ness first.
7236   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7237     return true;
7238 
7239   // Truncate to the given size.
7240   Result = Result.getLoBits(ArgBits);
7241   Result.setIsUnsigned(true);
7242 
7243   // Check to see if it's in either of the required forms.
7244   if (IsShiftedByte(Result) ||
7245       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7246     return false;
7247 
7248   return Diag(TheCall->getBeginLoc(),
7249               diag::err_argument_not_shifted_byte_or_xxff)
7250          << Arg->getSourceRange();
7251 }
7252 
7253 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7254 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7255   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7256     if (checkArgCount(*this, TheCall, 2))
7257       return true;
7258     Expr *Arg0 = TheCall->getArg(0);
7259     Expr *Arg1 = TheCall->getArg(1);
7260 
7261     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7262     if (FirstArg.isInvalid())
7263       return true;
7264     QualType FirstArgType = FirstArg.get()->getType();
7265     if (!FirstArgType->isAnyPointerType())
7266       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7267                << "first" << FirstArgType << Arg0->getSourceRange();
7268     TheCall->setArg(0, FirstArg.get());
7269 
7270     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7271     if (SecArg.isInvalid())
7272       return true;
7273     QualType SecArgType = SecArg.get()->getType();
7274     if (!SecArgType->isIntegerType())
7275       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7276                << "second" << SecArgType << Arg1->getSourceRange();
7277 
7278     // Derive the return type from the pointer argument.
7279     TheCall->setType(FirstArgType);
7280     return false;
7281   }
7282 
7283   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7284     if (checkArgCount(*this, TheCall, 2))
7285       return true;
7286 
7287     Expr *Arg0 = TheCall->getArg(0);
7288     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7289     if (FirstArg.isInvalid())
7290       return true;
7291     QualType FirstArgType = FirstArg.get()->getType();
7292     if (!FirstArgType->isAnyPointerType())
7293       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7294                << "first" << FirstArgType << Arg0->getSourceRange();
7295     TheCall->setArg(0, FirstArg.get());
7296 
7297     // Derive the return type from the pointer argument.
7298     TheCall->setType(FirstArgType);
7299 
7300     // Second arg must be an constant in range [0,15]
7301     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7302   }
7303 
7304   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7305     if (checkArgCount(*this, TheCall, 2))
7306       return true;
7307     Expr *Arg0 = TheCall->getArg(0);
7308     Expr *Arg1 = TheCall->getArg(1);
7309 
7310     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7311     if (FirstArg.isInvalid())
7312       return true;
7313     QualType FirstArgType = FirstArg.get()->getType();
7314     if (!FirstArgType->isAnyPointerType())
7315       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7316                << "first" << FirstArgType << Arg0->getSourceRange();
7317 
7318     QualType SecArgType = Arg1->getType();
7319     if (!SecArgType->isIntegerType())
7320       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7321                << "second" << SecArgType << Arg1->getSourceRange();
7322     TheCall->setType(Context.IntTy);
7323     return false;
7324   }
7325 
7326   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7327       BuiltinID == AArch64::BI__builtin_arm_stg) {
7328     if (checkArgCount(*this, TheCall, 1))
7329       return true;
7330     Expr *Arg0 = TheCall->getArg(0);
7331     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7332     if (FirstArg.isInvalid())
7333       return true;
7334 
7335     QualType FirstArgType = FirstArg.get()->getType();
7336     if (!FirstArgType->isAnyPointerType())
7337       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7338                << "first" << FirstArgType << Arg0->getSourceRange();
7339     TheCall->setArg(0, FirstArg.get());
7340 
7341     // Derive the return type from the pointer argument.
7342     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7343       TheCall->setType(FirstArgType);
7344     return false;
7345   }
7346 
7347   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7348     Expr *ArgA = TheCall->getArg(0);
7349     Expr *ArgB = TheCall->getArg(1);
7350 
7351     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7352     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7353 
7354     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7355       return true;
7356 
7357     QualType ArgTypeA = ArgExprA.get()->getType();
7358     QualType ArgTypeB = ArgExprB.get()->getType();
7359 
7360     auto isNull = [&] (Expr *E) -> bool {
7361       return E->isNullPointerConstant(
7362                         Context, Expr::NPC_ValueDependentIsNotNull); };
7363 
7364     // argument should be either a pointer or null
7365     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7366       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7367         << "first" << ArgTypeA << ArgA->getSourceRange();
7368 
7369     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7370       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7371         << "second" << ArgTypeB << ArgB->getSourceRange();
7372 
7373     // Ensure Pointee types are compatible
7374     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7375         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7376       QualType pointeeA = ArgTypeA->getPointeeType();
7377       QualType pointeeB = ArgTypeB->getPointeeType();
7378       if (!Context.typesAreCompatible(
7379              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7380              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7381         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7382           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7383           << ArgB->getSourceRange();
7384       }
7385     }
7386 
7387     // at least one argument should be pointer type
7388     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7389       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7390         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7391 
7392     if (isNull(ArgA)) // adopt type of the other pointer
7393       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7394 
7395     if (isNull(ArgB))
7396       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7397 
7398     TheCall->setArg(0, ArgExprA.get());
7399     TheCall->setArg(1, ArgExprB.get());
7400     TheCall->setType(Context.LongLongTy);
7401     return false;
7402   }
7403   assert(false && "Unhandled ARM MTE intrinsic");
7404   return true;
7405 }
7406 
7407 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7408 /// TheCall is an ARM/AArch64 special register string literal.
7409 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7410                                     int ArgNum, unsigned ExpectedFieldNum,
7411                                     bool AllowName) {
7412   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7413                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7414                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7415                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7416                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7417                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7418   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7419                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7420                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7421                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7422                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7423                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7424   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7425 
7426   // We can't check the value of a dependent argument.
7427   Expr *Arg = TheCall->getArg(ArgNum);
7428   if (Arg->isTypeDependent() || Arg->isValueDependent())
7429     return false;
7430 
7431   // Check if the argument is a string literal.
7432   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7433     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7434            << Arg->getSourceRange();
7435 
7436   // Check the type of special register given.
7437   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7438   SmallVector<StringRef, 6> Fields;
7439   Reg.split(Fields, ":");
7440 
7441   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7442     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7443            << Arg->getSourceRange();
7444 
7445   // If the string is the name of a register then we cannot check that it is
7446   // valid here but if the string is of one the forms described in ACLE then we
7447   // can check that the supplied fields are integers and within the valid
7448   // ranges.
7449   if (Fields.size() > 1) {
7450     bool FiveFields = Fields.size() == 5;
7451 
7452     bool ValidString = true;
7453     if (IsARMBuiltin) {
7454       ValidString &= Fields[0].startswith_insensitive("cp") ||
7455                      Fields[0].startswith_insensitive("p");
7456       if (ValidString)
7457         Fields[0] = Fields[0].drop_front(
7458             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7459 
7460       ValidString &= Fields[2].startswith_insensitive("c");
7461       if (ValidString)
7462         Fields[2] = Fields[2].drop_front(1);
7463 
7464       if (FiveFields) {
7465         ValidString &= Fields[3].startswith_insensitive("c");
7466         if (ValidString)
7467           Fields[3] = Fields[3].drop_front(1);
7468       }
7469     }
7470 
7471     SmallVector<int, 5> Ranges;
7472     if (FiveFields)
7473       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7474     else
7475       Ranges.append({15, 7, 15});
7476 
7477     for (unsigned i=0; i<Fields.size(); ++i) {
7478       int IntField;
7479       ValidString &= !Fields[i].getAsInteger(10, IntField);
7480       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7481     }
7482 
7483     if (!ValidString)
7484       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7485              << Arg->getSourceRange();
7486   } else if (IsAArch64Builtin && Fields.size() == 1) {
7487     // If the register name is one of those that appear in the condition below
7488     // and the special register builtin being used is one of the write builtins,
7489     // then we require that the argument provided for writing to the register
7490     // is an integer constant expression. This is because it will be lowered to
7491     // an MSR (immediate) instruction, so we need to know the immediate at
7492     // compile time.
7493     if (TheCall->getNumArgs() != 2)
7494       return false;
7495 
7496     std::string RegLower = Reg.lower();
7497     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7498         RegLower != "pan" && RegLower != "uao")
7499       return false;
7500 
7501     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7502   }
7503 
7504   return false;
7505 }
7506 
7507 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7508 /// Emit an error and return true on failure; return false on success.
7509 /// TypeStr is a string containing the type descriptor of the value returned by
7510 /// the builtin and the descriptors of the expected type of the arguments.
7511 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
7512                                  const char *TypeStr) {
7513 
7514   assert((TypeStr[0] != '\0') &&
7515          "Invalid types in PPC MMA builtin declaration");
7516 
7517   switch (BuiltinID) {
7518   default:
7519     // This function is called in CheckPPCBuiltinFunctionCall where the
7520     // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here
7521     // we are isolating the pair vector memop builtins that can be used with mma
7522     // off so the default case is every builtin that requires mma and paired
7523     // vector memops.
7524     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7525                          diag::err_ppc_builtin_only_on_arch, "10") ||
7526         SemaFeatureCheck(*this, TheCall, "mma",
7527                          diag::err_ppc_builtin_only_on_arch, "10"))
7528       return true;
7529     break;
7530   case PPC::BI__builtin_vsx_lxvp:
7531   case PPC::BI__builtin_vsx_stxvp:
7532   case PPC::BI__builtin_vsx_assemble_pair:
7533   case PPC::BI__builtin_vsx_disassemble_pair:
7534     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7535                          diag::err_ppc_builtin_only_on_arch, "10"))
7536       return true;
7537     break;
7538   }
7539 
7540   unsigned Mask = 0;
7541   unsigned ArgNum = 0;
7542 
7543   // The first type in TypeStr is the type of the value returned by the
7544   // builtin. So we first read that type and change the type of TheCall.
7545   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7546   TheCall->setType(type);
7547 
7548   while (*TypeStr != '\0') {
7549     Mask = 0;
7550     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7551     if (ArgNum >= TheCall->getNumArgs()) {
7552       ArgNum++;
7553       break;
7554     }
7555 
7556     Expr *Arg = TheCall->getArg(ArgNum);
7557     QualType PassedType = Arg->getType();
7558     QualType StrippedRVType = PassedType.getCanonicalType();
7559 
7560     // Strip Restrict/Volatile qualifiers.
7561     if (StrippedRVType.isRestrictQualified() ||
7562         StrippedRVType.isVolatileQualified())
7563       StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
7564 
7565     // The only case where the argument type and expected type are allowed to
7566     // mismatch is if the argument type is a non-void pointer (or array) and
7567     // expected type is a void pointer.
7568     if (StrippedRVType != ExpectedType)
7569       if (!(ExpectedType->isVoidPointerType() &&
7570             (StrippedRVType->isPointerType() || StrippedRVType->isArrayType())))
7571         return Diag(Arg->getBeginLoc(),
7572                     diag::err_typecheck_convert_incompatible)
7573                << PassedType << ExpectedType << 1 << 0 << 0;
7574 
7575     // If the value of the Mask is not 0, we have a constraint in the size of
7576     // the integer argument so here we ensure the argument is a constant that
7577     // is in the valid range.
7578     if (Mask != 0 &&
7579         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7580       return true;
7581 
7582     ArgNum++;
7583   }
7584 
7585   // In case we exited early from the previous loop, there are other types to
7586   // read from TypeStr. So we need to read them all to ensure we have the right
7587   // number of arguments in TheCall and if it is not the case, to display a
7588   // better error message.
7589   while (*TypeStr != '\0') {
7590     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7591     ArgNum++;
7592   }
7593   if (checkArgCount(*this, TheCall, ArgNum))
7594     return true;
7595 
7596   return false;
7597 }
7598 
7599 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7600 /// This checks that the target supports __builtin_longjmp and
7601 /// that val is a constant 1.
7602 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7603   if (!Context.getTargetInfo().hasSjLjLowering())
7604     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7605            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7606 
7607   Expr *Arg = TheCall->getArg(1);
7608   llvm::APSInt Result;
7609 
7610   // TODO: This is less than ideal. Overload this to take a value.
7611   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7612     return true;
7613 
7614   if (Result != 1)
7615     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7616            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7617 
7618   return false;
7619 }
7620 
7621 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7622 /// This checks that the target supports __builtin_setjmp.
7623 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7624   if (!Context.getTargetInfo().hasSjLjLowering())
7625     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7626            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7627   return false;
7628 }
7629 
7630 namespace {
7631 
7632 class UncoveredArgHandler {
7633   enum { Unknown = -1, AllCovered = -2 };
7634 
7635   signed FirstUncoveredArg = Unknown;
7636   SmallVector<const Expr *, 4> DiagnosticExprs;
7637 
7638 public:
7639   UncoveredArgHandler() = default;
7640 
7641   bool hasUncoveredArg() const {
7642     return (FirstUncoveredArg >= 0);
7643   }
7644 
7645   unsigned getUncoveredArg() const {
7646     assert(hasUncoveredArg() && "no uncovered argument");
7647     return FirstUncoveredArg;
7648   }
7649 
7650   void setAllCovered() {
7651     // A string has been found with all arguments covered, so clear out
7652     // the diagnostics.
7653     DiagnosticExprs.clear();
7654     FirstUncoveredArg = AllCovered;
7655   }
7656 
7657   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7658     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7659 
7660     // Don't update if a previous string covers all arguments.
7661     if (FirstUncoveredArg == AllCovered)
7662       return;
7663 
7664     // UncoveredArgHandler tracks the highest uncovered argument index
7665     // and with it all the strings that match this index.
7666     if (NewFirstUncoveredArg == FirstUncoveredArg)
7667       DiagnosticExprs.push_back(StrExpr);
7668     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7669       DiagnosticExprs.clear();
7670       DiagnosticExprs.push_back(StrExpr);
7671       FirstUncoveredArg = NewFirstUncoveredArg;
7672     }
7673   }
7674 
7675   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7676 };
7677 
7678 enum StringLiteralCheckType {
7679   SLCT_NotALiteral,
7680   SLCT_UncheckedLiteral,
7681   SLCT_CheckedLiteral
7682 };
7683 
7684 } // namespace
7685 
7686 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7687                                      BinaryOperatorKind BinOpKind,
7688                                      bool AddendIsRight) {
7689   unsigned BitWidth = Offset.getBitWidth();
7690   unsigned AddendBitWidth = Addend.getBitWidth();
7691   // There might be negative interim results.
7692   if (Addend.isUnsigned()) {
7693     Addend = Addend.zext(++AddendBitWidth);
7694     Addend.setIsSigned(true);
7695   }
7696   // Adjust the bit width of the APSInts.
7697   if (AddendBitWidth > BitWidth) {
7698     Offset = Offset.sext(AddendBitWidth);
7699     BitWidth = AddendBitWidth;
7700   } else if (BitWidth > AddendBitWidth) {
7701     Addend = Addend.sext(BitWidth);
7702   }
7703 
7704   bool Ov = false;
7705   llvm::APSInt ResOffset = Offset;
7706   if (BinOpKind == BO_Add)
7707     ResOffset = Offset.sadd_ov(Addend, Ov);
7708   else {
7709     assert(AddendIsRight && BinOpKind == BO_Sub &&
7710            "operator must be add or sub with addend on the right");
7711     ResOffset = Offset.ssub_ov(Addend, Ov);
7712   }
7713 
7714   // We add an offset to a pointer here so we should support an offset as big as
7715   // possible.
7716   if (Ov) {
7717     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7718            "index (intermediate) result too big");
7719     Offset = Offset.sext(2 * BitWidth);
7720     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7721     return;
7722   }
7723 
7724   Offset = ResOffset;
7725 }
7726 
7727 namespace {
7728 
7729 // This is a wrapper class around StringLiteral to support offsetted string
7730 // literals as format strings. It takes the offset into account when returning
7731 // the string and its length or the source locations to display notes correctly.
7732 class FormatStringLiteral {
7733   const StringLiteral *FExpr;
7734   int64_t Offset;
7735 
7736  public:
7737   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7738       : FExpr(fexpr), Offset(Offset) {}
7739 
7740   StringRef getString() const {
7741     return FExpr->getString().drop_front(Offset);
7742   }
7743 
7744   unsigned getByteLength() const {
7745     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7746   }
7747 
7748   unsigned getLength() const { return FExpr->getLength() - Offset; }
7749   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7750 
7751   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7752 
7753   QualType getType() const { return FExpr->getType(); }
7754 
7755   bool isAscii() const { return FExpr->isAscii(); }
7756   bool isWide() const { return FExpr->isWide(); }
7757   bool isUTF8() const { return FExpr->isUTF8(); }
7758   bool isUTF16() const { return FExpr->isUTF16(); }
7759   bool isUTF32() const { return FExpr->isUTF32(); }
7760   bool isPascal() const { return FExpr->isPascal(); }
7761 
7762   SourceLocation getLocationOfByte(
7763       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7764       const TargetInfo &Target, unsigned *StartToken = nullptr,
7765       unsigned *StartTokenByteOffset = nullptr) const {
7766     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7767                                     StartToken, StartTokenByteOffset);
7768   }
7769 
7770   SourceLocation getBeginLoc() const LLVM_READONLY {
7771     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7772   }
7773 
7774   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7775 };
7776 
7777 }  // namespace
7778 
7779 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7780                               const Expr *OrigFormatExpr,
7781                               ArrayRef<const Expr *> Args,
7782                               bool HasVAListArg, unsigned format_idx,
7783                               unsigned firstDataArg,
7784                               Sema::FormatStringType Type,
7785                               bool inFunctionCall,
7786                               Sema::VariadicCallType CallType,
7787                               llvm::SmallBitVector &CheckedVarArgs,
7788                               UncoveredArgHandler &UncoveredArg,
7789                               bool IgnoreStringsWithoutSpecifiers);
7790 
7791 // Determine if an expression is a string literal or constant string.
7792 // If this function returns false on the arguments to a function expecting a
7793 // format string, we will usually need to emit a warning.
7794 // True string literals are then checked by CheckFormatString.
7795 static StringLiteralCheckType
7796 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7797                       bool HasVAListArg, unsigned format_idx,
7798                       unsigned firstDataArg, Sema::FormatStringType Type,
7799                       Sema::VariadicCallType CallType, bool InFunctionCall,
7800                       llvm::SmallBitVector &CheckedVarArgs,
7801                       UncoveredArgHandler &UncoveredArg,
7802                       llvm::APSInt Offset,
7803                       bool IgnoreStringsWithoutSpecifiers = false) {
7804   if (S.isConstantEvaluated())
7805     return SLCT_NotALiteral;
7806  tryAgain:
7807   assert(Offset.isSigned() && "invalid offset");
7808 
7809   if (E->isTypeDependent() || E->isValueDependent())
7810     return SLCT_NotALiteral;
7811 
7812   E = E->IgnoreParenCasts();
7813 
7814   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7815     // Technically -Wformat-nonliteral does not warn about this case.
7816     // The behavior of printf and friends in this case is implementation
7817     // dependent.  Ideally if the format string cannot be null then
7818     // it should have a 'nonnull' attribute in the function prototype.
7819     return SLCT_UncheckedLiteral;
7820 
7821   switch (E->getStmtClass()) {
7822   case Stmt::BinaryConditionalOperatorClass:
7823   case Stmt::ConditionalOperatorClass: {
7824     // The expression is a literal if both sub-expressions were, and it was
7825     // completely checked only if both sub-expressions were checked.
7826     const AbstractConditionalOperator *C =
7827         cast<AbstractConditionalOperator>(E);
7828 
7829     // Determine whether it is necessary to check both sub-expressions, for
7830     // example, because the condition expression is a constant that can be
7831     // evaluated at compile time.
7832     bool CheckLeft = true, CheckRight = true;
7833 
7834     bool Cond;
7835     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7836                                                  S.isConstantEvaluated())) {
7837       if (Cond)
7838         CheckRight = false;
7839       else
7840         CheckLeft = false;
7841     }
7842 
7843     // We need to maintain the offsets for the right and the left hand side
7844     // separately to check if every possible indexed expression is a valid
7845     // string literal. They might have different offsets for different string
7846     // literals in the end.
7847     StringLiteralCheckType Left;
7848     if (!CheckLeft)
7849       Left = SLCT_UncheckedLiteral;
7850     else {
7851       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7852                                    HasVAListArg, format_idx, firstDataArg,
7853                                    Type, CallType, InFunctionCall,
7854                                    CheckedVarArgs, UncoveredArg, Offset,
7855                                    IgnoreStringsWithoutSpecifiers);
7856       if (Left == SLCT_NotALiteral || !CheckRight) {
7857         return Left;
7858       }
7859     }
7860 
7861     StringLiteralCheckType Right = checkFormatStringExpr(
7862         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7863         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7864         IgnoreStringsWithoutSpecifiers);
7865 
7866     return (CheckLeft && Left < Right) ? Left : Right;
7867   }
7868 
7869   case Stmt::ImplicitCastExprClass:
7870     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7871     goto tryAgain;
7872 
7873   case Stmt::OpaqueValueExprClass:
7874     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7875       E = src;
7876       goto tryAgain;
7877     }
7878     return SLCT_NotALiteral;
7879 
7880   case Stmt::PredefinedExprClass:
7881     // While __func__, etc., are technically not string literals, they
7882     // cannot contain format specifiers and thus are not a security
7883     // liability.
7884     return SLCT_UncheckedLiteral;
7885 
7886   case Stmt::DeclRefExprClass: {
7887     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7888 
7889     // As an exception, do not flag errors for variables binding to
7890     // const string literals.
7891     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7892       bool isConstant = false;
7893       QualType T = DR->getType();
7894 
7895       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7896         isConstant = AT->getElementType().isConstant(S.Context);
7897       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7898         isConstant = T.isConstant(S.Context) &&
7899                      PT->getPointeeType().isConstant(S.Context);
7900       } else if (T->isObjCObjectPointerType()) {
7901         // In ObjC, there is usually no "const ObjectPointer" type,
7902         // so don't check if the pointee type is constant.
7903         isConstant = T.isConstant(S.Context);
7904       }
7905 
7906       if (isConstant) {
7907         if (const Expr *Init = VD->getAnyInitializer()) {
7908           // Look through initializers like const char c[] = { "foo" }
7909           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7910             if (InitList->isStringLiteralInit())
7911               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7912           }
7913           return checkFormatStringExpr(S, Init, Args,
7914                                        HasVAListArg, format_idx,
7915                                        firstDataArg, Type, CallType,
7916                                        /*InFunctionCall*/ false, CheckedVarArgs,
7917                                        UncoveredArg, Offset);
7918         }
7919       }
7920 
7921       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7922       // special check to see if the format string is a function parameter
7923       // of the function calling the printf function.  If the function
7924       // has an attribute indicating it is a printf-like function, then we
7925       // should suppress warnings concerning non-literals being used in a call
7926       // to a vprintf function.  For example:
7927       //
7928       // void
7929       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7930       //      va_list ap;
7931       //      va_start(ap, fmt);
7932       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7933       //      ...
7934       // }
7935       if (HasVAListArg) {
7936         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7937           if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) {
7938             int PVIndex = PV->getFunctionScopeIndex() + 1;
7939             for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7940               // adjust for implicit parameter
7941               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
7942                 if (MD->isInstance())
7943                   ++PVIndex;
7944               // We also check if the formats are compatible.
7945               // We can't pass a 'scanf' string to a 'printf' function.
7946               if (PVIndex == PVFormat->getFormatIdx() &&
7947                   Type == S.GetFormatStringType(PVFormat))
7948                 return SLCT_UncheckedLiteral;
7949             }
7950           }
7951         }
7952       }
7953     }
7954 
7955     return SLCT_NotALiteral;
7956   }
7957 
7958   case Stmt::CallExprClass:
7959   case Stmt::CXXMemberCallExprClass: {
7960     const CallExpr *CE = cast<CallExpr>(E);
7961     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7962       bool IsFirst = true;
7963       StringLiteralCheckType CommonResult;
7964       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7965         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7966         StringLiteralCheckType Result = checkFormatStringExpr(
7967             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7968             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7969             IgnoreStringsWithoutSpecifiers);
7970         if (IsFirst) {
7971           CommonResult = Result;
7972           IsFirst = false;
7973         }
7974       }
7975       if (!IsFirst)
7976         return CommonResult;
7977 
7978       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7979         unsigned BuiltinID = FD->getBuiltinID();
7980         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7981             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7982           const Expr *Arg = CE->getArg(0);
7983           return checkFormatStringExpr(S, Arg, Args,
7984                                        HasVAListArg, format_idx,
7985                                        firstDataArg, Type, CallType,
7986                                        InFunctionCall, CheckedVarArgs,
7987                                        UncoveredArg, Offset,
7988                                        IgnoreStringsWithoutSpecifiers);
7989         }
7990       }
7991     }
7992 
7993     return SLCT_NotALiteral;
7994   }
7995   case Stmt::ObjCMessageExprClass: {
7996     const auto *ME = cast<ObjCMessageExpr>(E);
7997     if (const auto *MD = ME->getMethodDecl()) {
7998       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7999         // As a special case heuristic, if we're using the method -[NSBundle
8000         // localizedStringForKey:value:table:], ignore any key strings that lack
8001         // format specifiers. The idea is that if the key doesn't have any
8002         // format specifiers then its probably just a key to map to the
8003         // localized strings. If it does have format specifiers though, then its
8004         // likely that the text of the key is the format string in the
8005         // programmer's language, and should be checked.
8006         const ObjCInterfaceDecl *IFace;
8007         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
8008             IFace->getIdentifier()->isStr("NSBundle") &&
8009             MD->getSelector().isKeywordSelector(
8010                 {"localizedStringForKey", "value", "table"})) {
8011           IgnoreStringsWithoutSpecifiers = true;
8012         }
8013 
8014         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
8015         return checkFormatStringExpr(
8016             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8017             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8018             IgnoreStringsWithoutSpecifiers);
8019       }
8020     }
8021 
8022     return SLCT_NotALiteral;
8023   }
8024   case Stmt::ObjCStringLiteralClass:
8025   case Stmt::StringLiteralClass: {
8026     const StringLiteral *StrE = nullptr;
8027 
8028     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
8029       StrE = ObjCFExpr->getString();
8030     else
8031       StrE = cast<StringLiteral>(E);
8032 
8033     if (StrE) {
8034       if (Offset.isNegative() || Offset > StrE->getLength()) {
8035         // TODO: It would be better to have an explicit warning for out of
8036         // bounds literals.
8037         return SLCT_NotALiteral;
8038       }
8039       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
8040       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
8041                         firstDataArg, Type, InFunctionCall, CallType,
8042                         CheckedVarArgs, UncoveredArg,
8043                         IgnoreStringsWithoutSpecifiers);
8044       return SLCT_CheckedLiteral;
8045     }
8046 
8047     return SLCT_NotALiteral;
8048   }
8049   case Stmt::BinaryOperatorClass: {
8050     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
8051 
8052     // A string literal + an int offset is still a string literal.
8053     if (BinOp->isAdditiveOp()) {
8054       Expr::EvalResult LResult, RResult;
8055 
8056       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
8057           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8058       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
8059           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8060 
8061       if (LIsInt != RIsInt) {
8062         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
8063 
8064         if (LIsInt) {
8065           if (BinOpKind == BO_Add) {
8066             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
8067             E = BinOp->getRHS();
8068             goto tryAgain;
8069           }
8070         } else {
8071           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
8072           E = BinOp->getLHS();
8073           goto tryAgain;
8074         }
8075       }
8076     }
8077 
8078     return SLCT_NotALiteral;
8079   }
8080   case Stmt::UnaryOperatorClass: {
8081     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
8082     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
8083     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
8084       Expr::EvalResult IndexResult;
8085       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
8086                                        Expr::SE_NoSideEffects,
8087                                        S.isConstantEvaluated())) {
8088         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
8089                    /*RHS is int*/ true);
8090         E = ASE->getBase();
8091         goto tryAgain;
8092       }
8093     }
8094 
8095     return SLCT_NotALiteral;
8096   }
8097 
8098   default:
8099     return SLCT_NotALiteral;
8100   }
8101 }
8102 
8103 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
8104   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
8105       .Case("scanf", FST_Scanf)
8106       .Cases("printf", "printf0", FST_Printf)
8107       .Cases("NSString", "CFString", FST_NSString)
8108       .Case("strftime", FST_Strftime)
8109       .Case("strfmon", FST_Strfmon)
8110       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
8111       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
8112       .Case("os_trace", FST_OSLog)
8113       .Case("os_log", FST_OSLog)
8114       .Default(FST_Unknown);
8115 }
8116 
8117 /// CheckFormatArguments - Check calls to printf and scanf (and similar
8118 /// functions) for correct use of format strings.
8119 /// Returns true if a format string has been fully checked.
8120 bool Sema::CheckFormatArguments(const FormatAttr *Format,
8121                                 ArrayRef<const Expr *> Args,
8122                                 bool IsCXXMember,
8123                                 VariadicCallType CallType,
8124                                 SourceLocation Loc, SourceRange Range,
8125                                 llvm::SmallBitVector &CheckedVarArgs) {
8126   FormatStringInfo FSI;
8127   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
8128     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
8129                                 FSI.FirstDataArg, GetFormatStringType(Format),
8130                                 CallType, Loc, Range, CheckedVarArgs);
8131   return false;
8132 }
8133 
8134 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8135                                 bool HasVAListArg, unsigned format_idx,
8136                                 unsigned firstDataArg, FormatStringType Type,
8137                                 VariadicCallType CallType,
8138                                 SourceLocation Loc, SourceRange Range,
8139                                 llvm::SmallBitVector &CheckedVarArgs) {
8140   // CHECK: printf/scanf-like function is called with no format string.
8141   if (format_idx >= Args.size()) {
8142     Diag(Loc, diag::warn_missing_format_string) << Range;
8143     return false;
8144   }
8145 
8146   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8147 
8148   // CHECK: format string is not a string literal.
8149   //
8150   // Dynamically generated format strings are difficult to
8151   // automatically vet at compile time.  Requiring that format strings
8152   // are string literals: (1) permits the checking of format strings by
8153   // the compiler and thereby (2) can practically remove the source of
8154   // many format string exploits.
8155 
8156   // Format string can be either ObjC string (e.g. @"%d") or
8157   // C string (e.g. "%d")
8158   // ObjC string uses the same format specifiers as C string, so we can use
8159   // the same format string checking logic for both ObjC and C strings.
8160   UncoveredArgHandler UncoveredArg;
8161   StringLiteralCheckType CT =
8162       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8163                             format_idx, firstDataArg, Type, CallType,
8164                             /*IsFunctionCall*/ true, CheckedVarArgs,
8165                             UncoveredArg,
8166                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8167 
8168   // Generate a diagnostic where an uncovered argument is detected.
8169   if (UncoveredArg.hasUncoveredArg()) {
8170     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8171     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8172     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8173   }
8174 
8175   if (CT != SLCT_NotALiteral)
8176     // Literal format string found, check done!
8177     return CT == SLCT_CheckedLiteral;
8178 
8179   // Strftime is particular as it always uses a single 'time' argument,
8180   // so it is safe to pass a non-literal string.
8181   if (Type == FST_Strftime)
8182     return false;
8183 
8184   // Do not emit diag when the string param is a macro expansion and the
8185   // format is either NSString or CFString. This is a hack to prevent
8186   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8187   // which are usually used in place of NS and CF string literals.
8188   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8189   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8190     return false;
8191 
8192   // If there are no arguments specified, warn with -Wformat-security, otherwise
8193   // warn only with -Wformat-nonliteral.
8194   if (Args.size() == firstDataArg) {
8195     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8196       << OrigFormatExpr->getSourceRange();
8197     switch (Type) {
8198     default:
8199       break;
8200     case FST_Kprintf:
8201     case FST_FreeBSDKPrintf:
8202     case FST_Printf:
8203       Diag(FormatLoc, diag::note_format_security_fixit)
8204         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8205       break;
8206     case FST_NSString:
8207       Diag(FormatLoc, diag::note_format_security_fixit)
8208         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8209       break;
8210     }
8211   } else {
8212     Diag(FormatLoc, diag::warn_format_nonliteral)
8213       << OrigFormatExpr->getSourceRange();
8214   }
8215   return false;
8216 }
8217 
8218 namespace {
8219 
8220 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8221 protected:
8222   Sema &S;
8223   const FormatStringLiteral *FExpr;
8224   const Expr *OrigFormatExpr;
8225   const Sema::FormatStringType FSType;
8226   const unsigned FirstDataArg;
8227   const unsigned NumDataArgs;
8228   const char *Beg; // Start of format string.
8229   const bool HasVAListArg;
8230   ArrayRef<const Expr *> Args;
8231   unsigned FormatIdx;
8232   llvm::SmallBitVector CoveredArgs;
8233   bool usesPositionalArgs = false;
8234   bool atFirstArg = true;
8235   bool inFunctionCall;
8236   Sema::VariadicCallType CallType;
8237   llvm::SmallBitVector &CheckedVarArgs;
8238   UncoveredArgHandler &UncoveredArg;
8239 
8240 public:
8241   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8242                      const Expr *origFormatExpr,
8243                      const Sema::FormatStringType type, unsigned firstDataArg,
8244                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8245                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8246                      bool inFunctionCall, Sema::VariadicCallType callType,
8247                      llvm::SmallBitVector &CheckedVarArgs,
8248                      UncoveredArgHandler &UncoveredArg)
8249       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8250         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8251         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8252         inFunctionCall(inFunctionCall), CallType(callType),
8253         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8254     CoveredArgs.resize(numDataArgs);
8255     CoveredArgs.reset();
8256   }
8257 
8258   void DoneProcessing();
8259 
8260   void HandleIncompleteSpecifier(const char *startSpecifier,
8261                                  unsigned specifierLen) override;
8262 
8263   void HandleInvalidLengthModifier(
8264                            const analyze_format_string::FormatSpecifier &FS,
8265                            const analyze_format_string::ConversionSpecifier &CS,
8266                            const char *startSpecifier, unsigned specifierLen,
8267                            unsigned DiagID);
8268 
8269   void HandleNonStandardLengthModifier(
8270                     const analyze_format_string::FormatSpecifier &FS,
8271                     const char *startSpecifier, unsigned specifierLen);
8272 
8273   void HandleNonStandardConversionSpecifier(
8274                     const analyze_format_string::ConversionSpecifier &CS,
8275                     const char *startSpecifier, unsigned specifierLen);
8276 
8277   void HandlePosition(const char *startPos, unsigned posLen) override;
8278 
8279   void HandleInvalidPosition(const char *startSpecifier,
8280                              unsigned specifierLen,
8281                              analyze_format_string::PositionContext p) override;
8282 
8283   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8284 
8285   void HandleNullChar(const char *nullCharacter) override;
8286 
8287   template <typename Range>
8288   static void
8289   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8290                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8291                        bool IsStringLocation, Range StringRange,
8292                        ArrayRef<FixItHint> Fixit = None);
8293 
8294 protected:
8295   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8296                                         const char *startSpec,
8297                                         unsigned specifierLen,
8298                                         const char *csStart, unsigned csLen);
8299 
8300   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8301                                          const char *startSpec,
8302                                          unsigned specifierLen);
8303 
8304   SourceRange getFormatStringRange();
8305   CharSourceRange getSpecifierRange(const char *startSpecifier,
8306                                     unsigned specifierLen);
8307   SourceLocation getLocationOfByte(const char *x);
8308 
8309   const Expr *getDataArg(unsigned i) const;
8310 
8311   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8312                     const analyze_format_string::ConversionSpecifier &CS,
8313                     const char *startSpecifier, unsigned specifierLen,
8314                     unsigned argIndex);
8315 
8316   template <typename Range>
8317   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8318                             bool IsStringLocation, Range StringRange,
8319                             ArrayRef<FixItHint> Fixit = None);
8320 };
8321 
8322 } // namespace
8323 
8324 SourceRange CheckFormatHandler::getFormatStringRange() {
8325   return OrigFormatExpr->getSourceRange();
8326 }
8327 
8328 CharSourceRange CheckFormatHandler::
8329 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8330   SourceLocation Start = getLocationOfByte(startSpecifier);
8331   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8332 
8333   // Advance the end SourceLocation by one due to half-open ranges.
8334   End = End.getLocWithOffset(1);
8335 
8336   return CharSourceRange::getCharRange(Start, End);
8337 }
8338 
8339 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8340   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8341                                   S.getLangOpts(), S.Context.getTargetInfo());
8342 }
8343 
8344 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8345                                                    unsigned specifierLen){
8346   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8347                        getLocationOfByte(startSpecifier),
8348                        /*IsStringLocation*/true,
8349                        getSpecifierRange(startSpecifier, specifierLen));
8350 }
8351 
8352 void CheckFormatHandler::HandleInvalidLengthModifier(
8353     const analyze_format_string::FormatSpecifier &FS,
8354     const analyze_format_string::ConversionSpecifier &CS,
8355     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8356   using namespace analyze_format_string;
8357 
8358   const LengthModifier &LM = FS.getLengthModifier();
8359   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8360 
8361   // See if we know how to fix this length modifier.
8362   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8363   if (FixedLM) {
8364     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8365                          getLocationOfByte(LM.getStart()),
8366                          /*IsStringLocation*/true,
8367                          getSpecifierRange(startSpecifier, specifierLen));
8368 
8369     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8370       << FixedLM->toString()
8371       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8372 
8373   } else {
8374     FixItHint Hint;
8375     if (DiagID == diag::warn_format_nonsensical_length)
8376       Hint = FixItHint::CreateRemoval(LMRange);
8377 
8378     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8379                          getLocationOfByte(LM.getStart()),
8380                          /*IsStringLocation*/true,
8381                          getSpecifierRange(startSpecifier, specifierLen),
8382                          Hint);
8383   }
8384 }
8385 
8386 void CheckFormatHandler::HandleNonStandardLengthModifier(
8387     const analyze_format_string::FormatSpecifier &FS,
8388     const char *startSpecifier, unsigned specifierLen) {
8389   using namespace analyze_format_string;
8390 
8391   const LengthModifier &LM = FS.getLengthModifier();
8392   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8393 
8394   // See if we know how to fix this length modifier.
8395   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8396   if (FixedLM) {
8397     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8398                            << LM.toString() << 0,
8399                          getLocationOfByte(LM.getStart()),
8400                          /*IsStringLocation*/true,
8401                          getSpecifierRange(startSpecifier, specifierLen));
8402 
8403     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8404       << FixedLM->toString()
8405       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8406 
8407   } else {
8408     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8409                            << LM.toString() << 0,
8410                          getLocationOfByte(LM.getStart()),
8411                          /*IsStringLocation*/true,
8412                          getSpecifierRange(startSpecifier, specifierLen));
8413   }
8414 }
8415 
8416 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8417     const analyze_format_string::ConversionSpecifier &CS,
8418     const char *startSpecifier, unsigned specifierLen) {
8419   using namespace analyze_format_string;
8420 
8421   // See if we know how to fix this conversion specifier.
8422   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8423   if (FixedCS) {
8424     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8425                           << CS.toString() << /*conversion specifier*/1,
8426                          getLocationOfByte(CS.getStart()),
8427                          /*IsStringLocation*/true,
8428                          getSpecifierRange(startSpecifier, specifierLen));
8429 
8430     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8431     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8432       << FixedCS->toString()
8433       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8434   } else {
8435     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8436                           << CS.toString() << /*conversion specifier*/1,
8437                          getLocationOfByte(CS.getStart()),
8438                          /*IsStringLocation*/true,
8439                          getSpecifierRange(startSpecifier, specifierLen));
8440   }
8441 }
8442 
8443 void CheckFormatHandler::HandlePosition(const char *startPos,
8444                                         unsigned posLen) {
8445   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8446                                getLocationOfByte(startPos),
8447                                /*IsStringLocation*/true,
8448                                getSpecifierRange(startPos, posLen));
8449 }
8450 
8451 void
8452 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8453                                      analyze_format_string::PositionContext p) {
8454   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8455                          << (unsigned) p,
8456                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8457                        getSpecifierRange(startPos, posLen));
8458 }
8459 
8460 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8461                                             unsigned posLen) {
8462   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8463                                getLocationOfByte(startPos),
8464                                /*IsStringLocation*/true,
8465                                getSpecifierRange(startPos, posLen));
8466 }
8467 
8468 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8469   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8470     // The presence of a null character is likely an error.
8471     EmitFormatDiagnostic(
8472       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8473       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8474       getFormatStringRange());
8475   }
8476 }
8477 
8478 // Note that this may return NULL if there was an error parsing or building
8479 // one of the argument expressions.
8480 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8481   return Args[FirstDataArg + i];
8482 }
8483 
8484 void CheckFormatHandler::DoneProcessing() {
8485   // Does the number of data arguments exceed the number of
8486   // format conversions in the format string?
8487   if (!HasVAListArg) {
8488       // Find any arguments that weren't covered.
8489     CoveredArgs.flip();
8490     signed notCoveredArg = CoveredArgs.find_first();
8491     if (notCoveredArg >= 0) {
8492       assert((unsigned)notCoveredArg < NumDataArgs);
8493       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8494     } else {
8495       UncoveredArg.setAllCovered();
8496     }
8497   }
8498 }
8499 
8500 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8501                                    const Expr *ArgExpr) {
8502   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8503          "Invalid state");
8504 
8505   if (!ArgExpr)
8506     return;
8507 
8508   SourceLocation Loc = ArgExpr->getBeginLoc();
8509 
8510   if (S.getSourceManager().isInSystemMacro(Loc))
8511     return;
8512 
8513   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8514   for (auto E : DiagnosticExprs)
8515     PDiag << E->getSourceRange();
8516 
8517   CheckFormatHandler::EmitFormatDiagnostic(
8518                                   S, IsFunctionCall, DiagnosticExprs[0],
8519                                   PDiag, Loc, /*IsStringLocation*/false,
8520                                   DiagnosticExprs[0]->getSourceRange());
8521 }
8522 
8523 bool
8524 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8525                                                      SourceLocation Loc,
8526                                                      const char *startSpec,
8527                                                      unsigned specifierLen,
8528                                                      const char *csStart,
8529                                                      unsigned csLen) {
8530   bool keepGoing = true;
8531   if (argIndex < NumDataArgs) {
8532     // Consider the argument coverered, even though the specifier doesn't
8533     // make sense.
8534     CoveredArgs.set(argIndex);
8535   }
8536   else {
8537     // If argIndex exceeds the number of data arguments we
8538     // don't issue a warning because that is just a cascade of warnings (and
8539     // they may have intended '%%' anyway). We don't want to continue processing
8540     // the format string after this point, however, as we will like just get
8541     // gibberish when trying to match arguments.
8542     keepGoing = false;
8543   }
8544 
8545   StringRef Specifier(csStart, csLen);
8546 
8547   // If the specifier in non-printable, it could be the first byte of a UTF-8
8548   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8549   // hex value.
8550   std::string CodePointStr;
8551   if (!llvm::sys::locale::isPrint(*csStart)) {
8552     llvm::UTF32 CodePoint;
8553     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8554     const llvm::UTF8 *E =
8555         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8556     llvm::ConversionResult Result =
8557         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8558 
8559     if (Result != llvm::conversionOK) {
8560       unsigned char FirstChar = *csStart;
8561       CodePoint = (llvm::UTF32)FirstChar;
8562     }
8563 
8564     llvm::raw_string_ostream OS(CodePointStr);
8565     if (CodePoint < 256)
8566       OS << "\\x" << llvm::format("%02x", CodePoint);
8567     else if (CodePoint <= 0xFFFF)
8568       OS << "\\u" << llvm::format("%04x", CodePoint);
8569     else
8570       OS << "\\U" << llvm::format("%08x", CodePoint);
8571     OS.flush();
8572     Specifier = CodePointStr;
8573   }
8574 
8575   EmitFormatDiagnostic(
8576       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8577       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8578 
8579   return keepGoing;
8580 }
8581 
8582 void
8583 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8584                                                       const char *startSpec,
8585                                                       unsigned specifierLen) {
8586   EmitFormatDiagnostic(
8587     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8588     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8589 }
8590 
8591 bool
8592 CheckFormatHandler::CheckNumArgs(
8593   const analyze_format_string::FormatSpecifier &FS,
8594   const analyze_format_string::ConversionSpecifier &CS,
8595   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8596 
8597   if (argIndex >= NumDataArgs) {
8598     PartialDiagnostic PDiag = FS.usesPositionalArg()
8599       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8600            << (argIndex+1) << NumDataArgs)
8601       : S.PDiag(diag::warn_printf_insufficient_data_args);
8602     EmitFormatDiagnostic(
8603       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8604       getSpecifierRange(startSpecifier, specifierLen));
8605 
8606     // Since more arguments than conversion tokens are given, by extension
8607     // all arguments are covered, so mark this as so.
8608     UncoveredArg.setAllCovered();
8609     return false;
8610   }
8611   return true;
8612 }
8613 
8614 template<typename Range>
8615 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8616                                               SourceLocation Loc,
8617                                               bool IsStringLocation,
8618                                               Range StringRange,
8619                                               ArrayRef<FixItHint> FixIt) {
8620   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8621                        Loc, IsStringLocation, StringRange, FixIt);
8622 }
8623 
8624 /// If the format string is not within the function call, emit a note
8625 /// so that the function call and string are in diagnostic messages.
8626 ///
8627 /// \param InFunctionCall if true, the format string is within the function
8628 /// call and only one diagnostic message will be produced.  Otherwise, an
8629 /// extra note will be emitted pointing to location of the format string.
8630 ///
8631 /// \param ArgumentExpr the expression that is passed as the format string
8632 /// argument in the function call.  Used for getting locations when two
8633 /// diagnostics are emitted.
8634 ///
8635 /// \param PDiag the callee should already have provided any strings for the
8636 /// diagnostic message.  This function only adds locations and fixits
8637 /// to diagnostics.
8638 ///
8639 /// \param Loc primary location for diagnostic.  If two diagnostics are
8640 /// required, one will be at Loc and a new SourceLocation will be created for
8641 /// the other one.
8642 ///
8643 /// \param IsStringLocation if true, Loc points to the format string should be
8644 /// used for the note.  Otherwise, Loc points to the argument list and will
8645 /// be used with PDiag.
8646 ///
8647 /// \param StringRange some or all of the string to highlight.  This is
8648 /// templated so it can accept either a CharSourceRange or a SourceRange.
8649 ///
8650 /// \param FixIt optional fix it hint for the format string.
8651 template <typename Range>
8652 void CheckFormatHandler::EmitFormatDiagnostic(
8653     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8654     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8655     Range StringRange, ArrayRef<FixItHint> FixIt) {
8656   if (InFunctionCall) {
8657     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8658     D << StringRange;
8659     D << FixIt;
8660   } else {
8661     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8662       << ArgumentExpr->getSourceRange();
8663 
8664     const Sema::SemaDiagnosticBuilder &Note =
8665       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8666              diag::note_format_string_defined);
8667 
8668     Note << StringRange;
8669     Note << FixIt;
8670   }
8671 }
8672 
8673 //===--- CHECK: Printf format string checking ------------------------------===//
8674 
8675 namespace {
8676 
8677 class CheckPrintfHandler : public CheckFormatHandler {
8678 public:
8679   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8680                      const Expr *origFormatExpr,
8681                      const Sema::FormatStringType type, unsigned firstDataArg,
8682                      unsigned numDataArgs, bool isObjC, const char *beg,
8683                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8684                      unsigned formatIdx, bool inFunctionCall,
8685                      Sema::VariadicCallType CallType,
8686                      llvm::SmallBitVector &CheckedVarArgs,
8687                      UncoveredArgHandler &UncoveredArg)
8688       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8689                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8690                            inFunctionCall, CallType, CheckedVarArgs,
8691                            UncoveredArg) {}
8692 
8693   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8694 
8695   /// Returns true if '%@' specifiers are allowed in the format string.
8696   bool allowsObjCArg() const {
8697     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8698            FSType == Sema::FST_OSTrace;
8699   }
8700 
8701   bool HandleInvalidPrintfConversionSpecifier(
8702                                       const analyze_printf::PrintfSpecifier &FS,
8703                                       const char *startSpecifier,
8704                                       unsigned specifierLen) override;
8705 
8706   void handleInvalidMaskType(StringRef MaskType) override;
8707 
8708   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8709                              const char *startSpecifier,
8710                              unsigned specifierLen) override;
8711   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8712                        const char *StartSpecifier,
8713                        unsigned SpecifierLen,
8714                        const Expr *E);
8715 
8716   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8717                     const char *startSpecifier, unsigned specifierLen);
8718   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8719                            const analyze_printf::OptionalAmount &Amt,
8720                            unsigned type,
8721                            const char *startSpecifier, unsigned specifierLen);
8722   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8723                   const analyze_printf::OptionalFlag &flag,
8724                   const char *startSpecifier, unsigned specifierLen);
8725   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8726                          const analyze_printf::OptionalFlag &ignoredFlag,
8727                          const analyze_printf::OptionalFlag &flag,
8728                          const char *startSpecifier, unsigned specifierLen);
8729   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8730                            const Expr *E);
8731 
8732   void HandleEmptyObjCModifierFlag(const char *startFlag,
8733                                    unsigned flagLen) override;
8734 
8735   void HandleInvalidObjCModifierFlag(const char *startFlag,
8736                                             unsigned flagLen) override;
8737 
8738   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8739                                            const char *flagsEnd,
8740                                            const char *conversionPosition)
8741                                              override;
8742 };
8743 
8744 } // namespace
8745 
8746 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8747                                       const analyze_printf::PrintfSpecifier &FS,
8748                                       const char *startSpecifier,
8749                                       unsigned specifierLen) {
8750   const analyze_printf::PrintfConversionSpecifier &CS =
8751     FS.getConversionSpecifier();
8752 
8753   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8754                                           getLocationOfByte(CS.getStart()),
8755                                           startSpecifier, specifierLen,
8756                                           CS.getStart(), CS.getLength());
8757 }
8758 
8759 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8760   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8761 }
8762 
8763 bool CheckPrintfHandler::HandleAmount(
8764                                const analyze_format_string::OptionalAmount &Amt,
8765                                unsigned k, const char *startSpecifier,
8766                                unsigned specifierLen) {
8767   if (Amt.hasDataArgument()) {
8768     if (!HasVAListArg) {
8769       unsigned argIndex = Amt.getArgIndex();
8770       if (argIndex >= NumDataArgs) {
8771         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8772                                << k,
8773                              getLocationOfByte(Amt.getStart()),
8774                              /*IsStringLocation*/true,
8775                              getSpecifierRange(startSpecifier, specifierLen));
8776         // Don't do any more checking.  We will just emit
8777         // spurious errors.
8778         return false;
8779       }
8780 
8781       // Type check the data argument.  It should be an 'int'.
8782       // Although not in conformance with C99, we also allow the argument to be
8783       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8784       // doesn't emit a warning for that case.
8785       CoveredArgs.set(argIndex);
8786       const Expr *Arg = getDataArg(argIndex);
8787       if (!Arg)
8788         return false;
8789 
8790       QualType T = Arg->getType();
8791 
8792       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8793       assert(AT.isValid());
8794 
8795       if (!AT.matchesType(S.Context, T)) {
8796         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8797                                << k << AT.getRepresentativeTypeName(S.Context)
8798                                << T << Arg->getSourceRange(),
8799                              getLocationOfByte(Amt.getStart()),
8800                              /*IsStringLocation*/true,
8801                              getSpecifierRange(startSpecifier, specifierLen));
8802         // Don't do any more checking.  We will just emit
8803         // spurious errors.
8804         return false;
8805       }
8806     }
8807   }
8808   return true;
8809 }
8810 
8811 void CheckPrintfHandler::HandleInvalidAmount(
8812                                       const analyze_printf::PrintfSpecifier &FS,
8813                                       const analyze_printf::OptionalAmount &Amt,
8814                                       unsigned type,
8815                                       const char *startSpecifier,
8816                                       unsigned specifierLen) {
8817   const analyze_printf::PrintfConversionSpecifier &CS =
8818     FS.getConversionSpecifier();
8819 
8820   FixItHint fixit =
8821     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8822       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8823                                  Amt.getConstantLength()))
8824       : FixItHint();
8825 
8826   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8827                          << type << CS.toString(),
8828                        getLocationOfByte(Amt.getStart()),
8829                        /*IsStringLocation*/true,
8830                        getSpecifierRange(startSpecifier, specifierLen),
8831                        fixit);
8832 }
8833 
8834 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8835                                     const analyze_printf::OptionalFlag &flag,
8836                                     const char *startSpecifier,
8837                                     unsigned specifierLen) {
8838   // Warn about pointless flag with a fixit removal.
8839   const analyze_printf::PrintfConversionSpecifier &CS =
8840     FS.getConversionSpecifier();
8841   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8842                          << flag.toString() << CS.toString(),
8843                        getLocationOfByte(flag.getPosition()),
8844                        /*IsStringLocation*/true,
8845                        getSpecifierRange(startSpecifier, specifierLen),
8846                        FixItHint::CreateRemoval(
8847                          getSpecifierRange(flag.getPosition(), 1)));
8848 }
8849 
8850 void CheckPrintfHandler::HandleIgnoredFlag(
8851                                 const analyze_printf::PrintfSpecifier &FS,
8852                                 const analyze_printf::OptionalFlag &ignoredFlag,
8853                                 const analyze_printf::OptionalFlag &flag,
8854                                 const char *startSpecifier,
8855                                 unsigned specifierLen) {
8856   // Warn about ignored flag with a fixit removal.
8857   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8858                          << ignoredFlag.toString() << flag.toString(),
8859                        getLocationOfByte(ignoredFlag.getPosition()),
8860                        /*IsStringLocation*/true,
8861                        getSpecifierRange(startSpecifier, specifierLen),
8862                        FixItHint::CreateRemoval(
8863                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8864 }
8865 
8866 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8867                                                      unsigned flagLen) {
8868   // Warn about an empty flag.
8869   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8870                        getLocationOfByte(startFlag),
8871                        /*IsStringLocation*/true,
8872                        getSpecifierRange(startFlag, flagLen));
8873 }
8874 
8875 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8876                                                        unsigned flagLen) {
8877   // Warn about an invalid flag.
8878   auto Range = getSpecifierRange(startFlag, flagLen);
8879   StringRef flag(startFlag, flagLen);
8880   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8881                       getLocationOfByte(startFlag),
8882                       /*IsStringLocation*/true,
8883                       Range, FixItHint::CreateRemoval(Range));
8884 }
8885 
8886 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8887     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8888     // Warn about using '[...]' without a '@' conversion.
8889     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8890     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8891     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8892                          getLocationOfByte(conversionPosition),
8893                          /*IsStringLocation*/true,
8894                          Range, FixItHint::CreateRemoval(Range));
8895 }
8896 
8897 // Determines if the specified is a C++ class or struct containing
8898 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8899 // "c_str()").
8900 template<typename MemberKind>
8901 static llvm::SmallPtrSet<MemberKind*, 1>
8902 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8903   const RecordType *RT = Ty->getAs<RecordType>();
8904   llvm::SmallPtrSet<MemberKind*, 1> Results;
8905 
8906   if (!RT)
8907     return Results;
8908   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8909   if (!RD || !RD->getDefinition())
8910     return Results;
8911 
8912   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8913                  Sema::LookupMemberName);
8914   R.suppressDiagnostics();
8915 
8916   // We just need to include all members of the right kind turned up by the
8917   // filter, at this point.
8918   if (S.LookupQualifiedName(R, RT->getDecl()))
8919     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8920       NamedDecl *decl = (*I)->getUnderlyingDecl();
8921       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8922         Results.insert(FK);
8923     }
8924   return Results;
8925 }
8926 
8927 /// Check if we could call '.c_str()' on an object.
8928 ///
8929 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8930 /// allow the call, or if it would be ambiguous).
8931 bool Sema::hasCStrMethod(const Expr *E) {
8932   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8933 
8934   MethodSet Results =
8935       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8936   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8937        MI != ME; ++MI)
8938     if ((*MI)->getMinRequiredArguments() == 0)
8939       return true;
8940   return false;
8941 }
8942 
8943 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8944 // better diagnostic if so. AT is assumed to be valid.
8945 // Returns true when a c_str() conversion method is found.
8946 bool CheckPrintfHandler::checkForCStrMembers(
8947     const analyze_printf::ArgType &AT, const Expr *E) {
8948   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8949 
8950   MethodSet Results =
8951       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8952 
8953   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8954        MI != ME; ++MI) {
8955     const CXXMethodDecl *Method = *MI;
8956     if (Method->getMinRequiredArguments() == 0 &&
8957         AT.matchesType(S.Context, Method->getReturnType())) {
8958       // FIXME: Suggest parens if the expression needs them.
8959       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8960       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8961           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8962       return true;
8963     }
8964   }
8965 
8966   return false;
8967 }
8968 
8969 bool
8970 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8971                                             &FS,
8972                                           const char *startSpecifier,
8973                                           unsigned specifierLen) {
8974   using namespace analyze_format_string;
8975   using namespace analyze_printf;
8976 
8977   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8978 
8979   if (FS.consumesDataArgument()) {
8980     if (atFirstArg) {
8981         atFirstArg = false;
8982         usesPositionalArgs = FS.usesPositionalArg();
8983     }
8984     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8985       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8986                                         startSpecifier, specifierLen);
8987       return false;
8988     }
8989   }
8990 
8991   // First check if the field width, precision, and conversion specifier
8992   // have matching data arguments.
8993   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8994                     startSpecifier, specifierLen)) {
8995     return false;
8996   }
8997 
8998   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8999                     startSpecifier, specifierLen)) {
9000     return false;
9001   }
9002 
9003   if (!CS.consumesDataArgument()) {
9004     // FIXME: Technically specifying a precision or field width here
9005     // makes no sense.  Worth issuing a warning at some point.
9006     return true;
9007   }
9008 
9009   // Consume the argument.
9010   unsigned argIndex = FS.getArgIndex();
9011   if (argIndex < NumDataArgs) {
9012     // The check to see if the argIndex is valid will come later.
9013     // We set the bit here because we may exit early from this
9014     // function if we encounter some other error.
9015     CoveredArgs.set(argIndex);
9016   }
9017 
9018   // FreeBSD kernel extensions.
9019   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9020       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9021     // We need at least two arguments.
9022     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9023       return false;
9024 
9025     // Claim the second argument.
9026     CoveredArgs.set(argIndex + 1);
9027 
9028     // Type check the first argument (int for %b, pointer for %D)
9029     const Expr *Ex = getDataArg(argIndex);
9030     const analyze_printf::ArgType &AT =
9031       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
9032         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
9033     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9034       EmitFormatDiagnostic(
9035           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9036               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9037               << false << Ex->getSourceRange(),
9038           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9039           getSpecifierRange(startSpecifier, specifierLen));
9040 
9041     // Type check the second argument (char * for both %b and %D)
9042     Ex = getDataArg(argIndex + 1);
9043     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
9044     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9045       EmitFormatDiagnostic(
9046           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9047               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9048               << false << Ex->getSourceRange(),
9049           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9050           getSpecifierRange(startSpecifier, specifierLen));
9051 
9052      return true;
9053   }
9054 
9055   // Check for using an Objective-C specific conversion specifier
9056   // in a non-ObjC literal.
9057   if (!allowsObjCArg() && CS.isObjCArg()) {
9058     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9059                                                   specifierLen);
9060   }
9061 
9062   // %P can only be used with os_log.
9063   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
9064     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9065                                                   specifierLen);
9066   }
9067 
9068   // %n is not allowed with os_log.
9069   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
9070     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9071                          getLocationOfByte(CS.getStart()),
9072                          /*IsStringLocation*/ false,
9073                          getSpecifierRange(startSpecifier, specifierLen));
9074 
9075     return true;
9076   }
9077 
9078   // Only scalars are allowed for os_trace.
9079   if (FSType == Sema::FST_OSTrace &&
9080       (CS.getKind() == ConversionSpecifier::PArg ||
9081        CS.getKind() == ConversionSpecifier::sArg ||
9082        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9083     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9084                                                   specifierLen);
9085   }
9086 
9087   // Check for use of public/private annotation outside of os_log().
9088   if (FSType != Sema::FST_OSLog) {
9089     if (FS.isPublic().isSet()) {
9090       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9091                                << "public",
9092                            getLocationOfByte(FS.isPublic().getPosition()),
9093                            /*IsStringLocation*/ false,
9094                            getSpecifierRange(startSpecifier, specifierLen));
9095     }
9096     if (FS.isPrivate().isSet()) {
9097       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9098                                << "private",
9099                            getLocationOfByte(FS.isPrivate().getPosition()),
9100                            /*IsStringLocation*/ false,
9101                            getSpecifierRange(startSpecifier, specifierLen));
9102     }
9103   }
9104 
9105   // Check for invalid use of field width
9106   if (!FS.hasValidFieldWidth()) {
9107     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9108         startSpecifier, specifierLen);
9109   }
9110 
9111   // Check for invalid use of precision
9112   if (!FS.hasValidPrecision()) {
9113     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9114         startSpecifier, specifierLen);
9115   }
9116 
9117   // Precision is mandatory for %P specifier.
9118   if (CS.getKind() == ConversionSpecifier::PArg &&
9119       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9120     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9121                          getLocationOfByte(startSpecifier),
9122                          /*IsStringLocation*/ false,
9123                          getSpecifierRange(startSpecifier, specifierLen));
9124   }
9125 
9126   // Check each flag does not conflict with any other component.
9127   if (!FS.hasValidThousandsGroupingPrefix())
9128     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9129   if (!FS.hasValidLeadingZeros())
9130     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9131   if (!FS.hasValidPlusPrefix())
9132     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9133   if (!FS.hasValidSpacePrefix())
9134     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9135   if (!FS.hasValidAlternativeForm())
9136     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9137   if (!FS.hasValidLeftJustified())
9138     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9139 
9140   // Check that flags are not ignored by another flag
9141   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9142     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9143         startSpecifier, specifierLen);
9144   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9145     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9146             startSpecifier, specifierLen);
9147 
9148   // Check the length modifier is valid with the given conversion specifier.
9149   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9150                                  S.getLangOpts()))
9151     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9152                                 diag::warn_format_nonsensical_length);
9153   else if (!FS.hasStandardLengthModifier())
9154     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9155   else if (!FS.hasStandardLengthConversionCombination())
9156     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9157                                 diag::warn_format_non_standard_conversion_spec);
9158 
9159   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9160     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9161 
9162   // The remaining checks depend on the data arguments.
9163   if (HasVAListArg)
9164     return true;
9165 
9166   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9167     return false;
9168 
9169   const Expr *Arg = getDataArg(argIndex);
9170   if (!Arg)
9171     return true;
9172 
9173   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9174 }
9175 
9176 static bool requiresParensToAddCast(const Expr *E) {
9177   // FIXME: We should have a general way to reason about operator
9178   // precedence and whether parens are actually needed here.
9179   // Take care of a few common cases where they aren't.
9180   const Expr *Inside = E->IgnoreImpCasts();
9181   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9182     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9183 
9184   switch (Inside->getStmtClass()) {
9185   case Stmt::ArraySubscriptExprClass:
9186   case Stmt::CallExprClass:
9187   case Stmt::CharacterLiteralClass:
9188   case Stmt::CXXBoolLiteralExprClass:
9189   case Stmt::DeclRefExprClass:
9190   case Stmt::FloatingLiteralClass:
9191   case Stmt::IntegerLiteralClass:
9192   case Stmt::MemberExprClass:
9193   case Stmt::ObjCArrayLiteralClass:
9194   case Stmt::ObjCBoolLiteralExprClass:
9195   case Stmt::ObjCBoxedExprClass:
9196   case Stmt::ObjCDictionaryLiteralClass:
9197   case Stmt::ObjCEncodeExprClass:
9198   case Stmt::ObjCIvarRefExprClass:
9199   case Stmt::ObjCMessageExprClass:
9200   case Stmt::ObjCPropertyRefExprClass:
9201   case Stmt::ObjCStringLiteralClass:
9202   case Stmt::ObjCSubscriptRefExprClass:
9203   case Stmt::ParenExprClass:
9204   case Stmt::StringLiteralClass:
9205   case Stmt::UnaryOperatorClass:
9206     return false;
9207   default:
9208     return true;
9209   }
9210 }
9211 
9212 static std::pair<QualType, StringRef>
9213 shouldNotPrintDirectly(const ASTContext &Context,
9214                        QualType IntendedTy,
9215                        const Expr *E) {
9216   // Use a 'while' to peel off layers of typedefs.
9217   QualType TyTy = IntendedTy;
9218   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9219     StringRef Name = UserTy->getDecl()->getName();
9220     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9221       .Case("CFIndex", Context.getNSIntegerType())
9222       .Case("NSInteger", Context.getNSIntegerType())
9223       .Case("NSUInteger", Context.getNSUIntegerType())
9224       .Case("SInt32", Context.IntTy)
9225       .Case("UInt32", Context.UnsignedIntTy)
9226       .Default(QualType());
9227 
9228     if (!CastTy.isNull())
9229       return std::make_pair(CastTy, Name);
9230 
9231     TyTy = UserTy->desugar();
9232   }
9233 
9234   // Strip parens if necessary.
9235   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9236     return shouldNotPrintDirectly(Context,
9237                                   PE->getSubExpr()->getType(),
9238                                   PE->getSubExpr());
9239 
9240   // If this is a conditional expression, then its result type is constructed
9241   // via usual arithmetic conversions and thus there might be no necessary
9242   // typedef sugar there.  Recurse to operands to check for NSInteger &
9243   // Co. usage condition.
9244   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9245     QualType TrueTy, FalseTy;
9246     StringRef TrueName, FalseName;
9247 
9248     std::tie(TrueTy, TrueName) =
9249       shouldNotPrintDirectly(Context,
9250                              CO->getTrueExpr()->getType(),
9251                              CO->getTrueExpr());
9252     std::tie(FalseTy, FalseName) =
9253       shouldNotPrintDirectly(Context,
9254                              CO->getFalseExpr()->getType(),
9255                              CO->getFalseExpr());
9256 
9257     if (TrueTy == FalseTy)
9258       return std::make_pair(TrueTy, TrueName);
9259     else if (TrueTy.isNull())
9260       return std::make_pair(FalseTy, FalseName);
9261     else if (FalseTy.isNull())
9262       return std::make_pair(TrueTy, TrueName);
9263   }
9264 
9265   return std::make_pair(QualType(), StringRef());
9266 }
9267 
9268 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9269 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9270 /// type do not count.
9271 static bool
9272 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9273   QualType From = ICE->getSubExpr()->getType();
9274   QualType To = ICE->getType();
9275   // It's an integer promotion if the destination type is the promoted
9276   // source type.
9277   if (ICE->getCastKind() == CK_IntegralCast &&
9278       From->isPromotableIntegerType() &&
9279       S.Context.getPromotedIntegerType(From) == To)
9280     return true;
9281   // Look through vector types, since we do default argument promotion for
9282   // those in OpenCL.
9283   if (const auto *VecTy = From->getAs<ExtVectorType>())
9284     From = VecTy->getElementType();
9285   if (const auto *VecTy = To->getAs<ExtVectorType>())
9286     To = VecTy->getElementType();
9287   // It's a floating promotion if the source type is a lower rank.
9288   return ICE->getCastKind() == CK_FloatingCast &&
9289          S.Context.getFloatingTypeOrder(From, To) < 0;
9290 }
9291 
9292 bool
9293 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9294                                     const char *StartSpecifier,
9295                                     unsigned SpecifierLen,
9296                                     const Expr *E) {
9297   using namespace analyze_format_string;
9298   using namespace analyze_printf;
9299 
9300   // Now type check the data expression that matches the
9301   // format specifier.
9302   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9303   if (!AT.isValid())
9304     return true;
9305 
9306   QualType ExprTy = E->getType();
9307   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9308     ExprTy = TET->getUnderlyingExpr()->getType();
9309   }
9310 
9311   // Diagnose attempts to print a boolean value as a character. Unlike other
9312   // -Wformat diagnostics, this is fine from a type perspective, but it still
9313   // doesn't make sense.
9314   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9315       E->isKnownToHaveBooleanValue()) {
9316     const CharSourceRange &CSR =
9317         getSpecifierRange(StartSpecifier, SpecifierLen);
9318     SmallString<4> FSString;
9319     llvm::raw_svector_ostream os(FSString);
9320     FS.toString(os);
9321     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9322                              << FSString,
9323                          E->getExprLoc(), false, CSR);
9324     return true;
9325   }
9326 
9327   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9328   if (Match == analyze_printf::ArgType::Match)
9329     return true;
9330 
9331   // Look through argument promotions for our error message's reported type.
9332   // This includes the integral and floating promotions, but excludes array
9333   // and function pointer decay (seeing that an argument intended to be a
9334   // string has type 'char [6]' is probably more confusing than 'char *') and
9335   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9336   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9337     if (isArithmeticArgumentPromotion(S, ICE)) {
9338       E = ICE->getSubExpr();
9339       ExprTy = E->getType();
9340 
9341       // Check if we didn't match because of an implicit cast from a 'char'
9342       // or 'short' to an 'int'.  This is done because printf is a varargs
9343       // function.
9344       if (ICE->getType() == S.Context.IntTy ||
9345           ICE->getType() == S.Context.UnsignedIntTy) {
9346         // All further checking is done on the subexpression
9347         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9348             AT.matchesType(S.Context, ExprTy);
9349         if (ImplicitMatch == analyze_printf::ArgType::Match)
9350           return true;
9351         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9352             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9353           Match = ImplicitMatch;
9354       }
9355     }
9356   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9357     // Special case for 'a', which has type 'int' in C.
9358     // Note, however, that we do /not/ want to treat multibyte constants like
9359     // 'MooV' as characters! This form is deprecated but still exists. In
9360     // addition, don't treat expressions as of type 'char' if one byte length
9361     // modifier is provided.
9362     if (ExprTy == S.Context.IntTy &&
9363         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9364       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9365         ExprTy = S.Context.CharTy;
9366   }
9367 
9368   // Look through enums to their underlying type.
9369   bool IsEnum = false;
9370   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9371     ExprTy = EnumTy->getDecl()->getIntegerType();
9372     IsEnum = true;
9373   }
9374 
9375   // %C in an Objective-C context prints a unichar, not a wchar_t.
9376   // If the argument is an integer of some kind, believe the %C and suggest
9377   // a cast instead of changing the conversion specifier.
9378   QualType IntendedTy = ExprTy;
9379   if (isObjCContext() &&
9380       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9381     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9382         !ExprTy->isCharType()) {
9383       // 'unichar' is defined as a typedef of unsigned short, but we should
9384       // prefer using the typedef if it is visible.
9385       IntendedTy = S.Context.UnsignedShortTy;
9386 
9387       // While we are here, check if the value is an IntegerLiteral that happens
9388       // to be within the valid range.
9389       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9390         const llvm::APInt &V = IL->getValue();
9391         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9392           return true;
9393       }
9394 
9395       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9396                           Sema::LookupOrdinaryName);
9397       if (S.LookupName(Result, S.getCurScope())) {
9398         NamedDecl *ND = Result.getFoundDecl();
9399         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9400           if (TD->getUnderlyingType() == IntendedTy)
9401             IntendedTy = S.Context.getTypedefType(TD);
9402       }
9403     }
9404   }
9405 
9406   // Special-case some of Darwin's platform-independence types by suggesting
9407   // casts to primitive types that are known to be large enough.
9408   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9409   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9410     QualType CastTy;
9411     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9412     if (!CastTy.isNull()) {
9413       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9414       // (long in ASTContext). Only complain to pedants.
9415       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9416           (AT.isSizeT() || AT.isPtrdiffT()) &&
9417           AT.matchesType(S.Context, CastTy))
9418         Match = ArgType::NoMatchPedantic;
9419       IntendedTy = CastTy;
9420       ShouldNotPrintDirectly = true;
9421     }
9422   }
9423 
9424   // We may be able to offer a FixItHint if it is a supported type.
9425   PrintfSpecifier fixedFS = FS;
9426   bool Success =
9427       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9428 
9429   if (Success) {
9430     // Get the fix string from the fixed format specifier
9431     SmallString<16> buf;
9432     llvm::raw_svector_ostream os(buf);
9433     fixedFS.toString(os);
9434 
9435     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9436 
9437     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9438       unsigned Diag;
9439       switch (Match) {
9440       case ArgType::Match: llvm_unreachable("expected non-matching");
9441       case ArgType::NoMatchPedantic:
9442         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9443         break;
9444       case ArgType::NoMatchTypeConfusion:
9445         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9446         break;
9447       case ArgType::NoMatch:
9448         Diag = diag::warn_format_conversion_argument_type_mismatch;
9449         break;
9450       }
9451 
9452       // In this case, the specifier is wrong and should be changed to match
9453       // the argument.
9454       EmitFormatDiagnostic(S.PDiag(Diag)
9455                                << AT.getRepresentativeTypeName(S.Context)
9456                                << IntendedTy << IsEnum << E->getSourceRange(),
9457                            E->getBeginLoc(),
9458                            /*IsStringLocation*/ false, SpecRange,
9459                            FixItHint::CreateReplacement(SpecRange, os.str()));
9460     } else {
9461       // The canonical type for formatting this value is different from the
9462       // actual type of the expression. (This occurs, for example, with Darwin's
9463       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9464       // should be printed as 'long' for 64-bit compatibility.)
9465       // Rather than emitting a normal format/argument mismatch, we want to
9466       // add a cast to the recommended type (and correct the format string
9467       // if necessary).
9468       SmallString<16> CastBuf;
9469       llvm::raw_svector_ostream CastFix(CastBuf);
9470       CastFix << "(";
9471       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9472       CastFix << ")";
9473 
9474       SmallVector<FixItHint,4> Hints;
9475       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9476         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9477 
9478       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9479         // If there's already a cast present, just replace it.
9480         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9481         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9482 
9483       } else if (!requiresParensToAddCast(E)) {
9484         // If the expression has high enough precedence,
9485         // just write the C-style cast.
9486         Hints.push_back(
9487             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9488       } else {
9489         // Otherwise, add parens around the expression as well as the cast.
9490         CastFix << "(";
9491         Hints.push_back(
9492             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9493 
9494         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9495         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9496       }
9497 
9498       if (ShouldNotPrintDirectly) {
9499         // The expression has a type that should not be printed directly.
9500         // We extract the name from the typedef because we don't want to show
9501         // the underlying type in the diagnostic.
9502         StringRef Name;
9503         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9504           Name = TypedefTy->getDecl()->getName();
9505         else
9506           Name = CastTyName;
9507         unsigned Diag = Match == ArgType::NoMatchPedantic
9508                             ? diag::warn_format_argument_needs_cast_pedantic
9509                             : diag::warn_format_argument_needs_cast;
9510         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9511                                            << E->getSourceRange(),
9512                              E->getBeginLoc(), /*IsStringLocation=*/false,
9513                              SpecRange, Hints);
9514       } else {
9515         // In this case, the expression could be printed using a different
9516         // specifier, but we've decided that the specifier is probably correct
9517         // and we should cast instead. Just use the normal warning message.
9518         EmitFormatDiagnostic(
9519             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9520                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9521                 << E->getSourceRange(),
9522             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9523       }
9524     }
9525   } else {
9526     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9527                                                    SpecifierLen);
9528     // Since the warning for passing non-POD types to variadic functions
9529     // was deferred until now, we emit a warning for non-POD
9530     // arguments here.
9531     switch (S.isValidVarArgType(ExprTy)) {
9532     case Sema::VAK_Valid:
9533     case Sema::VAK_ValidInCXX11: {
9534       unsigned Diag;
9535       switch (Match) {
9536       case ArgType::Match: llvm_unreachable("expected non-matching");
9537       case ArgType::NoMatchPedantic:
9538         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9539         break;
9540       case ArgType::NoMatchTypeConfusion:
9541         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9542         break;
9543       case ArgType::NoMatch:
9544         Diag = diag::warn_format_conversion_argument_type_mismatch;
9545         break;
9546       }
9547 
9548       EmitFormatDiagnostic(
9549           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9550                         << IsEnum << CSR << E->getSourceRange(),
9551           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9552       break;
9553     }
9554     case Sema::VAK_Undefined:
9555     case Sema::VAK_MSVCUndefined:
9556       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9557                                << S.getLangOpts().CPlusPlus11 << ExprTy
9558                                << CallType
9559                                << AT.getRepresentativeTypeName(S.Context) << CSR
9560                                << E->getSourceRange(),
9561                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9562       checkForCStrMembers(AT, E);
9563       break;
9564 
9565     case Sema::VAK_Invalid:
9566       if (ExprTy->isObjCObjectType())
9567         EmitFormatDiagnostic(
9568             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9569                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9570                 << AT.getRepresentativeTypeName(S.Context) << CSR
9571                 << E->getSourceRange(),
9572             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9573       else
9574         // FIXME: If this is an initializer list, suggest removing the braces
9575         // or inserting a cast to the target type.
9576         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9577             << isa<InitListExpr>(E) << ExprTy << CallType
9578             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9579       break;
9580     }
9581 
9582     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9583            "format string specifier index out of range");
9584     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9585   }
9586 
9587   return true;
9588 }
9589 
9590 //===--- CHECK: Scanf format string checking ------------------------------===//
9591 
9592 namespace {
9593 
9594 class CheckScanfHandler : public CheckFormatHandler {
9595 public:
9596   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9597                     const Expr *origFormatExpr, Sema::FormatStringType type,
9598                     unsigned firstDataArg, unsigned numDataArgs,
9599                     const char *beg, bool hasVAListArg,
9600                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9601                     bool inFunctionCall, Sema::VariadicCallType CallType,
9602                     llvm::SmallBitVector &CheckedVarArgs,
9603                     UncoveredArgHandler &UncoveredArg)
9604       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9605                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9606                            inFunctionCall, CallType, CheckedVarArgs,
9607                            UncoveredArg) {}
9608 
9609   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9610                             const char *startSpecifier,
9611                             unsigned specifierLen) override;
9612 
9613   bool HandleInvalidScanfConversionSpecifier(
9614           const analyze_scanf::ScanfSpecifier &FS,
9615           const char *startSpecifier,
9616           unsigned specifierLen) override;
9617 
9618   void HandleIncompleteScanList(const char *start, const char *end) override;
9619 };
9620 
9621 } // namespace
9622 
9623 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9624                                                  const char *end) {
9625   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9626                        getLocationOfByte(end), /*IsStringLocation*/true,
9627                        getSpecifierRange(start, end - start));
9628 }
9629 
9630 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9631                                         const analyze_scanf::ScanfSpecifier &FS,
9632                                         const char *startSpecifier,
9633                                         unsigned specifierLen) {
9634   const analyze_scanf::ScanfConversionSpecifier &CS =
9635     FS.getConversionSpecifier();
9636 
9637   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9638                                           getLocationOfByte(CS.getStart()),
9639                                           startSpecifier, specifierLen,
9640                                           CS.getStart(), CS.getLength());
9641 }
9642 
9643 bool CheckScanfHandler::HandleScanfSpecifier(
9644                                        const analyze_scanf::ScanfSpecifier &FS,
9645                                        const char *startSpecifier,
9646                                        unsigned specifierLen) {
9647   using namespace analyze_scanf;
9648   using namespace analyze_format_string;
9649 
9650   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9651 
9652   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9653   // be used to decide if we are using positional arguments consistently.
9654   if (FS.consumesDataArgument()) {
9655     if (atFirstArg) {
9656       atFirstArg = false;
9657       usesPositionalArgs = FS.usesPositionalArg();
9658     }
9659     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9660       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9661                                         startSpecifier, specifierLen);
9662       return false;
9663     }
9664   }
9665 
9666   // Check if the field with is non-zero.
9667   const OptionalAmount &Amt = FS.getFieldWidth();
9668   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9669     if (Amt.getConstantAmount() == 0) {
9670       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9671                                                    Amt.getConstantLength());
9672       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9673                            getLocationOfByte(Amt.getStart()),
9674                            /*IsStringLocation*/true, R,
9675                            FixItHint::CreateRemoval(R));
9676     }
9677   }
9678 
9679   if (!FS.consumesDataArgument()) {
9680     // FIXME: Technically specifying a precision or field width here
9681     // makes no sense.  Worth issuing a warning at some point.
9682     return true;
9683   }
9684 
9685   // Consume the argument.
9686   unsigned argIndex = FS.getArgIndex();
9687   if (argIndex < NumDataArgs) {
9688       // The check to see if the argIndex is valid will come later.
9689       // We set the bit here because we may exit early from this
9690       // function if we encounter some other error.
9691     CoveredArgs.set(argIndex);
9692   }
9693 
9694   // Check the length modifier is valid with the given conversion specifier.
9695   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9696                                  S.getLangOpts()))
9697     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9698                                 diag::warn_format_nonsensical_length);
9699   else if (!FS.hasStandardLengthModifier())
9700     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9701   else if (!FS.hasStandardLengthConversionCombination())
9702     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9703                                 diag::warn_format_non_standard_conversion_spec);
9704 
9705   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9706     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9707 
9708   // The remaining checks depend on the data arguments.
9709   if (HasVAListArg)
9710     return true;
9711 
9712   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9713     return false;
9714 
9715   // Check that the argument type matches the format specifier.
9716   const Expr *Ex = getDataArg(argIndex);
9717   if (!Ex)
9718     return true;
9719 
9720   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9721 
9722   if (!AT.isValid()) {
9723     return true;
9724   }
9725 
9726   analyze_format_string::ArgType::MatchKind Match =
9727       AT.matchesType(S.Context, Ex->getType());
9728   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9729   if (Match == analyze_format_string::ArgType::Match)
9730     return true;
9731 
9732   ScanfSpecifier fixedFS = FS;
9733   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9734                                  S.getLangOpts(), S.Context);
9735 
9736   unsigned Diag =
9737       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9738                : diag::warn_format_conversion_argument_type_mismatch;
9739 
9740   if (Success) {
9741     // Get the fix string from the fixed format specifier.
9742     SmallString<128> buf;
9743     llvm::raw_svector_ostream os(buf);
9744     fixedFS.toString(os);
9745 
9746     EmitFormatDiagnostic(
9747         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9748                       << Ex->getType() << false << Ex->getSourceRange(),
9749         Ex->getBeginLoc(),
9750         /*IsStringLocation*/ false,
9751         getSpecifierRange(startSpecifier, specifierLen),
9752         FixItHint::CreateReplacement(
9753             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9754   } else {
9755     EmitFormatDiagnostic(S.PDiag(Diag)
9756                              << AT.getRepresentativeTypeName(S.Context)
9757                              << Ex->getType() << false << Ex->getSourceRange(),
9758                          Ex->getBeginLoc(),
9759                          /*IsStringLocation*/ false,
9760                          getSpecifierRange(startSpecifier, specifierLen));
9761   }
9762 
9763   return true;
9764 }
9765 
9766 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9767                               const Expr *OrigFormatExpr,
9768                               ArrayRef<const Expr *> Args,
9769                               bool HasVAListArg, unsigned format_idx,
9770                               unsigned firstDataArg,
9771                               Sema::FormatStringType Type,
9772                               bool inFunctionCall,
9773                               Sema::VariadicCallType CallType,
9774                               llvm::SmallBitVector &CheckedVarArgs,
9775                               UncoveredArgHandler &UncoveredArg,
9776                               bool IgnoreStringsWithoutSpecifiers) {
9777   // CHECK: is the format string a wide literal?
9778   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9779     CheckFormatHandler::EmitFormatDiagnostic(
9780         S, inFunctionCall, Args[format_idx],
9781         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9782         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9783     return;
9784   }
9785 
9786   // Str - The format string.  NOTE: this is NOT null-terminated!
9787   StringRef StrRef = FExpr->getString();
9788   const char *Str = StrRef.data();
9789   // Account for cases where the string literal is truncated in a declaration.
9790   const ConstantArrayType *T =
9791     S.Context.getAsConstantArrayType(FExpr->getType());
9792   assert(T && "String literal not of constant array type!");
9793   size_t TypeSize = T->getSize().getZExtValue();
9794   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9795   const unsigned numDataArgs = Args.size() - firstDataArg;
9796 
9797   if (IgnoreStringsWithoutSpecifiers &&
9798       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9799           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9800     return;
9801 
9802   // Emit a warning if the string literal is truncated and does not contain an
9803   // embedded null character.
9804   if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9805     CheckFormatHandler::EmitFormatDiagnostic(
9806         S, inFunctionCall, Args[format_idx],
9807         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9808         FExpr->getBeginLoc(),
9809         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9810     return;
9811   }
9812 
9813   // CHECK: empty format string?
9814   if (StrLen == 0 && numDataArgs > 0) {
9815     CheckFormatHandler::EmitFormatDiagnostic(
9816         S, inFunctionCall, Args[format_idx],
9817         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9818         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9819     return;
9820   }
9821 
9822   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9823       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9824       Type == Sema::FST_OSTrace) {
9825     CheckPrintfHandler H(
9826         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9827         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9828         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9829         CheckedVarArgs, UncoveredArg);
9830 
9831     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9832                                                   S.getLangOpts(),
9833                                                   S.Context.getTargetInfo(),
9834                                             Type == Sema::FST_FreeBSDKPrintf))
9835       H.DoneProcessing();
9836   } else if (Type == Sema::FST_Scanf) {
9837     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9838                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9839                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9840 
9841     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9842                                                  S.getLangOpts(),
9843                                                  S.Context.getTargetInfo()))
9844       H.DoneProcessing();
9845   } // TODO: handle other formats
9846 }
9847 
9848 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9849   // Str - The format string.  NOTE: this is NOT null-terminated!
9850   StringRef StrRef = FExpr->getString();
9851   const char *Str = StrRef.data();
9852   // Account for cases where the string literal is truncated in a declaration.
9853   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9854   assert(T && "String literal not of constant array type!");
9855   size_t TypeSize = T->getSize().getZExtValue();
9856   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9857   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9858                                                          getLangOpts(),
9859                                                          Context.getTargetInfo());
9860 }
9861 
9862 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9863 
9864 // Returns the related absolute value function that is larger, of 0 if one
9865 // does not exist.
9866 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9867   switch (AbsFunction) {
9868   default:
9869     return 0;
9870 
9871   case Builtin::BI__builtin_abs:
9872     return Builtin::BI__builtin_labs;
9873   case Builtin::BI__builtin_labs:
9874     return Builtin::BI__builtin_llabs;
9875   case Builtin::BI__builtin_llabs:
9876     return 0;
9877 
9878   case Builtin::BI__builtin_fabsf:
9879     return Builtin::BI__builtin_fabs;
9880   case Builtin::BI__builtin_fabs:
9881     return Builtin::BI__builtin_fabsl;
9882   case Builtin::BI__builtin_fabsl:
9883     return 0;
9884 
9885   case Builtin::BI__builtin_cabsf:
9886     return Builtin::BI__builtin_cabs;
9887   case Builtin::BI__builtin_cabs:
9888     return Builtin::BI__builtin_cabsl;
9889   case Builtin::BI__builtin_cabsl:
9890     return 0;
9891 
9892   case Builtin::BIabs:
9893     return Builtin::BIlabs;
9894   case Builtin::BIlabs:
9895     return Builtin::BIllabs;
9896   case Builtin::BIllabs:
9897     return 0;
9898 
9899   case Builtin::BIfabsf:
9900     return Builtin::BIfabs;
9901   case Builtin::BIfabs:
9902     return Builtin::BIfabsl;
9903   case Builtin::BIfabsl:
9904     return 0;
9905 
9906   case Builtin::BIcabsf:
9907    return Builtin::BIcabs;
9908   case Builtin::BIcabs:
9909     return Builtin::BIcabsl;
9910   case Builtin::BIcabsl:
9911     return 0;
9912   }
9913 }
9914 
9915 // Returns the argument type of the absolute value function.
9916 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9917                                              unsigned AbsType) {
9918   if (AbsType == 0)
9919     return QualType();
9920 
9921   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9922   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9923   if (Error != ASTContext::GE_None)
9924     return QualType();
9925 
9926   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9927   if (!FT)
9928     return QualType();
9929 
9930   if (FT->getNumParams() != 1)
9931     return QualType();
9932 
9933   return FT->getParamType(0);
9934 }
9935 
9936 // Returns the best absolute value function, or zero, based on type and
9937 // current absolute value function.
9938 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9939                                    unsigned AbsFunctionKind) {
9940   unsigned BestKind = 0;
9941   uint64_t ArgSize = Context.getTypeSize(ArgType);
9942   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9943        Kind = getLargerAbsoluteValueFunction(Kind)) {
9944     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9945     if (Context.getTypeSize(ParamType) >= ArgSize) {
9946       if (BestKind == 0)
9947         BestKind = Kind;
9948       else if (Context.hasSameType(ParamType, ArgType)) {
9949         BestKind = Kind;
9950         break;
9951       }
9952     }
9953   }
9954   return BestKind;
9955 }
9956 
9957 enum AbsoluteValueKind {
9958   AVK_Integer,
9959   AVK_Floating,
9960   AVK_Complex
9961 };
9962 
9963 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9964   if (T->isIntegralOrEnumerationType())
9965     return AVK_Integer;
9966   if (T->isRealFloatingType())
9967     return AVK_Floating;
9968   if (T->isAnyComplexType())
9969     return AVK_Complex;
9970 
9971   llvm_unreachable("Type not integer, floating, or complex");
9972 }
9973 
9974 // Changes the absolute value function to a different type.  Preserves whether
9975 // the function is a builtin.
9976 static unsigned changeAbsFunction(unsigned AbsKind,
9977                                   AbsoluteValueKind ValueKind) {
9978   switch (ValueKind) {
9979   case AVK_Integer:
9980     switch (AbsKind) {
9981     default:
9982       return 0;
9983     case Builtin::BI__builtin_fabsf:
9984     case Builtin::BI__builtin_fabs:
9985     case Builtin::BI__builtin_fabsl:
9986     case Builtin::BI__builtin_cabsf:
9987     case Builtin::BI__builtin_cabs:
9988     case Builtin::BI__builtin_cabsl:
9989       return Builtin::BI__builtin_abs;
9990     case Builtin::BIfabsf:
9991     case Builtin::BIfabs:
9992     case Builtin::BIfabsl:
9993     case Builtin::BIcabsf:
9994     case Builtin::BIcabs:
9995     case Builtin::BIcabsl:
9996       return Builtin::BIabs;
9997     }
9998   case AVK_Floating:
9999     switch (AbsKind) {
10000     default:
10001       return 0;
10002     case Builtin::BI__builtin_abs:
10003     case Builtin::BI__builtin_labs:
10004     case Builtin::BI__builtin_llabs:
10005     case Builtin::BI__builtin_cabsf:
10006     case Builtin::BI__builtin_cabs:
10007     case Builtin::BI__builtin_cabsl:
10008       return Builtin::BI__builtin_fabsf;
10009     case Builtin::BIabs:
10010     case Builtin::BIlabs:
10011     case Builtin::BIllabs:
10012     case Builtin::BIcabsf:
10013     case Builtin::BIcabs:
10014     case Builtin::BIcabsl:
10015       return Builtin::BIfabsf;
10016     }
10017   case AVK_Complex:
10018     switch (AbsKind) {
10019     default:
10020       return 0;
10021     case Builtin::BI__builtin_abs:
10022     case Builtin::BI__builtin_labs:
10023     case Builtin::BI__builtin_llabs:
10024     case Builtin::BI__builtin_fabsf:
10025     case Builtin::BI__builtin_fabs:
10026     case Builtin::BI__builtin_fabsl:
10027       return Builtin::BI__builtin_cabsf;
10028     case Builtin::BIabs:
10029     case Builtin::BIlabs:
10030     case Builtin::BIllabs:
10031     case Builtin::BIfabsf:
10032     case Builtin::BIfabs:
10033     case Builtin::BIfabsl:
10034       return Builtin::BIcabsf;
10035     }
10036   }
10037   llvm_unreachable("Unable to convert function");
10038 }
10039 
10040 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10041   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10042   if (!FnInfo)
10043     return 0;
10044 
10045   switch (FDecl->getBuiltinID()) {
10046   default:
10047     return 0;
10048   case Builtin::BI__builtin_abs:
10049   case Builtin::BI__builtin_fabs:
10050   case Builtin::BI__builtin_fabsf:
10051   case Builtin::BI__builtin_fabsl:
10052   case Builtin::BI__builtin_labs:
10053   case Builtin::BI__builtin_llabs:
10054   case Builtin::BI__builtin_cabs:
10055   case Builtin::BI__builtin_cabsf:
10056   case Builtin::BI__builtin_cabsl:
10057   case Builtin::BIabs:
10058   case Builtin::BIlabs:
10059   case Builtin::BIllabs:
10060   case Builtin::BIfabs:
10061   case Builtin::BIfabsf:
10062   case Builtin::BIfabsl:
10063   case Builtin::BIcabs:
10064   case Builtin::BIcabsf:
10065   case Builtin::BIcabsl:
10066     return FDecl->getBuiltinID();
10067   }
10068   llvm_unreachable("Unknown Builtin type");
10069 }
10070 
10071 // If the replacement is valid, emit a note with replacement function.
10072 // Additionally, suggest including the proper header if not already included.
10073 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10074                             unsigned AbsKind, QualType ArgType) {
10075   bool EmitHeaderHint = true;
10076   const char *HeaderName = nullptr;
10077   const char *FunctionName = nullptr;
10078   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10079     FunctionName = "std::abs";
10080     if (ArgType->isIntegralOrEnumerationType()) {
10081       HeaderName = "cstdlib";
10082     } else if (ArgType->isRealFloatingType()) {
10083       HeaderName = "cmath";
10084     } else {
10085       llvm_unreachable("Invalid Type");
10086     }
10087 
10088     // Lookup all std::abs
10089     if (NamespaceDecl *Std = S.getStdNamespace()) {
10090       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10091       R.suppressDiagnostics();
10092       S.LookupQualifiedName(R, Std);
10093 
10094       for (const auto *I : R) {
10095         const FunctionDecl *FDecl = nullptr;
10096         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10097           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10098         } else {
10099           FDecl = dyn_cast<FunctionDecl>(I);
10100         }
10101         if (!FDecl)
10102           continue;
10103 
10104         // Found std::abs(), check that they are the right ones.
10105         if (FDecl->getNumParams() != 1)
10106           continue;
10107 
10108         // Check that the parameter type can handle the argument.
10109         QualType ParamType = FDecl->getParamDecl(0)->getType();
10110         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10111             S.Context.getTypeSize(ArgType) <=
10112                 S.Context.getTypeSize(ParamType)) {
10113           // Found a function, don't need the header hint.
10114           EmitHeaderHint = false;
10115           break;
10116         }
10117       }
10118     }
10119   } else {
10120     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10121     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10122 
10123     if (HeaderName) {
10124       DeclarationName DN(&S.Context.Idents.get(FunctionName));
10125       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10126       R.suppressDiagnostics();
10127       S.LookupName(R, S.getCurScope());
10128 
10129       if (R.isSingleResult()) {
10130         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10131         if (FD && FD->getBuiltinID() == AbsKind) {
10132           EmitHeaderHint = false;
10133         } else {
10134           return;
10135         }
10136       } else if (!R.empty()) {
10137         return;
10138       }
10139     }
10140   }
10141 
10142   S.Diag(Loc, diag::note_replace_abs_function)
10143       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10144 
10145   if (!HeaderName)
10146     return;
10147 
10148   if (!EmitHeaderHint)
10149     return;
10150 
10151   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10152                                                     << FunctionName;
10153 }
10154 
10155 template <std::size_t StrLen>
10156 static bool IsStdFunction(const FunctionDecl *FDecl,
10157                           const char (&Str)[StrLen]) {
10158   if (!FDecl)
10159     return false;
10160   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10161     return false;
10162   if (!FDecl->isInStdNamespace())
10163     return false;
10164 
10165   return true;
10166 }
10167 
10168 // Warn when using the wrong abs() function.
10169 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10170                                       const FunctionDecl *FDecl) {
10171   if (Call->getNumArgs() != 1)
10172     return;
10173 
10174   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10175   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10176   if (AbsKind == 0 && !IsStdAbs)
10177     return;
10178 
10179   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10180   QualType ParamType = Call->getArg(0)->getType();
10181 
10182   // Unsigned types cannot be negative.  Suggest removing the absolute value
10183   // function call.
10184   if (ArgType->isUnsignedIntegerType()) {
10185     const char *FunctionName =
10186         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10187     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10188     Diag(Call->getExprLoc(), diag::note_remove_abs)
10189         << FunctionName
10190         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10191     return;
10192   }
10193 
10194   // Taking the absolute value of a pointer is very suspicious, they probably
10195   // wanted to index into an array, dereference a pointer, call a function, etc.
10196   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10197     unsigned DiagType = 0;
10198     if (ArgType->isFunctionType())
10199       DiagType = 1;
10200     else if (ArgType->isArrayType())
10201       DiagType = 2;
10202 
10203     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10204     return;
10205   }
10206 
10207   // std::abs has overloads which prevent most of the absolute value problems
10208   // from occurring.
10209   if (IsStdAbs)
10210     return;
10211 
10212   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10213   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10214 
10215   // The argument and parameter are the same kind.  Check if they are the right
10216   // size.
10217   if (ArgValueKind == ParamValueKind) {
10218     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10219       return;
10220 
10221     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10222     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10223         << FDecl << ArgType << ParamType;
10224 
10225     if (NewAbsKind == 0)
10226       return;
10227 
10228     emitReplacement(*this, Call->getExprLoc(),
10229                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10230     return;
10231   }
10232 
10233   // ArgValueKind != ParamValueKind
10234   // The wrong type of absolute value function was used.  Attempt to find the
10235   // proper one.
10236   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10237   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10238   if (NewAbsKind == 0)
10239     return;
10240 
10241   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10242       << FDecl << ParamValueKind << ArgValueKind;
10243 
10244   emitReplacement(*this, Call->getExprLoc(),
10245                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10246 }
10247 
10248 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10249 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10250                                 const FunctionDecl *FDecl) {
10251   if (!Call || !FDecl) return;
10252 
10253   // Ignore template specializations and macros.
10254   if (inTemplateInstantiation()) return;
10255   if (Call->getExprLoc().isMacroID()) return;
10256 
10257   // Only care about the one template argument, two function parameter std::max
10258   if (Call->getNumArgs() != 2) return;
10259   if (!IsStdFunction(FDecl, "max")) return;
10260   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10261   if (!ArgList) return;
10262   if (ArgList->size() != 1) return;
10263 
10264   // Check that template type argument is unsigned integer.
10265   const auto& TA = ArgList->get(0);
10266   if (TA.getKind() != TemplateArgument::Type) return;
10267   QualType ArgType = TA.getAsType();
10268   if (!ArgType->isUnsignedIntegerType()) return;
10269 
10270   // See if either argument is a literal zero.
10271   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10272     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10273     if (!MTE) return false;
10274     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10275     if (!Num) return false;
10276     if (Num->getValue() != 0) return false;
10277     return true;
10278   };
10279 
10280   const Expr *FirstArg = Call->getArg(0);
10281   const Expr *SecondArg = Call->getArg(1);
10282   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10283   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10284 
10285   // Only warn when exactly one argument is zero.
10286   if (IsFirstArgZero == IsSecondArgZero) return;
10287 
10288   SourceRange FirstRange = FirstArg->getSourceRange();
10289   SourceRange SecondRange = SecondArg->getSourceRange();
10290 
10291   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10292 
10293   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10294       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10295 
10296   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10297   SourceRange RemovalRange;
10298   if (IsFirstArgZero) {
10299     RemovalRange = SourceRange(FirstRange.getBegin(),
10300                                SecondRange.getBegin().getLocWithOffset(-1));
10301   } else {
10302     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10303                                SecondRange.getEnd());
10304   }
10305 
10306   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10307         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10308         << FixItHint::CreateRemoval(RemovalRange);
10309 }
10310 
10311 //===--- CHECK: Standard memory functions ---------------------------------===//
10312 
10313 /// Takes the expression passed to the size_t parameter of functions
10314 /// such as memcmp, strncat, etc and warns if it's a comparison.
10315 ///
10316 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10317 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10318                                            IdentifierInfo *FnName,
10319                                            SourceLocation FnLoc,
10320                                            SourceLocation RParenLoc) {
10321   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10322   if (!Size)
10323     return false;
10324 
10325   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10326   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10327     return false;
10328 
10329   SourceRange SizeRange = Size->getSourceRange();
10330   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10331       << SizeRange << FnName;
10332   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10333       << FnName
10334       << FixItHint::CreateInsertion(
10335              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10336       << FixItHint::CreateRemoval(RParenLoc);
10337   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10338       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10339       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10340                                     ")");
10341 
10342   return true;
10343 }
10344 
10345 /// Determine whether the given type is or contains a dynamic class type
10346 /// (e.g., whether it has a vtable).
10347 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10348                                                      bool &IsContained) {
10349   // Look through array types while ignoring qualifiers.
10350   const Type *Ty = T->getBaseElementTypeUnsafe();
10351   IsContained = false;
10352 
10353   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10354   RD = RD ? RD->getDefinition() : nullptr;
10355   if (!RD || RD->isInvalidDecl())
10356     return nullptr;
10357 
10358   if (RD->isDynamicClass())
10359     return RD;
10360 
10361   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10362   // It's impossible for a class to transitively contain itself by value, so
10363   // infinite recursion is impossible.
10364   for (auto *FD : RD->fields()) {
10365     bool SubContained;
10366     if (const CXXRecordDecl *ContainedRD =
10367             getContainedDynamicClass(FD->getType(), SubContained)) {
10368       IsContained = true;
10369       return ContainedRD;
10370     }
10371   }
10372 
10373   return nullptr;
10374 }
10375 
10376 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10377   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10378     if (Unary->getKind() == UETT_SizeOf)
10379       return Unary;
10380   return nullptr;
10381 }
10382 
10383 /// If E is a sizeof expression, returns its argument expression,
10384 /// otherwise returns NULL.
10385 static const Expr *getSizeOfExprArg(const Expr *E) {
10386   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10387     if (!SizeOf->isArgumentType())
10388       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10389   return nullptr;
10390 }
10391 
10392 /// If E is a sizeof expression, returns its argument type.
10393 static QualType getSizeOfArgType(const Expr *E) {
10394   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10395     return SizeOf->getTypeOfArgument();
10396   return QualType();
10397 }
10398 
10399 namespace {
10400 
10401 struct SearchNonTrivialToInitializeField
10402     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10403   using Super =
10404       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10405 
10406   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10407 
10408   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10409                      SourceLocation SL) {
10410     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10411       asDerived().visitArray(PDIK, AT, SL);
10412       return;
10413     }
10414 
10415     Super::visitWithKind(PDIK, FT, SL);
10416   }
10417 
10418   void visitARCStrong(QualType FT, SourceLocation SL) {
10419     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10420   }
10421   void visitARCWeak(QualType FT, SourceLocation SL) {
10422     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10423   }
10424   void visitStruct(QualType FT, SourceLocation SL) {
10425     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10426       visit(FD->getType(), FD->getLocation());
10427   }
10428   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10429                   const ArrayType *AT, SourceLocation SL) {
10430     visit(getContext().getBaseElementType(AT), SL);
10431   }
10432   void visitTrivial(QualType FT, SourceLocation SL) {}
10433 
10434   static void diag(QualType RT, const Expr *E, Sema &S) {
10435     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10436   }
10437 
10438   ASTContext &getContext() { return S.getASTContext(); }
10439 
10440   const Expr *E;
10441   Sema &S;
10442 };
10443 
10444 struct SearchNonTrivialToCopyField
10445     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10446   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10447 
10448   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10449 
10450   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10451                      SourceLocation SL) {
10452     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10453       asDerived().visitArray(PCK, AT, SL);
10454       return;
10455     }
10456 
10457     Super::visitWithKind(PCK, FT, SL);
10458   }
10459 
10460   void visitARCStrong(QualType FT, SourceLocation SL) {
10461     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10462   }
10463   void visitARCWeak(QualType FT, SourceLocation SL) {
10464     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10465   }
10466   void visitStruct(QualType FT, SourceLocation SL) {
10467     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10468       visit(FD->getType(), FD->getLocation());
10469   }
10470   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10471                   SourceLocation SL) {
10472     visit(getContext().getBaseElementType(AT), SL);
10473   }
10474   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10475                 SourceLocation SL) {}
10476   void visitTrivial(QualType FT, SourceLocation SL) {}
10477   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10478 
10479   static void diag(QualType RT, const Expr *E, Sema &S) {
10480     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10481   }
10482 
10483   ASTContext &getContext() { return S.getASTContext(); }
10484 
10485   const Expr *E;
10486   Sema &S;
10487 };
10488 
10489 }
10490 
10491 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10492 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10493   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10494 
10495   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10496     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10497       return false;
10498 
10499     return doesExprLikelyComputeSize(BO->getLHS()) ||
10500            doesExprLikelyComputeSize(BO->getRHS());
10501   }
10502 
10503   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10504 }
10505 
10506 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10507 ///
10508 /// \code
10509 ///   #define MACRO 0
10510 ///   foo(MACRO);
10511 ///   foo(0);
10512 /// \endcode
10513 ///
10514 /// This should return true for the first call to foo, but not for the second
10515 /// (regardless of whether foo is a macro or function).
10516 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10517                                         SourceLocation CallLoc,
10518                                         SourceLocation ArgLoc) {
10519   if (!CallLoc.isMacroID())
10520     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10521 
10522   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10523          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10524 }
10525 
10526 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10527 /// last two arguments transposed.
10528 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10529   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10530     return;
10531 
10532   const Expr *SizeArg =
10533     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10534 
10535   auto isLiteralZero = [](const Expr *E) {
10536     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10537   };
10538 
10539   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10540   SourceLocation CallLoc = Call->getRParenLoc();
10541   SourceManager &SM = S.getSourceManager();
10542   if (isLiteralZero(SizeArg) &&
10543       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10544 
10545     SourceLocation DiagLoc = SizeArg->getExprLoc();
10546 
10547     // Some platforms #define bzero to __builtin_memset. See if this is the
10548     // case, and if so, emit a better diagnostic.
10549     if (BId == Builtin::BIbzero ||
10550         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10551                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10552       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10553       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10554     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10555       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10556       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10557     }
10558     return;
10559   }
10560 
10561   // If the second argument to a memset is a sizeof expression and the third
10562   // isn't, this is also likely an error. This should catch
10563   // 'memset(buf, sizeof(buf), 0xff)'.
10564   if (BId == Builtin::BImemset &&
10565       doesExprLikelyComputeSize(Call->getArg(1)) &&
10566       !doesExprLikelyComputeSize(Call->getArg(2))) {
10567     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10568     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10569     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10570     return;
10571   }
10572 }
10573 
10574 /// Check for dangerous or invalid arguments to memset().
10575 ///
10576 /// This issues warnings on known problematic, dangerous or unspecified
10577 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10578 /// function calls.
10579 ///
10580 /// \param Call The call expression to diagnose.
10581 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10582                                    unsigned BId,
10583                                    IdentifierInfo *FnName) {
10584   assert(BId != 0);
10585 
10586   // It is possible to have a non-standard definition of memset.  Validate
10587   // we have enough arguments, and if not, abort further checking.
10588   unsigned ExpectedNumArgs =
10589       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10590   if (Call->getNumArgs() < ExpectedNumArgs)
10591     return;
10592 
10593   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10594                       BId == Builtin::BIstrndup ? 1 : 2);
10595   unsigned LenArg =
10596       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10597   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10598 
10599   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10600                                      Call->getBeginLoc(), Call->getRParenLoc()))
10601     return;
10602 
10603   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10604   CheckMemaccessSize(*this, BId, Call);
10605 
10606   // We have special checking when the length is a sizeof expression.
10607   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10608   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10609   llvm::FoldingSetNodeID SizeOfArgID;
10610 
10611   // Although widely used, 'bzero' is not a standard function. Be more strict
10612   // with the argument types before allowing diagnostics and only allow the
10613   // form bzero(ptr, sizeof(...)).
10614   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10615   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10616     return;
10617 
10618   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10619     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10620     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10621 
10622     QualType DestTy = Dest->getType();
10623     QualType PointeeTy;
10624     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10625       PointeeTy = DestPtrTy->getPointeeType();
10626 
10627       // Never warn about void type pointers. This can be used to suppress
10628       // false positives.
10629       if (PointeeTy->isVoidType())
10630         continue;
10631 
10632       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10633       // actually comparing the expressions for equality. Because computing the
10634       // expression IDs can be expensive, we only do this if the diagnostic is
10635       // enabled.
10636       if (SizeOfArg &&
10637           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10638                            SizeOfArg->getExprLoc())) {
10639         // We only compute IDs for expressions if the warning is enabled, and
10640         // cache the sizeof arg's ID.
10641         if (SizeOfArgID == llvm::FoldingSetNodeID())
10642           SizeOfArg->Profile(SizeOfArgID, Context, true);
10643         llvm::FoldingSetNodeID DestID;
10644         Dest->Profile(DestID, Context, true);
10645         if (DestID == SizeOfArgID) {
10646           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10647           //       over sizeof(src) as well.
10648           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10649           StringRef ReadableName = FnName->getName();
10650 
10651           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10652             if (UnaryOp->getOpcode() == UO_AddrOf)
10653               ActionIdx = 1; // If its an address-of operator, just remove it.
10654           if (!PointeeTy->isIncompleteType() &&
10655               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10656             ActionIdx = 2; // If the pointee's size is sizeof(char),
10657                            // suggest an explicit length.
10658 
10659           // If the function is defined as a builtin macro, do not show macro
10660           // expansion.
10661           SourceLocation SL = SizeOfArg->getExprLoc();
10662           SourceRange DSR = Dest->getSourceRange();
10663           SourceRange SSR = SizeOfArg->getSourceRange();
10664           SourceManager &SM = getSourceManager();
10665 
10666           if (SM.isMacroArgExpansion(SL)) {
10667             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10668             SL = SM.getSpellingLoc(SL);
10669             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10670                              SM.getSpellingLoc(DSR.getEnd()));
10671             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10672                              SM.getSpellingLoc(SSR.getEnd()));
10673           }
10674 
10675           DiagRuntimeBehavior(SL, SizeOfArg,
10676                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10677                                 << ReadableName
10678                                 << PointeeTy
10679                                 << DestTy
10680                                 << DSR
10681                                 << SSR);
10682           DiagRuntimeBehavior(SL, SizeOfArg,
10683                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10684                                 << ActionIdx
10685                                 << SSR);
10686 
10687           break;
10688         }
10689       }
10690 
10691       // Also check for cases where the sizeof argument is the exact same
10692       // type as the memory argument, and where it points to a user-defined
10693       // record type.
10694       if (SizeOfArgTy != QualType()) {
10695         if (PointeeTy->isRecordType() &&
10696             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10697           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10698                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10699                                 << FnName << SizeOfArgTy << ArgIdx
10700                                 << PointeeTy << Dest->getSourceRange()
10701                                 << LenExpr->getSourceRange());
10702           break;
10703         }
10704       }
10705     } else if (DestTy->isArrayType()) {
10706       PointeeTy = DestTy;
10707     }
10708 
10709     if (PointeeTy == QualType())
10710       continue;
10711 
10712     // Always complain about dynamic classes.
10713     bool IsContained;
10714     if (const CXXRecordDecl *ContainedRD =
10715             getContainedDynamicClass(PointeeTy, IsContained)) {
10716 
10717       unsigned OperationType = 0;
10718       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10719       // "overwritten" if we're warning about the destination for any call
10720       // but memcmp; otherwise a verb appropriate to the call.
10721       if (ArgIdx != 0 || IsCmp) {
10722         if (BId == Builtin::BImemcpy)
10723           OperationType = 1;
10724         else if(BId == Builtin::BImemmove)
10725           OperationType = 2;
10726         else if (IsCmp)
10727           OperationType = 3;
10728       }
10729 
10730       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10731                           PDiag(diag::warn_dyn_class_memaccess)
10732                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10733                               << IsContained << ContainedRD << OperationType
10734                               << Call->getCallee()->getSourceRange());
10735     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10736              BId != Builtin::BImemset)
10737       DiagRuntimeBehavior(
10738         Dest->getExprLoc(), Dest,
10739         PDiag(diag::warn_arc_object_memaccess)
10740           << ArgIdx << FnName << PointeeTy
10741           << Call->getCallee()->getSourceRange());
10742     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10743       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10744           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10745         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10746                             PDiag(diag::warn_cstruct_memaccess)
10747                                 << ArgIdx << FnName << PointeeTy << 0);
10748         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10749       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10750                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10751         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10752                             PDiag(diag::warn_cstruct_memaccess)
10753                                 << ArgIdx << FnName << PointeeTy << 1);
10754         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10755       } else {
10756         continue;
10757       }
10758     } else
10759       continue;
10760 
10761     DiagRuntimeBehavior(
10762       Dest->getExprLoc(), Dest,
10763       PDiag(diag::note_bad_memaccess_silence)
10764         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10765     break;
10766   }
10767 }
10768 
10769 // A little helper routine: ignore addition and subtraction of integer literals.
10770 // This intentionally does not ignore all integer constant expressions because
10771 // we don't want to remove sizeof().
10772 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10773   Ex = Ex->IgnoreParenCasts();
10774 
10775   while (true) {
10776     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10777     if (!BO || !BO->isAdditiveOp())
10778       break;
10779 
10780     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10781     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10782 
10783     if (isa<IntegerLiteral>(RHS))
10784       Ex = LHS;
10785     else if (isa<IntegerLiteral>(LHS))
10786       Ex = RHS;
10787     else
10788       break;
10789   }
10790 
10791   return Ex;
10792 }
10793 
10794 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10795                                                       ASTContext &Context) {
10796   // Only handle constant-sized or VLAs, but not flexible members.
10797   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10798     // Only issue the FIXIT for arrays of size > 1.
10799     if (CAT->getSize().getSExtValue() <= 1)
10800       return false;
10801   } else if (!Ty->isVariableArrayType()) {
10802     return false;
10803   }
10804   return true;
10805 }
10806 
10807 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10808 // be the size of the source, instead of the destination.
10809 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10810                                     IdentifierInfo *FnName) {
10811 
10812   // Don't crash if the user has the wrong number of arguments
10813   unsigned NumArgs = Call->getNumArgs();
10814   if ((NumArgs != 3) && (NumArgs != 4))
10815     return;
10816 
10817   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10818   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10819   const Expr *CompareWithSrc = nullptr;
10820 
10821   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10822                                      Call->getBeginLoc(), Call->getRParenLoc()))
10823     return;
10824 
10825   // Look for 'strlcpy(dst, x, sizeof(x))'
10826   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10827     CompareWithSrc = Ex;
10828   else {
10829     // Look for 'strlcpy(dst, x, strlen(x))'
10830     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10831       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10832           SizeCall->getNumArgs() == 1)
10833         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10834     }
10835   }
10836 
10837   if (!CompareWithSrc)
10838     return;
10839 
10840   // Determine if the argument to sizeof/strlen is equal to the source
10841   // argument.  In principle there's all kinds of things you could do
10842   // here, for instance creating an == expression and evaluating it with
10843   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10844   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10845   if (!SrcArgDRE)
10846     return;
10847 
10848   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10849   if (!CompareWithSrcDRE ||
10850       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10851     return;
10852 
10853   const Expr *OriginalSizeArg = Call->getArg(2);
10854   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10855       << OriginalSizeArg->getSourceRange() << FnName;
10856 
10857   // Output a FIXIT hint if the destination is an array (rather than a
10858   // pointer to an array).  This could be enhanced to handle some
10859   // pointers if we know the actual size, like if DstArg is 'array+2'
10860   // we could say 'sizeof(array)-2'.
10861   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10862   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10863     return;
10864 
10865   SmallString<128> sizeString;
10866   llvm::raw_svector_ostream OS(sizeString);
10867   OS << "sizeof(";
10868   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10869   OS << ")";
10870 
10871   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10872       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10873                                       OS.str());
10874 }
10875 
10876 /// Check if two expressions refer to the same declaration.
10877 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10878   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10879     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10880       return D1->getDecl() == D2->getDecl();
10881   return false;
10882 }
10883 
10884 static const Expr *getStrlenExprArg(const Expr *E) {
10885   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10886     const FunctionDecl *FD = CE->getDirectCallee();
10887     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10888       return nullptr;
10889     return CE->getArg(0)->IgnoreParenCasts();
10890   }
10891   return nullptr;
10892 }
10893 
10894 // Warn on anti-patterns as the 'size' argument to strncat.
10895 // The correct size argument should look like following:
10896 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10897 void Sema::CheckStrncatArguments(const CallExpr *CE,
10898                                  IdentifierInfo *FnName) {
10899   // Don't crash if the user has the wrong number of arguments.
10900   if (CE->getNumArgs() < 3)
10901     return;
10902   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10903   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10904   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10905 
10906   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10907                                      CE->getRParenLoc()))
10908     return;
10909 
10910   // Identify common expressions, which are wrongly used as the size argument
10911   // to strncat and may lead to buffer overflows.
10912   unsigned PatternType = 0;
10913   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10914     // - sizeof(dst)
10915     if (referToTheSameDecl(SizeOfArg, DstArg))
10916       PatternType = 1;
10917     // - sizeof(src)
10918     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10919       PatternType = 2;
10920   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10921     if (BE->getOpcode() == BO_Sub) {
10922       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10923       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10924       // - sizeof(dst) - strlen(dst)
10925       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10926           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10927         PatternType = 1;
10928       // - sizeof(src) - (anything)
10929       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10930         PatternType = 2;
10931     }
10932   }
10933 
10934   if (PatternType == 0)
10935     return;
10936 
10937   // Generate the diagnostic.
10938   SourceLocation SL = LenArg->getBeginLoc();
10939   SourceRange SR = LenArg->getSourceRange();
10940   SourceManager &SM = getSourceManager();
10941 
10942   // If the function is defined as a builtin macro, do not show macro expansion.
10943   if (SM.isMacroArgExpansion(SL)) {
10944     SL = SM.getSpellingLoc(SL);
10945     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10946                      SM.getSpellingLoc(SR.getEnd()));
10947   }
10948 
10949   // Check if the destination is an array (rather than a pointer to an array).
10950   QualType DstTy = DstArg->getType();
10951   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10952                                                                     Context);
10953   if (!isKnownSizeArray) {
10954     if (PatternType == 1)
10955       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10956     else
10957       Diag(SL, diag::warn_strncat_src_size) << SR;
10958     return;
10959   }
10960 
10961   if (PatternType == 1)
10962     Diag(SL, diag::warn_strncat_large_size) << SR;
10963   else
10964     Diag(SL, diag::warn_strncat_src_size) << SR;
10965 
10966   SmallString<128> sizeString;
10967   llvm::raw_svector_ostream OS(sizeString);
10968   OS << "sizeof(";
10969   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10970   OS << ") - ";
10971   OS << "strlen(";
10972   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10973   OS << ") - 1";
10974 
10975   Diag(SL, diag::note_strncat_wrong_size)
10976     << FixItHint::CreateReplacement(SR, OS.str());
10977 }
10978 
10979 namespace {
10980 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10981                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10982   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10983     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10984         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10985     return;
10986   }
10987 }
10988 
10989 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10990                                  const UnaryOperator *UnaryExpr) {
10991   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10992     const Decl *D = Lvalue->getDecl();
10993     if (isa<DeclaratorDecl>(D))
10994       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
10995         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10996   }
10997 
10998   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10999     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11000                                       Lvalue->getMemberDecl());
11001 }
11002 
11003 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11004                             const UnaryOperator *UnaryExpr) {
11005   const auto *Lambda = dyn_cast<LambdaExpr>(
11006       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11007   if (!Lambda)
11008     return;
11009 
11010   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11011       << CalleeName << 2 /*object: lambda expression*/;
11012 }
11013 
11014 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11015                                   const DeclRefExpr *Lvalue) {
11016   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11017   if (Var == nullptr)
11018     return;
11019 
11020   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11021       << CalleeName << 0 /*object: */ << Var;
11022 }
11023 
11024 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11025                             const CastExpr *Cast) {
11026   SmallString<128> SizeString;
11027   llvm::raw_svector_ostream OS(SizeString);
11028 
11029   clang::CastKind Kind = Cast->getCastKind();
11030   if (Kind == clang::CK_BitCast &&
11031       !Cast->getSubExpr()->getType()->isFunctionPointerType())
11032     return;
11033   if (Kind == clang::CK_IntegralToPointer &&
11034       !isa<IntegerLiteral>(
11035           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11036     return;
11037 
11038   switch (Cast->getCastKind()) {
11039   case clang::CK_BitCast:
11040   case clang::CK_IntegralToPointer:
11041   case clang::CK_FunctionToPointerDecay:
11042     OS << '\'';
11043     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11044     OS << '\'';
11045     break;
11046   default:
11047     return;
11048   }
11049 
11050   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11051       << CalleeName << 0 /*object: */ << OS.str();
11052 }
11053 } // namespace
11054 
11055 /// Alerts the user that they are attempting to free a non-malloc'd object.
11056 void Sema::CheckFreeArguments(const CallExpr *E) {
11057   const std::string CalleeName =
11058       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11059 
11060   { // Prefer something that doesn't involve a cast to make things simpler.
11061     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11062     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11063       switch (UnaryExpr->getOpcode()) {
11064       case UnaryOperator::Opcode::UO_AddrOf:
11065         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11066       case UnaryOperator::Opcode::UO_Plus:
11067         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11068       default:
11069         break;
11070       }
11071 
11072     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11073       if (Lvalue->getType()->isArrayType())
11074         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11075 
11076     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11077       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11078           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11079       return;
11080     }
11081 
11082     if (isa<BlockExpr>(Arg)) {
11083       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11084           << CalleeName << 1 /*object: block*/;
11085       return;
11086     }
11087   }
11088   // Maybe the cast was important, check after the other cases.
11089   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11090     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11091 }
11092 
11093 void
11094 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11095                          SourceLocation ReturnLoc,
11096                          bool isObjCMethod,
11097                          const AttrVec *Attrs,
11098                          const FunctionDecl *FD) {
11099   // Check if the return value is null but should not be.
11100   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11101        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
11102       CheckNonNullExpr(*this, RetValExp))
11103     Diag(ReturnLoc, diag::warn_null_ret)
11104       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11105 
11106   // C++11 [basic.stc.dynamic.allocation]p4:
11107   //   If an allocation function declared with a non-throwing
11108   //   exception-specification fails to allocate storage, it shall return
11109   //   a null pointer. Any other allocation function that fails to allocate
11110   //   storage shall indicate failure only by throwing an exception [...]
11111   if (FD) {
11112     OverloadedOperatorKind Op = FD->getOverloadedOperator();
11113     if (Op == OO_New || Op == OO_Array_New) {
11114       const FunctionProtoType *Proto
11115         = FD->getType()->castAs<FunctionProtoType>();
11116       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11117           CheckNonNullExpr(*this, RetValExp))
11118         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11119           << FD << getLangOpts().CPlusPlus11;
11120     }
11121   }
11122 
11123   // PPC MMA non-pointer types are not allowed as return type. Checking the type
11124   // here prevent the user from using a PPC MMA type as trailing return type.
11125   if (Context.getTargetInfo().getTriple().isPPC64())
11126     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11127 }
11128 
11129 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
11130 
11131 /// Check for comparisons of floating point operands using != and ==.
11132 /// Issue a warning if these are no self-comparisons, as they are not likely
11133 /// to do what the programmer intended.
11134 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
11135   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
11136   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
11137 
11138   // Special case: check for x == x (which is OK).
11139   // Do not emit warnings for such cases.
11140   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11141     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11142       if (DRL->getDecl() == DRR->getDecl())
11143         return;
11144 
11145   // Special case: check for comparisons against literals that can be exactly
11146   //  represented by APFloat.  In such cases, do not emit a warning.  This
11147   //  is a heuristic: often comparison against such literals are used to
11148   //  detect if a value in a variable has not changed.  This clearly can
11149   //  lead to false negatives.
11150   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11151     if (FLL->isExact())
11152       return;
11153   } else
11154     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11155       if (FLR->isExact())
11156         return;
11157 
11158   // Check for comparisons with builtin types.
11159   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11160     if (CL->getBuiltinCallee())
11161       return;
11162 
11163   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11164     if (CR->getBuiltinCallee())
11165       return;
11166 
11167   // Emit the diagnostic.
11168   Diag(Loc, diag::warn_floatingpoint_eq)
11169     << LHS->getSourceRange() << RHS->getSourceRange();
11170 }
11171 
11172 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11173 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11174 
11175 namespace {
11176 
11177 /// Structure recording the 'active' range of an integer-valued
11178 /// expression.
11179 struct IntRange {
11180   /// The number of bits active in the int. Note that this includes exactly one
11181   /// sign bit if !NonNegative.
11182   unsigned Width;
11183 
11184   /// True if the int is known not to have negative values. If so, all leading
11185   /// bits before Width are known zero, otherwise they are known to be the
11186   /// same as the MSB within Width.
11187   bool NonNegative;
11188 
11189   IntRange(unsigned Width, bool NonNegative)
11190       : Width(Width), NonNegative(NonNegative) {}
11191 
11192   /// Number of bits excluding the sign bit.
11193   unsigned valueBits() const {
11194     return NonNegative ? Width : Width - 1;
11195   }
11196 
11197   /// Returns the range of the bool type.
11198   static IntRange forBoolType() {
11199     return IntRange(1, true);
11200   }
11201 
11202   /// Returns the range of an opaque value of the given integral type.
11203   static IntRange forValueOfType(ASTContext &C, QualType T) {
11204     return forValueOfCanonicalType(C,
11205                           T->getCanonicalTypeInternal().getTypePtr());
11206   }
11207 
11208   /// Returns the range of an opaque value of a canonical integral type.
11209   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11210     assert(T->isCanonicalUnqualified());
11211 
11212     if (const VectorType *VT = dyn_cast<VectorType>(T))
11213       T = VT->getElementType().getTypePtr();
11214     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11215       T = CT->getElementType().getTypePtr();
11216     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11217       T = AT->getValueType().getTypePtr();
11218 
11219     if (!C.getLangOpts().CPlusPlus) {
11220       // For enum types in C code, use the underlying datatype.
11221       if (const EnumType *ET = dyn_cast<EnumType>(T))
11222         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11223     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11224       // For enum types in C++, use the known bit width of the enumerators.
11225       EnumDecl *Enum = ET->getDecl();
11226       // In C++11, enums can have a fixed underlying type. Use this type to
11227       // compute the range.
11228       if (Enum->isFixed()) {
11229         return IntRange(C.getIntWidth(QualType(T, 0)),
11230                         !ET->isSignedIntegerOrEnumerationType());
11231       }
11232 
11233       unsigned NumPositive = Enum->getNumPositiveBits();
11234       unsigned NumNegative = Enum->getNumNegativeBits();
11235 
11236       if (NumNegative == 0)
11237         return IntRange(NumPositive, true/*NonNegative*/);
11238       else
11239         return IntRange(std::max(NumPositive + 1, NumNegative),
11240                         false/*NonNegative*/);
11241     }
11242 
11243     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11244       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11245 
11246     const BuiltinType *BT = cast<BuiltinType>(T);
11247     assert(BT->isInteger());
11248 
11249     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11250   }
11251 
11252   /// Returns the "target" range of a canonical integral type, i.e.
11253   /// the range of values expressible in the type.
11254   ///
11255   /// This matches forValueOfCanonicalType except that enums have the
11256   /// full range of their type, not the range of their enumerators.
11257   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11258     assert(T->isCanonicalUnqualified());
11259 
11260     if (const VectorType *VT = dyn_cast<VectorType>(T))
11261       T = VT->getElementType().getTypePtr();
11262     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11263       T = CT->getElementType().getTypePtr();
11264     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11265       T = AT->getValueType().getTypePtr();
11266     if (const EnumType *ET = dyn_cast<EnumType>(T))
11267       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11268 
11269     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11270       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11271 
11272     const BuiltinType *BT = cast<BuiltinType>(T);
11273     assert(BT->isInteger());
11274 
11275     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11276   }
11277 
11278   /// Returns the supremum of two ranges: i.e. their conservative merge.
11279   static IntRange join(IntRange L, IntRange R) {
11280     bool Unsigned = L.NonNegative && R.NonNegative;
11281     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11282                     L.NonNegative && R.NonNegative);
11283   }
11284 
11285   /// Return the range of a bitwise-AND of the two ranges.
11286   static IntRange bit_and(IntRange L, IntRange R) {
11287     unsigned Bits = std::max(L.Width, R.Width);
11288     bool NonNegative = false;
11289     if (L.NonNegative) {
11290       Bits = std::min(Bits, L.Width);
11291       NonNegative = true;
11292     }
11293     if (R.NonNegative) {
11294       Bits = std::min(Bits, R.Width);
11295       NonNegative = true;
11296     }
11297     return IntRange(Bits, NonNegative);
11298   }
11299 
11300   /// Return the range of a sum of the two ranges.
11301   static IntRange sum(IntRange L, IntRange R) {
11302     bool Unsigned = L.NonNegative && R.NonNegative;
11303     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11304                     Unsigned);
11305   }
11306 
11307   /// Return the range of a difference of the two ranges.
11308   static IntRange difference(IntRange L, IntRange R) {
11309     // We need a 1-bit-wider range if:
11310     //   1) LHS can be negative: least value can be reduced.
11311     //   2) RHS can be negative: greatest value can be increased.
11312     bool CanWiden = !L.NonNegative || !R.NonNegative;
11313     bool Unsigned = L.NonNegative && R.Width == 0;
11314     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11315                         !Unsigned,
11316                     Unsigned);
11317   }
11318 
11319   /// Return the range of a product of the two ranges.
11320   static IntRange product(IntRange L, IntRange R) {
11321     // If both LHS and RHS can be negative, we can form
11322     //   -2^L * -2^R = 2^(L + R)
11323     // which requires L + R + 1 value bits to represent.
11324     bool CanWiden = !L.NonNegative && !R.NonNegative;
11325     bool Unsigned = L.NonNegative && R.NonNegative;
11326     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11327                     Unsigned);
11328   }
11329 
11330   /// Return the range of a remainder operation between the two ranges.
11331   static IntRange rem(IntRange L, IntRange R) {
11332     // The result of a remainder can't be larger than the result of
11333     // either side. The sign of the result is the sign of the LHS.
11334     bool Unsigned = L.NonNegative;
11335     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11336                     Unsigned);
11337   }
11338 };
11339 
11340 } // namespace
11341 
11342 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11343                               unsigned MaxWidth) {
11344   if (value.isSigned() && value.isNegative())
11345     return IntRange(value.getMinSignedBits(), false);
11346 
11347   if (value.getBitWidth() > MaxWidth)
11348     value = value.trunc(MaxWidth);
11349 
11350   // isNonNegative() just checks the sign bit without considering
11351   // signedness.
11352   return IntRange(value.getActiveBits(), true);
11353 }
11354 
11355 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11356                               unsigned MaxWidth) {
11357   if (result.isInt())
11358     return GetValueRange(C, result.getInt(), MaxWidth);
11359 
11360   if (result.isVector()) {
11361     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11362     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11363       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11364       R = IntRange::join(R, El);
11365     }
11366     return R;
11367   }
11368 
11369   if (result.isComplexInt()) {
11370     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11371     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11372     return IntRange::join(R, I);
11373   }
11374 
11375   // This can happen with lossless casts to intptr_t of "based" lvalues.
11376   // Assume it might use arbitrary bits.
11377   // FIXME: The only reason we need to pass the type in here is to get
11378   // the sign right on this one case.  It would be nice if APValue
11379   // preserved this.
11380   assert(result.isLValue() || result.isAddrLabelDiff());
11381   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11382 }
11383 
11384 static QualType GetExprType(const Expr *E) {
11385   QualType Ty = E->getType();
11386   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11387     Ty = AtomicRHS->getValueType();
11388   return Ty;
11389 }
11390 
11391 /// Pseudo-evaluate the given integer expression, estimating the
11392 /// range of values it might take.
11393 ///
11394 /// \param MaxWidth The width to which the value will be truncated.
11395 /// \param Approximate If \c true, return a likely range for the result: in
11396 ///        particular, assume that arithmetic on narrower types doesn't leave
11397 ///        those types. If \c false, return a range including all possible
11398 ///        result values.
11399 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11400                              bool InConstantContext, bool Approximate) {
11401   E = E->IgnoreParens();
11402 
11403   // Try a full evaluation first.
11404   Expr::EvalResult result;
11405   if (E->EvaluateAsRValue(result, C, InConstantContext))
11406     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11407 
11408   // I think we only want to look through implicit casts here; if the
11409   // user has an explicit widening cast, we should treat the value as
11410   // being of the new, wider type.
11411   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11412     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11413       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11414                           Approximate);
11415 
11416     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11417 
11418     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11419                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11420 
11421     // Assume that non-integer casts can span the full range of the type.
11422     if (!isIntegerCast)
11423       return OutputTypeRange;
11424 
11425     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11426                                      std::min(MaxWidth, OutputTypeRange.Width),
11427                                      InConstantContext, Approximate);
11428 
11429     // Bail out if the subexpr's range is as wide as the cast type.
11430     if (SubRange.Width >= OutputTypeRange.Width)
11431       return OutputTypeRange;
11432 
11433     // Otherwise, we take the smaller width, and we're non-negative if
11434     // either the output type or the subexpr is.
11435     return IntRange(SubRange.Width,
11436                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11437   }
11438 
11439   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11440     // If we can fold the condition, just take that operand.
11441     bool CondResult;
11442     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11443       return GetExprRange(C,
11444                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11445                           MaxWidth, InConstantContext, Approximate);
11446 
11447     // Otherwise, conservatively merge.
11448     // GetExprRange requires an integer expression, but a throw expression
11449     // results in a void type.
11450     Expr *E = CO->getTrueExpr();
11451     IntRange L = E->getType()->isVoidType()
11452                      ? IntRange{0, true}
11453                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11454     E = CO->getFalseExpr();
11455     IntRange R = E->getType()->isVoidType()
11456                      ? IntRange{0, true}
11457                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11458     return IntRange::join(L, R);
11459   }
11460 
11461   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11462     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11463 
11464     switch (BO->getOpcode()) {
11465     case BO_Cmp:
11466       llvm_unreachable("builtin <=> should have class type");
11467 
11468     // Boolean-valued operations are single-bit and positive.
11469     case BO_LAnd:
11470     case BO_LOr:
11471     case BO_LT:
11472     case BO_GT:
11473     case BO_LE:
11474     case BO_GE:
11475     case BO_EQ:
11476     case BO_NE:
11477       return IntRange::forBoolType();
11478 
11479     // The type of the assignments is the type of the LHS, so the RHS
11480     // is not necessarily the same type.
11481     case BO_MulAssign:
11482     case BO_DivAssign:
11483     case BO_RemAssign:
11484     case BO_AddAssign:
11485     case BO_SubAssign:
11486     case BO_XorAssign:
11487     case BO_OrAssign:
11488       // TODO: bitfields?
11489       return IntRange::forValueOfType(C, GetExprType(E));
11490 
11491     // Simple assignments just pass through the RHS, which will have
11492     // been coerced to the LHS type.
11493     case BO_Assign:
11494       // TODO: bitfields?
11495       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11496                           Approximate);
11497 
11498     // Operations with opaque sources are black-listed.
11499     case BO_PtrMemD:
11500     case BO_PtrMemI:
11501       return IntRange::forValueOfType(C, GetExprType(E));
11502 
11503     // Bitwise-and uses the *infinum* of the two source ranges.
11504     case BO_And:
11505     case BO_AndAssign:
11506       Combine = IntRange::bit_and;
11507       break;
11508 
11509     // Left shift gets black-listed based on a judgement call.
11510     case BO_Shl:
11511       // ...except that we want to treat '1 << (blah)' as logically
11512       // positive.  It's an important idiom.
11513       if (IntegerLiteral *I
11514             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11515         if (I->getValue() == 1) {
11516           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11517           return IntRange(R.Width, /*NonNegative*/ true);
11518         }
11519       }
11520       LLVM_FALLTHROUGH;
11521 
11522     case BO_ShlAssign:
11523       return IntRange::forValueOfType(C, GetExprType(E));
11524 
11525     // Right shift by a constant can narrow its left argument.
11526     case BO_Shr:
11527     case BO_ShrAssign: {
11528       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11529                                 Approximate);
11530 
11531       // If the shift amount is a positive constant, drop the width by
11532       // that much.
11533       if (Optional<llvm::APSInt> shift =
11534               BO->getRHS()->getIntegerConstantExpr(C)) {
11535         if (shift->isNonNegative()) {
11536           unsigned zext = shift->getZExtValue();
11537           if (zext >= L.Width)
11538             L.Width = (L.NonNegative ? 0 : 1);
11539           else
11540             L.Width -= zext;
11541         }
11542       }
11543 
11544       return L;
11545     }
11546 
11547     // Comma acts as its right operand.
11548     case BO_Comma:
11549       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11550                           Approximate);
11551 
11552     case BO_Add:
11553       if (!Approximate)
11554         Combine = IntRange::sum;
11555       break;
11556 
11557     case BO_Sub:
11558       if (BO->getLHS()->getType()->isPointerType())
11559         return IntRange::forValueOfType(C, GetExprType(E));
11560       if (!Approximate)
11561         Combine = IntRange::difference;
11562       break;
11563 
11564     case BO_Mul:
11565       if (!Approximate)
11566         Combine = IntRange::product;
11567       break;
11568 
11569     // The width of a division result is mostly determined by the size
11570     // of the LHS.
11571     case BO_Div: {
11572       // Don't 'pre-truncate' the operands.
11573       unsigned opWidth = C.getIntWidth(GetExprType(E));
11574       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11575                                 Approximate);
11576 
11577       // If the divisor is constant, use that.
11578       if (Optional<llvm::APSInt> divisor =
11579               BO->getRHS()->getIntegerConstantExpr(C)) {
11580         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11581         if (log2 >= L.Width)
11582           L.Width = (L.NonNegative ? 0 : 1);
11583         else
11584           L.Width = std::min(L.Width - log2, MaxWidth);
11585         return L;
11586       }
11587 
11588       // Otherwise, just use the LHS's width.
11589       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11590       // could be -1.
11591       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11592                                 Approximate);
11593       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11594     }
11595 
11596     case BO_Rem:
11597       Combine = IntRange::rem;
11598       break;
11599 
11600     // The default behavior is okay for these.
11601     case BO_Xor:
11602     case BO_Or:
11603       break;
11604     }
11605 
11606     // Combine the two ranges, but limit the result to the type in which we
11607     // performed the computation.
11608     QualType T = GetExprType(E);
11609     unsigned opWidth = C.getIntWidth(T);
11610     IntRange L =
11611         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11612     IntRange R =
11613         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11614     IntRange C = Combine(L, R);
11615     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11616     C.Width = std::min(C.Width, MaxWidth);
11617     return C;
11618   }
11619 
11620   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11621     switch (UO->getOpcode()) {
11622     // Boolean-valued operations are white-listed.
11623     case UO_LNot:
11624       return IntRange::forBoolType();
11625 
11626     // Operations with opaque sources are black-listed.
11627     case UO_Deref:
11628     case UO_AddrOf: // should be impossible
11629       return IntRange::forValueOfType(C, GetExprType(E));
11630 
11631     default:
11632       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11633                           Approximate);
11634     }
11635   }
11636 
11637   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11638     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11639                         Approximate);
11640 
11641   if (const auto *BitField = E->getSourceBitField())
11642     return IntRange(BitField->getBitWidthValue(C),
11643                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11644 
11645   return IntRange::forValueOfType(C, GetExprType(E));
11646 }
11647 
11648 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11649                              bool InConstantContext, bool Approximate) {
11650   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11651                       Approximate);
11652 }
11653 
11654 /// Checks whether the given value, which currently has the given
11655 /// source semantics, has the same value when coerced through the
11656 /// target semantics.
11657 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11658                                  const llvm::fltSemantics &Src,
11659                                  const llvm::fltSemantics &Tgt) {
11660   llvm::APFloat truncated = value;
11661 
11662   bool ignored;
11663   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11664   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11665 
11666   return truncated.bitwiseIsEqual(value);
11667 }
11668 
11669 /// Checks whether the given value, which currently has the given
11670 /// source semantics, has the same value when coerced through the
11671 /// target semantics.
11672 ///
11673 /// The value might be a vector of floats (or a complex number).
11674 static bool IsSameFloatAfterCast(const APValue &value,
11675                                  const llvm::fltSemantics &Src,
11676                                  const llvm::fltSemantics &Tgt) {
11677   if (value.isFloat())
11678     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11679 
11680   if (value.isVector()) {
11681     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11682       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11683         return false;
11684     return true;
11685   }
11686 
11687   assert(value.isComplexFloat());
11688   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11689           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11690 }
11691 
11692 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11693                                        bool IsListInit = false);
11694 
11695 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11696   // Suppress cases where we are comparing against an enum constant.
11697   if (const DeclRefExpr *DR =
11698       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11699     if (isa<EnumConstantDecl>(DR->getDecl()))
11700       return true;
11701 
11702   // Suppress cases where the value is expanded from a macro, unless that macro
11703   // is how a language represents a boolean literal. This is the case in both C
11704   // and Objective-C.
11705   SourceLocation BeginLoc = E->getBeginLoc();
11706   if (BeginLoc.isMacroID()) {
11707     StringRef MacroName = Lexer::getImmediateMacroName(
11708         BeginLoc, S.getSourceManager(), S.getLangOpts());
11709     return MacroName != "YES" && MacroName != "NO" &&
11710            MacroName != "true" && MacroName != "false";
11711   }
11712 
11713   return false;
11714 }
11715 
11716 static bool isKnownToHaveUnsignedValue(Expr *E) {
11717   return E->getType()->isIntegerType() &&
11718          (!E->getType()->isSignedIntegerType() ||
11719           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11720 }
11721 
11722 namespace {
11723 /// The promoted range of values of a type. In general this has the
11724 /// following structure:
11725 ///
11726 ///     |-----------| . . . |-----------|
11727 ///     ^           ^       ^           ^
11728 ///    Min       HoleMin  HoleMax      Max
11729 ///
11730 /// ... where there is only a hole if a signed type is promoted to unsigned
11731 /// (in which case Min and Max are the smallest and largest representable
11732 /// values).
11733 struct PromotedRange {
11734   // Min, or HoleMax if there is a hole.
11735   llvm::APSInt PromotedMin;
11736   // Max, or HoleMin if there is a hole.
11737   llvm::APSInt PromotedMax;
11738 
11739   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11740     if (R.Width == 0)
11741       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11742     else if (R.Width >= BitWidth && !Unsigned) {
11743       // Promotion made the type *narrower*. This happens when promoting
11744       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11745       // Treat all values of 'signed int' as being in range for now.
11746       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11747       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11748     } else {
11749       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11750                         .extOrTrunc(BitWidth);
11751       PromotedMin.setIsUnsigned(Unsigned);
11752 
11753       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11754                         .extOrTrunc(BitWidth);
11755       PromotedMax.setIsUnsigned(Unsigned);
11756     }
11757   }
11758 
11759   // Determine whether this range is contiguous (has no hole).
11760   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11761 
11762   // Where a constant value is within the range.
11763   enum ComparisonResult {
11764     LT = 0x1,
11765     LE = 0x2,
11766     GT = 0x4,
11767     GE = 0x8,
11768     EQ = 0x10,
11769     NE = 0x20,
11770     InRangeFlag = 0x40,
11771 
11772     Less = LE | LT | NE,
11773     Min = LE | InRangeFlag,
11774     InRange = InRangeFlag,
11775     Max = GE | InRangeFlag,
11776     Greater = GE | GT | NE,
11777 
11778     OnlyValue = LE | GE | EQ | InRangeFlag,
11779     InHole = NE
11780   };
11781 
11782   ComparisonResult compare(const llvm::APSInt &Value) const {
11783     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11784            Value.isUnsigned() == PromotedMin.isUnsigned());
11785     if (!isContiguous()) {
11786       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11787       if (Value.isMinValue()) return Min;
11788       if (Value.isMaxValue()) return Max;
11789       if (Value >= PromotedMin) return InRange;
11790       if (Value <= PromotedMax) return InRange;
11791       return InHole;
11792     }
11793 
11794     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11795     case -1: return Less;
11796     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11797     case 1:
11798       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11799       case -1: return InRange;
11800       case 0: return Max;
11801       case 1: return Greater;
11802       }
11803     }
11804 
11805     llvm_unreachable("impossible compare result");
11806   }
11807 
11808   static llvm::Optional<StringRef>
11809   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11810     if (Op == BO_Cmp) {
11811       ComparisonResult LTFlag = LT, GTFlag = GT;
11812       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11813 
11814       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11815       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11816       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11817       return llvm::None;
11818     }
11819 
11820     ComparisonResult TrueFlag, FalseFlag;
11821     if (Op == BO_EQ) {
11822       TrueFlag = EQ;
11823       FalseFlag = NE;
11824     } else if (Op == BO_NE) {
11825       TrueFlag = NE;
11826       FalseFlag = EQ;
11827     } else {
11828       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11829         TrueFlag = LT;
11830         FalseFlag = GE;
11831       } else {
11832         TrueFlag = GT;
11833         FalseFlag = LE;
11834       }
11835       if (Op == BO_GE || Op == BO_LE)
11836         std::swap(TrueFlag, FalseFlag);
11837     }
11838     if (R & TrueFlag)
11839       return StringRef("true");
11840     if (R & FalseFlag)
11841       return StringRef("false");
11842     return llvm::None;
11843   }
11844 };
11845 }
11846 
11847 static bool HasEnumType(Expr *E) {
11848   // Strip off implicit integral promotions.
11849   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11850     if (ICE->getCastKind() != CK_IntegralCast &&
11851         ICE->getCastKind() != CK_NoOp)
11852       break;
11853     E = ICE->getSubExpr();
11854   }
11855 
11856   return E->getType()->isEnumeralType();
11857 }
11858 
11859 static int classifyConstantValue(Expr *Constant) {
11860   // The values of this enumeration are used in the diagnostics
11861   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11862   enum ConstantValueKind {
11863     Miscellaneous = 0,
11864     LiteralTrue,
11865     LiteralFalse
11866   };
11867   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11868     return BL->getValue() ? ConstantValueKind::LiteralTrue
11869                           : ConstantValueKind::LiteralFalse;
11870   return ConstantValueKind::Miscellaneous;
11871 }
11872 
11873 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11874                                         Expr *Constant, Expr *Other,
11875                                         const llvm::APSInt &Value,
11876                                         bool RhsConstant) {
11877   if (S.inTemplateInstantiation())
11878     return false;
11879 
11880   Expr *OriginalOther = Other;
11881 
11882   Constant = Constant->IgnoreParenImpCasts();
11883   Other = Other->IgnoreParenImpCasts();
11884 
11885   // Suppress warnings on tautological comparisons between values of the same
11886   // enumeration type. There are only two ways we could warn on this:
11887   //  - If the constant is outside the range of representable values of
11888   //    the enumeration. In such a case, we should warn about the cast
11889   //    to enumeration type, not about the comparison.
11890   //  - If the constant is the maximum / minimum in-range value. For an
11891   //    enumeratin type, such comparisons can be meaningful and useful.
11892   if (Constant->getType()->isEnumeralType() &&
11893       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11894     return false;
11895 
11896   IntRange OtherValueRange = GetExprRange(
11897       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11898 
11899   QualType OtherT = Other->getType();
11900   if (const auto *AT = OtherT->getAs<AtomicType>())
11901     OtherT = AT->getValueType();
11902   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11903 
11904   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11905   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11906   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11907                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11908                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11909 
11910   // Whether we're treating Other as being a bool because of the form of
11911   // expression despite it having another type (typically 'int' in C).
11912   bool OtherIsBooleanDespiteType =
11913       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11914   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11915     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11916 
11917   // Check if all values in the range of possible values of this expression
11918   // lead to the same comparison outcome.
11919   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11920                                         Value.isUnsigned());
11921   auto Cmp = OtherPromotedValueRange.compare(Value);
11922   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11923   if (!Result)
11924     return false;
11925 
11926   // Also consider the range determined by the type alone. This allows us to
11927   // classify the warning under the proper diagnostic group.
11928   bool TautologicalTypeCompare = false;
11929   {
11930     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11931                                          Value.isUnsigned());
11932     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11933     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11934                                                        RhsConstant)) {
11935       TautologicalTypeCompare = true;
11936       Cmp = TypeCmp;
11937       Result = TypeResult;
11938     }
11939   }
11940 
11941   // Don't warn if the non-constant operand actually always evaluates to the
11942   // same value.
11943   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11944     return false;
11945 
11946   // Suppress the diagnostic for an in-range comparison if the constant comes
11947   // from a macro or enumerator. We don't want to diagnose
11948   //
11949   //   some_long_value <= INT_MAX
11950   //
11951   // when sizeof(int) == sizeof(long).
11952   bool InRange = Cmp & PromotedRange::InRangeFlag;
11953   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11954     return false;
11955 
11956   // A comparison of an unsigned bit-field against 0 is really a type problem,
11957   // even though at the type level the bit-field might promote to 'signed int'.
11958   if (Other->refersToBitField() && InRange && Value == 0 &&
11959       Other->getType()->isUnsignedIntegerOrEnumerationType())
11960     TautologicalTypeCompare = true;
11961 
11962   // If this is a comparison to an enum constant, include that
11963   // constant in the diagnostic.
11964   const EnumConstantDecl *ED = nullptr;
11965   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11966     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11967 
11968   // Should be enough for uint128 (39 decimal digits)
11969   SmallString<64> PrettySourceValue;
11970   llvm::raw_svector_ostream OS(PrettySourceValue);
11971   if (ED) {
11972     OS << '\'' << *ED << "' (" << Value << ")";
11973   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11974                Constant->IgnoreParenImpCasts())) {
11975     OS << (BL->getValue() ? "YES" : "NO");
11976   } else {
11977     OS << Value;
11978   }
11979 
11980   if (!TautologicalTypeCompare) {
11981     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11982         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11983         << E->getOpcodeStr() << OS.str() << *Result
11984         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11985     return true;
11986   }
11987 
11988   if (IsObjCSignedCharBool) {
11989     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11990                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11991                               << OS.str() << *Result);
11992     return true;
11993   }
11994 
11995   // FIXME: We use a somewhat different formatting for the in-range cases and
11996   // cases involving boolean values for historical reasons. We should pick a
11997   // consistent way of presenting these diagnostics.
11998   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11999 
12000     S.DiagRuntimeBehavior(
12001         E->getOperatorLoc(), E,
12002         S.PDiag(!InRange ? diag::warn_out_of_range_compare
12003                          : diag::warn_tautological_bool_compare)
12004             << OS.str() << classifyConstantValue(Constant) << OtherT
12005             << OtherIsBooleanDespiteType << *Result
12006             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12007   } else {
12008     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12009     unsigned Diag =
12010         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12011             ? (HasEnumType(OriginalOther)
12012                    ? diag::warn_unsigned_enum_always_true_comparison
12013                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12014                               : diag::warn_unsigned_always_true_comparison)
12015             : diag::warn_tautological_constant_compare;
12016 
12017     S.Diag(E->getOperatorLoc(), Diag)
12018         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12019         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12020   }
12021 
12022   return true;
12023 }
12024 
12025 /// Analyze the operands of the given comparison.  Implements the
12026 /// fallback case from AnalyzeComparison.
12027 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12028   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12029   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12030 }
12031 
12032 /// Implements -Wsign-compare.
12033 ///
12034 /// \param E the binary operator to check for warnings
12035 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12036   // The type the comparison is being performed in.
12037   QualType T = E->getLHS()->getType();
12038 
12039   // Only analyze comparison operators where both sides have been converted to
12040   // the same type.
12041   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12042     return AnalyzeImpConvsInComparison(S, E);
12043 
12044   // Don't analyze value-dependent comparisons directly.
12045   if (E->isValueDependent())
12046     return AnalyzeImpConvsInComparison(S, E);
12047 
12048   Expr *LHS = E->getLHS();
12049   Expr *RHS = E->getRHS();
12050 
12051   if (T->isIntegralType(S.Context)) {
12052     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
12053     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
12054 
12055     // We don't care about expressions whose result is a constant.
12056     if (RHSValue && LHSValue)
12057       return AnalyzeImpConvsInComparison(S, E);
12058 
12059     // We only care about expressions where just one side is literal
12060     if ((bool)RHSValue ^ (bool)LHSValue) {
12061       // Is the constant on the RHS or LHS?
12062       const bool RhsConstant = (bool)RHSValue;
12063       Expr *Const = RhsConstant ? RHS : LHS;
12064       Expr *Other = RhsConstant ? LHS : RHS;
12065       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12066 
12067       // Check whether an integer constant comparison results in a value
12068       // of 'true' or 'false'.
12069       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12070         return AnalyzeImpConvsInComparison(S, E);
12071     }
12072   }
12073 
12074   if (!T->hasUnsignedIntegerRepresentation()) {
12075     // We don't do anything special if this isn't an unsigned integral
12076     // comparison:  we're only interested in integral comparisons, and
12077     // signed comparisons only happen in cases we don't care to warn about.
12078     return AnalyzeImpConvsInComparison(S, E);
12079   }
12080 
12081   LHS = LHS->IgnoreParenImpCasts();
12082   RHS = RHS->IgnoreParenImpCasts();
12083 
12084   if (!S.getLangOpts().CPlusPlus) {
12085     // Avoid warning about comparison of integers with different signs when
12086     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12087     // the type of `E`.
12088     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12089       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12090     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12091       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12092   }
12093 
12094   // Check to see if one of the (unmodified) operands is of different
12095   // signedness.
12096   Expr *signedOperand, *unsignedOperand;
12097   if (LHS->getType()->hasSignedIntegerRepresentation()) {
12098     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12099            "unsigned comparison between two signed integer expressions?");
12100     signedOperand = LHS;
12101     unsignedOperand = RHS;
12102   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12103     signedOperand = RHS;
12104     unsignedOperand = LHS;
12105   } else {
12106     return AnalyzeImpConvsInComparison(S, E);
12107   }
12108 
12109   // Otherwise, calculate the effective range of the signed operand.
12110   IntRange signedRange = GetExprRange(
12111       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
12112 
12113   // Go ahead and analyze implicit conversions in the operands.  Note
12114   // that we skip the implicit conversions on both sides.
12115   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
12116   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
12117 
12118   // If the signed range is non-negative, -Wsign-compare won't fire.
12119   if (signedRange.NonNegative)
12120     return;
12121 
12122   // For (in)equality comparisons, if the unsigned operand is a
12123   // constant which cannot collide with a overflowed signed operand,
12124   // then reinterpreting the signed operand as unsigned will not
12125   // change the result of the comparison.
12126   if (E->isEqualityOp()) {
12127     unsigned comparisonWidth = S.Context.getIntWidth(T);
12128     IntRange unsignedRange =
12129         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
12130                      /*Approximate*/ true);
12131 
12132     // We should never be unable to prove that the unsigned operand is
12133     // non-negative.
12134     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
12135 
12136     if (unsignedRange.Width < comparisonWidth)
12137       return;
12138   }
12139 
12140   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12141                         S.PDiag(diag::warn_mixed_sign_comparison)
12142                             << LHS->getType() << RHS->getType()
12143                             << LHS->getSourceRange() << RHS->getSourceRange());
12144 }
12145 
12146 /// Analyzes an attempt to assign the given value to a bitfield.
12147 ///
12148 /// Returns true if there was something fishy about the attempt.
12149 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12150                                       SourceLocation InitLoc) {
12151   assert(Bitfield->isBitField());
12152   if (Bitfield->isInvalidDecl())
12153     return false;
12154 
12155   // White-list bool bitfields.
12156   QualType BitfieldType = Bitfield->getType();
12157   if (BitfieldType->isBooleanType())
12158      return false;
12159 
12160   if (BitfieldType->isEnumeralType()) {
12161     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12162     // If the underlying enum type was not explicitly specified as an unsigned
12163     // type and the enum contain only positive values, MSVC++ will cause an
12164     // inconsistency by storing this as a signed type.
12165     if (S.getLangOpts().CPlusPlus11 &&
12166         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12167         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12168         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12169       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12170           << BitfieldEnumDecl;
12171     }
12172   }
12173 
12174   if (Bitfield->getType()->isBooleanType())
12175     return false;
12176 
12177   // Ignore value- or type-dependent expressions.
12178   if (Bitfield->getBitWidth()->isValueDependent() ||
12179       Bitfield->getBitWidth()->isTypeDependent() ||
12180       Init->isValueDependent() ||
12181       Init->isTypeDependent())
12182     return false;
12183 
12184   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12185   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12186 
12187   Expr::EvalResult Result;
12188   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12189                                    Expr::SE_AllowSideEffects)) {
12190     // The RHS is not constant.  If the RHS has an enum type, make sure the
12191     // bitfield is wide enough to hold all the values of the enum without
12192     // truncation.
12193     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12194       EnumDecl *ED = EnumTy->getDecl();
12195       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12196 
12197       // Enum types are implicitly signed on Windows, so check if there are any
12198       // negative enumerators to see if the enum was intended to be signed or
12199       // not.
12200       bool SignedEnum = ED->getNumNegativeBits() > 0;
12201 
12202       // Check for surprising sign changes when assigning enum values to a
12203       // bitfield of different signedness.  If the bitfield is signed and we
12204       // have exactly the right number of bits to store this unsigned enum,
12205       // suggest changing the enum to an unsigned type. This typically happens
12206       // on Windows where unfixed enums always use an underlying type of 'int'.
12207       unsigned DiagID = 0;
12208       if (SignedEnum && !SignedBitfield) {
12209         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12210       } else if (SignedBitfield && !SignedEnum &&
12211                  ED->getNumPositiveBits() == FieldWidth) {
12212         DiagID = diag::warn_signed_bitfield_enum_conversion;
12213       }
12214 
12215       if (DiagID) {
12216         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12217         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12218         SourceRange TypeRange =
12219             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12220         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12221             << SignedEnum << TypeRange;
12222       }
12223 
12224       // Compute the required bitwidth. If the enum has negative values, we need
12225       // one more bit than the normal number of positive bits to represent the
12226       // sign bit.
12227       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12228                                                   ED->getNumNegativeBits())
12229                                        : ED->getNumPositiveBits();
12230 
12231       // Check the bitwidth.
12232       if (BitsNeeded > FieldWidth) {
12233         Expr *WidthExpr = Bitfield->getBitWidth();
12234         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12235             << Bitfield << ED;
12236         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12237             << BitsNeeded << ED << WidthExpr->getSourceRange();
12238       }
12239     }
12240 
12241     return false;
12242   }
12243 
12244   llvm::APSInt Value = Result.Val.getInt();
12245 
12246   unsigned OriginalWidth = Value.getBitWidth();
12247 
12248   if (!Value.isSigned() || Value.isNegative())
12249     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12250       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12251         OriginalWidth = Value.getMinSignedBits();
12252 
12253   if (OriginalWidth <= FieldWidth)
12254     return false;
12255 
12256   // Compute the value which the bitfield will contain.
12257   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12258   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12259 
12260   // Check whether the stored value is equal to the original value.
12261   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12262   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12263     return false;
12264 
12265   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12266   // therefore don't strictly fit into a signed bitfield of width 1.
12267   if (FieldWidth == 1 && Value == 1)
12268     return false;
12269 
12270   std::string PrettyValue = toString(Value, 10);
12271   std::string PrettyTrunc = toString(TruncatedValue, 10);
12272 
12273   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12274     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12275     << Init->getSourceRange();
12276 
12277   return true;
12278 }
12279 
12280 /// Analyze the given simple or compound assignment for warning-worthy
12281 /// operations.
12282 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12283   // Just recurse on the LHS.
12284   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12285 
12286   // We want to recurse on the RHS as normal unless we're assigning to
12287   // a bitfield.
12288   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12289     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12290                                   E->getOperatorLoc())) {
12291       // Recurse, ignoring any implicit conversions on the RHS.
12292       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12293                                         E->getOperatorLoc());
12294     }
12295   }
12296 
12297   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12298 
12299   // Diagnose implicitly sequentially-consistent atomic assignment.
12300   if (E->getLHS()->getType()->isAtomicType())
12301     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12302 }
12303 
12304 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12305 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12306                             SourceLocation CContext, unsigned diag,
12307                             bool pruneControlFlow = false) {
12308   if (pruneControlFlow) {
12309     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12310                           S.PDiag(diag)
12311                               << SourceType << T << E->getSourceRange()
12312                               << SourceRange(CContext));
12313     return;
12314   }
12315   S.Diag(E->getExprLoc(), diag)
12316     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12317 }
12318 
12319 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12320 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12321                             SourceLocation CContext,
12322                             unsigned diag, bool pruneControlFlow = false) {
12323   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12324 }
12325 
12326 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12327   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12328       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12329 }
12330 
12331 static void adornObjCBoolConversionDiagWithTernaryFixit(
12332     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12333   Expr *Ignored = SourceExpr->IgnoreImplicit();
12334   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12335     Ignored = OVE->getSourceExpr();
12336   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12337                      isa<BinaryOperator>(Ignored) ||
12338                      isa<CXXOperatorCallExpr>(Ignored);
12339   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12340   if (NeedsParens)
12341     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12342             << FixItHint::CreateInsertion(EndLoc, ")");
12343   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12344 }
12345 
12346 /// Diagnose an implicit cast from a floating point value to an integer value.
12347 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12348                                     SourceLocation CContext) {
12349   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12350   const bool PruneWarnings = S.inTemplateInstantiation();
12351 
12352   Expr *InnerE = E->IgnoreParenImpCasts();
12353   // We also want to warn on, e.g., "int i = -1.234"
12354   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12355     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12356       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12357 
12358   const bool IsLiteral =
12359       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12360 
12361   llvm::APFloat Value(0.0);
12362   bool IsConstant =
12363     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12364   if (!IsConstant) {
12365     if (isObjCSignedCharBool(S, T)) {
12366       return adornObjCBoolConversionDiagWithTernaryFixit(
12367           S, E,
12368           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12369               << E->getType());
12370     }
12371 
12372     return DiagnoseImpCast(S, E, T, CContext,
12373                            diag::warn_impcast_float_integer, PruneWarnings);
12374   }
12375 
12376   bool isExact = false;
12377 
12378   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12379                             T->hasUnsignedIntegerRepresentation());
12380   llvm::APFloat::opStatus Result = Value.convertToInteger(
12381       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12382 
12383   // FIXME: Force the precision of the source value down so we don't print
12384   // digits which are usually useless (we don't really care here if we
12385   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12386   // would automatically print the shortest representation, but it's a bit
12387   // tricky to implement.
12388   SmallString<16> PrettySourceValue;
12389   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12390   precision = (precision * 59 + 195) / 196;
12391   Value.toString(PrettySourceValue, precision);
12392 
12393   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12394     return adornObjCBoolConversionDiagWithTernaryFixit(
12395         S, E,
12396         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12397             << PrettySourceValue);
12398   }
12399 
12400   if (Result == llvm::APFloat::opOK && isExact) {
12401     if (IsLiteral) return;
12402     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12403                            PruneWarnings);
12404   }
12405 
12406   // Conversion of a floating-point value to a non-bool integer where the
12407   // integral part cannot be represented by the integer type is undefined.
12408   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12409     return DiagnoseImpCast(
12410         S, E, T, CContext,
12411         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12412                   : diag::warn_impcast_float_to_integer_out_of_range,
12413         PruneWarnings);
12414 
12415   unsigned DiagID = 0;
12416   if (IsLiteral) {
12417     // Warn on floating point literal to integer.
12418     DiagID = diag::warn_impcast_literal_float_to_integer;
12419   } else if (IntegerValue == 0) {
12420     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12421       return DiagnoseImpCast(S, E, T, CContext,
12422                              diag::warn_impcast_float_integer, PruneWarnings);
12423     }
12424     // Warn on non-zero to zero conversion.
12425     DiagID = diag::warn_impcast_float_to_integer_zero;
12426   } else {
12427     if (IntegerValue.isUnsigned()) {
12428       if (!IntegerValue.isMaxValue()) {
12429         return DiagnoseImpCast(S, E, T, CContext,
12430                                diag::warn_impcast_float_integer, PruneWarnings);
12431       }
12432     } else {  // IntegerValue.isSigned()
12433       if (!IntegerValue.isMaxSignedValue() &&
12434           !IntegerValue.isMinSignedValue()) {
12435         return DiagnoseImpCast(S, E, T, CContext,
12436                                diag::warn_impcast_float_integer, PruneWarnings);
12437       }
12438     }
12439     // Warn on evaluatable floating point expression to integer conversion.
12440     DiagID = diag::warn_impcast_float_to_integer;
12441   }
12442 
12443   SmallString<16> PrettyTargetValue;
12444   if (IsBool)
12445     PrettyTargetValue = Value.isZero() ? "false" : "true";
12446   else
12447     IntegerValue.toString(PrettyTargetValue);
12448 
12449   if (PruneWarnings) {
12450     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12451                           S.PDiag(DiagID)
12452                               << E->getType() << T.getUnqualifiedType()
12453                               << PrettySourceValue << PrettyTargetValue
12454                               << E->getSourceRange() << SourceRange(CContext));
12455   } else {
12456     S.Diag(E->getExprLoc(), DiagID)
12457         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12458         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12459   }
12460 }
12461 
12462 /// Analyze the given compound assignment for the possible losing of
12463 /// floating-point precision.
12464 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12465   assert(isa<CompoundAssignOperator>(E) &&
12466          "Must be compound assignment operation");
12467   // Recurse on the LHS and RHS in here
12468   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12469   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12470 
12471   if (E->getLHS()->getType()->isAtomicType())
12472     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12473 
12474   // Now check the outermost expression
12475   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12476   const auto *RBT = cast<CompoundAssignOperator>(E)
12477                         ->getComputationResultType()
12478                         ->getAs<BuiltinType>();
12479 
12480   // The below checks assume source is floating point.
12481   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12482 
12483   // If source is floating point but target is an integer.
12484   if (ResultBT->isInteger())
12485     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12486                            E->getExprLoc(), diag::warn_impcast_float_integer);
12487 
12488   if (!ResultBT->isFloatingPoint())
12489     return;
12490 
12491   // If both source and target are floating points, warn about losing precision.
12492   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12493       QualType(ResultBT, 0), QualType(RBT, 0));
12494   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12495     // warn about dropping FP rank.
12496     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12497                     diag::warn_impcast_float_result_precision);
12498 }
12499 
12500 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12501                                       IntRange Range) {
12502   if (!Range.Width) return "0";
12503 
12504   llvm::APSInt ValueInRange = Value;
12505   ValueInRange.setIsSigned(!Range.NonNegative);
12506   ValueInRange = ValueInRange.trunc(Range.Width);
12507   return toString(ValueInRange, 10);
12508 }
12509 
12510 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12511   if (!isa<ImplicitCastExpr>(Ex))
12512     return false;
12513 
12514   Expr *InnerE = Ex->IgnoreParenImpCasts();
12515   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12516   const Type *Source =
12517     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12518   if (Target->isDependentType())
12519     return false;
12520 
12521   const BuiltinType *FloatCandidateBT =
12522     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12523   const Type *BoolCandidateType = ToBool ? Target : Source;
12524 
12525   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12526           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12527 }
12528 
12529 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12530                                              SourceLocation CC) {
12531   unsigned NumArgs = TheCall->getNumArgs();
12532   for (unsigned i = 0; i < NumArgs; ++i) {
12533     Expr *CurrA = TheCall->getArg(i);
12534     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12535       continue;
12536 
12537     bool IsSwapped = ((i > 0) &&
12538         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12539     IsSwapped |= ((i < (NumArgs - 1)) &&
12540         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12541     if (IsSwapped) {
12542       // Warn on this floating-point to bool conversion.
12543       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12544                       CurrA->getType(), CC,
12545                       diag::warn_impcast_floating_point_to_bool);
12546     }
12547   }
12548 }
12549 
12550 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12551                                    SourceLocation CC) {
12552   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12553                         E->getExprLoc()))
12554     return;
12555 
12556   // Don't warn on functions which have return type nullptr_t.
12557   if (isa<CallExpr>(E))
12558     return;
12559 
12560   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12561   const Expr::NullPointerConstantKind NullKind =
12562       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12563   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12564     return;
12565 
12566   // Return if target type is a safe conversion.
12567   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12568       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12569     return;
12570 
12571   SourceLocation Loc = E->getSourceRange().getBegin();
12572 
12573   // Venture through the macro stacks to get to the source of macro arguments.
12574   // The new location is a better location than the complete location that was
12575   // passed in.
12576   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12577   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12578 
12579   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12580   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12581     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12582         Loc, S.SourceMgr, S.getLangOpts());
12583     if (MacroName == "NULL")
12584       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12585   }
12586 
12587   // Only warn if the null and context location are in the same macro expansion.
12588   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12589     return;
12590 
12591   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12592       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12593       << FixItHint::CreateReplacement(Loc,
12594                                       S.getFixItZeroLiteralForType(T, Loc));
12595 }
12596 
12597 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12598                                   ObjCArrayLiteral *ArrayLiteral);
12599 
12600 static void
12601 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12602                            ObjCDictionaryLiteral *DictionaryLiteral);
12603 
12604 /// Check a single element within a collection literal against the
12605 /// target element type.
12606 static void checkObjCCollectionLiteralElement(Sema &S,
12607                                               QualType TargetElementType,
12608                                               Expr *Element,
12609                                               unsigned ElementKind) {
12610   // Skip a bitcast to 'id' or qualified 'id'.
12611   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12612     if (ICE->getCastKind() == CK_BitCast &&
12613         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12614       Element = ICE->getSubExpr();
12615   }
12616 
12617   QualType ElementType = Element->getType();
12618   ExprResult ElementResult(Element);
12619   if (ElementType->getAs<ObjCObjectPointerType>() &&
12620       S.CheckSingleAssignmentConstraints(TargetElementType,
12621                                          ElementResult,
12622                                          false, false)
12623         != Sema::Compatible) {
12624     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12625         << ElementType << ElementKind << TargetElementType
12626         << Element->getSourceRange();
12627   }
12628 
12629   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12630     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12631   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12632     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12633 }
12634 
12635 /// Check an Objective-C array literal being converted to the given
12636 /// target type.
12637 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12638                                   ObjCArrayLiteral *ArrayLiteral) {
12639   if (!S.NSArrayDecl)
12640     return;
12641 
12642   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12643   if (!TargetObjCPtr)
12644     return;
12645 
12646   if (TargetObjCPtr->isUnspecialized() ||
12647       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12648         != S.NSArrayDecl->getCanonicalDecl())
12649     return;
12650 
12651   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12652   if (TypeArgs.size() != 1)
12653     return;
12654 
12655   QualType TargetElementType = TypeArgs[0];
12656   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12657     checkObjCCollectionLiteralElement(S, TargetElementType,
12658                                       ArrayLiteral->getElement(I),
12659                                       0);
12660   }
12661 }
12662 
12663 /// Check an Objective-C dictionary literal being converted to the given
12664 /// target type.
12665 static void
12666 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12667                            ObjCDictionaryLiteral *DictionaryLiteral) {
12668   if (!S.NSDictionaryDecl)
12669     return;
12670 
12671   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12672   if (!TargetObjCPtr)
12673     return;
12674 
12675   if (TargetObjCPtr->isUnspecialized() ||
12676       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12677         != S.NSDictionaryDecl->getCanonicalDecl())
12678     return;
12679 
12680   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12681   if (TypeArgs.size() != 2)
12682     return;
12683 
12684   QualType TargetKeyType = TypeArgs[0];
12685   QualType TargetObjectType = TypeArgs[1];
12686   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12687     auto Element = DictionaryLiteral->getKeyValueElement(I);
12688     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12689     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12690   }
12691 }
12692 
12693 // Helper function to filter out cases for constant width constant conversion.
12694 // Don't warn on char array initialization or for non-decimal values.
12695 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12696                                           SourceLocation CC) {
12697   // If initializing from a constant, and the constant starts with '0',
12698   // then it is a binary, octal, or hexadecimal.  Allow these constants
12699   // to fill all the bits, even if there is a sign change.
12700   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12701     const char FirstLiteralCharacter =
12702         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12703     if (FirstLiteralCharacter == '0')
12704       return false;
12705   }
12706 
12707   // If the CC location points to a '{', and the type is char, then assume
12708   // assume it is an array initialization.
12709   if (CC.isValid() && T->isCharType()) {
12710     const char FirstContextCharacter =
12711         S.getSourceManager().getCharacterData(CC)[0];
12712     if (FirstContextCharacter == '{')
12713       return false;
12714   }
12715 
12716   return true;
12717 }
12718 
12719 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12720   const auto *IL = dyn_cast<IntegerLiteral>(E);
12721   if (!IL) {
12722     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12723       if (UO->getOpcode() == UO_Minus)
12724         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12725     }
12726   }
12727 
12728   return IL;
12729 }
12730 
12731 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12732   E = E->IgnoreParenImpCasts();
12733   SourceLocation ExprLoc = E->getExprLoc();
12734 
12735   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12736     BinaryOperator::Opcode Opc = BO->getOpcode();
12737     Expr::EvalResult Result;
12738     // Do not diagnose unsigned shifts.
12739     if (Opc == BO_Shl) {
12740       const auto *LHS = getIntegerLiteral(BO->getLHS());
12741       const auto *RHS = getIntegerLiteral(BO->getRHS());
12742       if (LHS && LHS->getValue() == 0)
12743         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12744       else if (!E->isValueDependent() && LHS && RHS &&
12745                RHS->getValue().isNonNegative() &&
12746                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12747         S.Diag(ExprLoc, diag::warn_left_shift_always)
12748             << (Result.Val.getInt() != 0);
12749       else if (E->getType()->isSignedIntegerType())
12750         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12751     }
12752   }
12753 
12754   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12755     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12756     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12757     if (!LHS || !RHS)
12758       return;
12759     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12760         (RHS->getValue() == 0 || RHS->getValue() == 1))
12761       // Do not diagnose common idioms.
12762       return;
12763     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12764       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12765   }
12766 }
12767 
12768 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12769                                     SourceLocation CC,
12770                                     bool *ICContext = nullptr,
12771                                     bool IsListInit = false) {
12772   if (E->isTypeDependent() || E->isValueDependent()) return;
12773 
12774   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12775   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12776   if (Source == Target) return;
12777   if (Target->isDependentType()) return;
12778 
12779   // If the conversion context location is invalid don't complain. We also
12780   // don't want to emit a warning if the issue occurs from the expansion of
12781   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12782   // delay this check as long as possible. Once we detect we are in that
12783   // scenario, we just return.
12784   if (CC.isInvalid())
12785     return;
12786 
12787   if (Source->isAtomicType())
12788     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12789 
12790   // Diagnose implicit casts to bool.
12791   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12792     if (isa<StringLiteral>(E))
12793       // Warn on string literal to bool.  Checks for string literals in logical
12794       // and expressions, for instance, assert(0 && "error here"), are
12795       // prevented by a check in AnalyzeImplicitConversions().
12796       return DiagnoseImpCast(S, E, T, CC,
12797                              diag::warn_impcast_string_literal_to_bool);
12798     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12799         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12800       // This covers the literal expressions that evaluate to Objective-C
12801       // objects.
12802       return DiagnoseImpCast(S, E, T, CC,
12803                              diag::warn_impcast_objective_c_literal_to_bool);
12804     }
12805     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12806       // Warn on pointer to bool conversion that is always true.
12807       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12808                                      SourceRange(CC));
12809     }
12810   }
12811 
12812   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12813   // is a typedef for signed char (macOS), then that constant value has to be 1
12814   // or 0.
12815   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12816     Expr::EvalResult Result;
12817     if (E->EvaluateAsInt(Result, S.getASTContext(),
12818                          Expr::SE_AllowSideEffects)) {
12819       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12820         adornObjCBoolConversionDiagWithTernaryFixit(
12821             S, E,
12822             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12823                 << toString(Result.Val.getInt(), 10));
12824       }
12825       return;
12826     }
12827   }
12828 
12829   // Check implicit casts from Objective-C collection literals to specialized
12830   // collection types, e.g., NSArray<NSString *> *.
12831   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12832     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12833   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12834     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12835 
12836   // Strip vector types.
12837   if (isa<VectorType>(Source)) {
12838     if (Target->isVLSTBuiltinType() &&
12839         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
12840                                          QualType(Source, 0)) ||
12841          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
12842                                             QualType(Source, 0))))
12843       return;
12844 
12845     if (!isa<VectorType>(Target)) {
12846       if (S.SourceMgr.isInSystemMacro(CC))
12847         return;
12848       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12849     }
12850 
12851     // If the vector cast is cast between two vectors of the same size, it is
12852     // a bitcast, not a conversion.
12853     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12854       return;
12855 
12856     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12857     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12858   }
12859   if (auto VecTy = dyn_cast<VectorType>(Target))
12860     Target = VecTy->getElementType().getTypePtr();
12861 
12862   // Strip complex types.
12863   if (isa<ComplexType>(Source)) {
12864     if (!isa<ComplexType>(Target)) {
12865       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12866         return;
12867 
12868       return DiagnoseImpCast(S, E, T, CC,
12869                              S.getLangOpts().CPlusPlus
12870                                  ? diag::err_impcast_complex_scalar
12871                                  : diag::warn_impcast_complex_scalar);
12872     }
12873 
12874     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12875     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12876   }
12877 
12878   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12879   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12880 
12881   // If the source is floating point...
12882   if (SourceBT && SourceBT->isFloatingPoint()) {
12883     // ...and the target is floating point...
12884     if (TargetBT && TargetBT->isFloatingPoint()) {
12885       // ...then warn if we're dropping FP rank.
12886 
12887       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12888           QualType(SourceBT, 0), QualType(TargetBT, 0));
12889       if (Order > 0) {
12890         // Don't warn about float constants that are precisely
12891         // representable in the target type.
12892         Expr::EvalResult result;
12893         if (E->EvaluateAsRValue(result, S.Context)) {
12894           // Value might be a float, a float vector, or a float complex.
12895           if (IsSameFloatAfterCast(result.Val,
12896                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12897                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12898             return;
12899         }
12900 
12901         if (S.SourceMgr.isInSystemMacro(CC))
12902           return;
12903 
12904         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12905       }
12906       // ... or possibly if we're increasing rank, too
12907       else if (Order < 0) {
12908         if (S.SourceMgr.isInSystemMacro(CC))
12909           return;
12910 
12911         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12912       }
12913       return;
12914     }
12915 
12916     // If the target is integral, always warn.
12917     if (TargetBT && TargetBT->isInteger()) {
12918       if (S.SourceMgr.isInSystemMacro(CC))
12919         return;
12920 
12921       DiagnoseFloatingImpCast(S, E, T, CC);
12922     }
12923 
12924     // Detect the case where a call result is converted from floating-point to
12925     // to bool, and the final argument to the call is converted from bool, to
12926     // discover this typo:
12927     //
12928     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12929     //
12930     // FIXME: This is an incredibly special case; is there some more general
12931     // way to detect this class of misplaced-parentheses bug?
12932     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12933       // Check last argument of function call to see if it is an
12934       // implicit cast from a type matching the type the result
12935       // is being cast to.
12936       CallExpr *CEx = cast<CallExpr>(E);
12937       if (unsigned NumArgs = CEx->getNumArgs()) {
12938         Expr *LastA = CEx->getArg(NumArgs - 1);
12939         Expr *InnerE = LastA->IgnoreParenImpCasts();
12940         if (isa<ImplicitCastExpr>(LastA) &&
12941             InnerE->getType()->isBooleanType()) {
12942           // Warn on this floating-point to bool conversion
12943           DiagnoseImpCast(S, E, T, CC,
12944                           diag::warn_impcast_floating_point_to_bool);
12945         }
12946       }
12947     }
12948     return;
12949   }
12950 
12951   // Valid casts involving fixed point types should be accounted for here.
12952   if (Source->isFixedPointType()) {
12953     if (Target->isUnsaturatedFixedPointType()) {
12954       Expr::EvalResult Result;
12955       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12956                                   S.isConstantEvaluated())) {
12957         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12958         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12959         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12960         if (Value > MaxVal || Value < MinVal) {
12961           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12962                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12963                                     << Value.toString() << T
12964                                     << E->getSourceRange()
12965                                     << clang::SourceRange(CC));
12966           return;
12967         }
12968       }
12969     } else if (Target->isIntegerType()) {
12970       Expr::EvalResult Result;
12971       if (!S.isConstantEvaluated() &&
12972           E->EvaluateAsFixedPoint(Result, S.Context,
12973                                   Expr::SE_AllowSideEffects)) {
12974         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12975 
12976         bool Overflowed;
12977         llvm::APSInt IntResult = FXResult.convertToInt(
12978             S.Context.getIntWidth(T),
12979             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12980 
12981         if (Overflowed) {
12982           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12983                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12984                                     << FXResult.toString() << T
12985                                     << E->getSourceRange()
12986                                     << clang::SourceRange(CC));
12987           return;
12988         }
12989       }
12990     }
12991   } else if (Target->isUnsaturatedFixedPointType()) {
12992     if (Source->isIntegerType()) {
12993       Expr::EvalResult Result;
12994       if (!S.isConstantEvaluated() &&
12995           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12996         llvm::APSInt Value = Result.Val.getInt();
12997 
12998         bool Overflowed;
12999         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13000             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
13001 
13002         if (Overflowed) {
13003           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13004                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13005                                     << toString(Value, /*Radix=*/10) << T
13006                                     << E->getSourceRange()
13007                                     << clang::SourceRange(CC));
13008           return;
13009         }
13010       }
13011     }
13012   }
13013 
13014   // If we are casting an integer type to a floating point type without
13015   // initialization-list syntax, we might lose accuracy if the floating
13016   // point type has a narrower significand than the integer type.
13017   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13018       TargetBT->isFloatingType() && !IsListInit) {
13019     // Determine the number of precision bits in the source integer type.
13020     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
13021                                         /*Approximate*/ true);
13022     unsigned int SourcePrecision = SourceRange.Width;
13023 
13024     // Determine the number of precision bits in the
13025     // target floating point type.
13026     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13027         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13028 
13029     if (SourcePrecision > 0 && TargetPrecision > 0 &&
13030         SourcePrecision > TargetPrecision) {
13031 
13032       if (Optional<llvm::APSInt> SourceInt =
13033               E->getIntegerConstantExpr(S.Context)) {
13034         // If the source integer is a constant, convert it to the target
13035         // floating point type. Issue a warning if the value changes
13036         // during the whole conversion.
13037         llvm::APFloat TargetFloatValue(
13038             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13039         llvm::APFloat::opStatus ConversionStatus =
13040             TargetFloatValue.convertFromAPInt(
13041                 *SourceInt, SourceBT->isSignedInteger(),
13042                 llvm::APFloat::rmNearestTiesToEven);
13043 
13044         if (ConversionStatus != llvm::APFloat::opOK) {
13045           SmallString<32> PrettySourceValue;
13046           SourceInt->toString(PrettySourceValue, 10);
13047           SmallString<32> PrettyTargetValue;
13048           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13049 
13050           S.DiagRuntimeBehavior(
13051               E->getExprLoc(), E,
13052               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
13053                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
13054                   << E->getSourceRange() << clang::SourceRange(CC));
13055         }
13056       } else {
13057         // Otherwise, the implicit conversion may lose precision.
13058         DiagnoseImpCast(S, E, T, CC,
13059                         diag::warn_impcast_integer_float_precision);
13060       }
13061     }
13062   }
13063 
13064   DiagnoseNullConversion(S, E, T, CC);
13065 
13066   S.DiscardMisalignedMemberAddress(Target, E);
13067 
13068   if (Target->isBooleanType())
13069     DiagnoseIntInBoolContext(S, E);
13070 
13071   if (!Source->isIntegerType() || !Target->isIntegerType())
13072     return;
13073 
13074   // TODO: remove this early return once the false positives for constant->bool
13075   // in templates, macros, etc, are reduced or removed.
13076   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13077     return;
13078 
13079   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
13080       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13081     return adornObjCBoolConversionDiagWithTernaryFixit(
13082         S, E,
13083         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13084             << E->getType());
13085   }
13086 
13087   IntRange SourceTypeRange =
13088       IntRange::forTargetOfCanonicalType(S.Context, Source);
13089   IntRange LikelySourceRange =
13090       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
13091   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
13092 
13093   if (LikelySourceRange.Width > TargetRange.Width) {
13094     // If the source is a constant, use a default-on diagnostic.
13095     // TODO: this should happen for bitfield stores, too.
13096     Expr::EvalResult Result;
13097     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
13098                          S.isConstantEvaluated())) {
13099       llvm::APSInt Value(32);
13100       Value = Result.Val.getInt();
13101 
13102       if (S.SourceMgr.isInSystemMacro(CC))
13103         return;
13104 
13105       std::string PrettySourceValue = toString(Value, 10);
13106       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13107 
13108       S.DiagRuntimeBehavior(
13109           E->getExprLoc(), E,
13110           S.PDiag(diag::warn_impcast_integer_precision_constant)
13111               << PrettySourceValue << PrettyTargetValue << E->getType() << T
13112               << E->getSourceRange() << SourceRange(CC));
13113       return;
13114     }
13115 
13116     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13117     if (S.SourceMgr.isInSystemMacro(CC))
13118       return;
13119 
13120     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
13121       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
13122                              /* pruneControlFlow */ true);
13123     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
13124   }
13125 
13126   if (TargetRange.Width > SourceTypeRange.Width) {
13127     if (auto *UO = dyn_cast<UnaryOperator>(E))
13128       if (UO->getOpcode() == UO_Minus)
13129         if (Source->isUnsignedIntegerType()) {
13130           if (Target->isUnsignedIntegerType())
13131             return DiagnoseImpCast(S, E, T, CC,
13132                                    diag::warn_impcast_high_order_zero_bits);
13133           if (Target->isSignedIntegerType())
13134             return DiagnoseImpCast(S, E, T, CC,
13135                                    diag::warn_impcast_nonnegative_result);
13136         }
13137   }
13138 
13139   if (TargetRange.Width == LikelySourceRange.Width &&
13140       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13141       Source->isSignedIntegerType()) {
13142     // Warn when doing a signed to signed conversion, warn if the positive
13143     // source value is exactly the width of the target type, which will
13144     // cause a negative value to be stored.
13145 
13146     Expr::EvalResult Result;
13147     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
13148         !S.SourceMgr.isInSystemMacro(CC)) {
13149       llvm::APSInt Value = Result.Val.getInt();
13150       if (isSameWidthConstantConversion(S, E, T, CC)) {
13151         std::string PrettySourceValue = toString(Value, 10);
13152         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13153 
13154         S.DiagRuntimeBehavior(
13155             E->getExprLoc(), E,
13156             S.PDiag(diag::warn_impcast_integer_precision_constant)
13157                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13158                 << E->getSourceRange() << SourceRange(CC));
13159         return;
13160       }
13161     }
13162 
13163     // Fall through for non-constants to give a sign conversion warning.
13164   }
13165 
13166   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13167       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13168        LikelySourceRange.Width == TargetRange.Width)) {
13169     if (S.SourceMgr.isInSystemMacro(CC))
13170       return;
13171 
13172     unsigned DiagID = diag::warn_impcast_integer_sign;
13173 
13174     // Traditionally, gcc has warned about this under -Wsign-compare.
13175     // We also want to warn about it in -Wconversion.
13176     // So if -Wconversion is off, use a completely identical diagnostic
13177     // in the sign-compare group.
13178     // The conditional-checking code will
13179     if (ICContext) {
13180       DiagID = diag::warn_impcast_integer_sign_conditional;
13181       *ICContext = true;
13182     }
13183 
13184     return DiagnoseImpCast(S, E, T, CC, DiagID);
13185   }
13186 
13187   // Diagnose conversions between different enumeration types.
13188   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13189   // type, to give us better diagnostics.
13190   QualType SourceType = E->getType();
13191   if (!S.getLangOpts().CPlusPlus) {
13192     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13193       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13194         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13195         SourceType = S.Context.getTypeDeclType(Enum);
13196         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13197       }
13198   }
13199 
13200   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13201     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13202       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13203           TargetEnum->getDecl()->hasNameForLinkage() &&
13204           SourceEnum != TargetEnum) {
13205         if (S.SourceMgr.isInSystemMacro(CC))
13206           return;
13207 
13208         return DiagnoseImpCast(S, E, SourceType, T, CC,
13209                                diag::warn_impcast_different_enum_types);
13210       }
13211 }
13212 
13213 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13214                                      SourceLocation CC, QualType T);
13215 
13216 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13217                                     SourceLocation CC, bool &ICContext) {
13218   E = E->IgnoreParenImpCasts();
13219 
13220   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13221     return CheckConditionalOperator(S, CO, CC, T);
13222 
13223   AnalyzeImplicitConversions(S, E, CC);
13224   if (E->getType() != T)
13225     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13226 }
13227 
13228 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13229                                      SourceLocation CC, QualType T) {
13230   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13231 
13232   Expr *TrueExpr = E->getTrueExpr();
13233   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13234     TrueExpr = BCO->getCommon();
13235 
13236   bool Suspicious = false;
13237   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13238   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13239 
13240   if (T->isBooleanType())
13241     DiagnoseIntInBoolContext(S, E);
13242 
13243   // If -Wconversion would have warned about either of the candidates
13244   // for a signedness conversion to the context type...
13245   if (!Suspicious) return;
13246 
13247   // ...but it's currently ignored...
13248   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13249     return;
13250 
13251   // ...then check whether it would have warned about either of the
13252   // candidates for a signedness conversion to the condition type.
13253   if (E->getType() == T) return;
13254 
13255   Suspicious = false;
13256   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13257                           E->getType(), CC, &Suspicious);
13258   if (!Suspicious)
13259     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13260                             E->getType(), CC, &Suspicious);
13261 }
13262 
13263 /// Check conversion of given expression to boolean.
13264 /// Input argument E is a logical expression.
13265 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13266   if (S.getLangOpts().Bool)
13267     return;
13268   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13269     return;
13270   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13271 }
13272 
13273 namespace {
13274 struct AnalyzeImplicitConversionsWorkItem {
13275   Expr *E;
13276   SourceLocation CC;
13277   bool IsListInit;
13278 };
13279 }
13280 
13281 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13282 /// that should be visited are added to WorkList.
13283 static void AnalyzeImplicitConversions(
13284     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13285     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13286   Expr *OrigE = Item.E;
13287   SourceLocation CC = Item.CC;
13288 
13289   QualType T = OrigE->getType();
13290   Expr *E = OrigE->IgnoreParenImpCasts();
13291 
13292   // Propagate whether we are in a C++ list initialization expression.
13293   // If so, we do not issue warnings for implicit int-float conversion
13294   // precision loss, because C++11 narrowing already handles it.
13295   bool IsListInit = Item.IsListInit ||
13296                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13297 
13298   if (E->isTypeDependent() || E->isValueDependent())
13299     return;
13300 
13301   Expr *SourceExpr = E;
13302   // Examine, but don't traverse into the source expression of an
13303   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13304   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13305   // evaluate it in the context of checking the specific conversion to T though.
13306   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13307     if (auto *Src = OVE->getSourceExpr())
13308       SourceExpr = Src;
13309 
13310   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13311     if (UO->getOpcode() == UO_Not &&
13312         UO->getSubExpr()->isKnownToHaveBooleanValue())
13313       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13314           << OrigE->getSourceRange() << T->isBooleanType()
13315           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13316 
13317   if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
13318     if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13319         BO->getLHS()->isKnownToHaveBooleanValue() &&
13320         BO->getRHS()->isKnownToHaveBooleanValue() &&
13321         BO->getLHS()->HasSideEffects(S.Context) &&
13322         BO->getRHS()->HasSideEffects(S.Context)) {
13323       S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13324           << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange()
13325           << FixItHint::CreateReplacement(
13326                  BO->getOperatorLoc(),
13327                  (BO->getOpcode() == BO_And ? "&&" : "||"));
13328       S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13329     }
13330 
13331   // For conditional operators, we analyze the arguments as if they
13332   // were being fed directly into the output.
13333   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13334     CheckConditionalOperator(S, CO, CC, T);
13335     return;
13336   }
13337 
13338   // Check implicit argument conversions for function calls.
13339   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13340     CheckImplicitArgumentConversions(S, Call, CC);
13341 
13342   // Go ahead and check any implicit conversions we might have skipped.
13343   // The non-canonical typecheck is just an optimization;
13344   // CheckImplicitConversion will filter out dead implicit conversions.
13345   if (SourceExpr->getType() != T)
13346     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13347 
13348   // Now continue drilling into this expression.
13349 
13350   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13351     // The bound subexpressions in a PseudoObjectExpr are not reachable
13352     // as transitive children.
13353     // FIXME: Use a more uniform representation for this.
13354     for (auto *SE : POE->semantics())
13355       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13356         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13357   }
13358 
13359   // Skip past explicit casts.
13360   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13361     E = CE->getSubExpr()->IgnoreParenImpCasts();
13362     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13363       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13364     WorkList.push_back({E, CC, IsListInit});
13365     return;
13366   }
13367 
13368   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13369     // Do a somewhat different check with comparison operators.
13370     if (BO->isComparisonOp())
13371       return AnalyzeComparison(S, BO);
13372 
13373     // And with simple assignments.
13374     if (BO->getOpcode() == BO_Assign)
13375       return AnalyzeAssignment(S, BO);
13376     // And with compound assignments.
13377     if (BO->isAssignmentOp())
13378       return AnalyzeCompoundAssignment(S, BO);
13379   }
13380 
13381   // These break the otherwise-useful invariant below.  Fortunately,
13382   // we don't really need to recurse into them, because any internal
13383   // expressions should have been analyzed already when they were
13384   // built into statements.
13385   if (isa<StmtExpr>(E)) return;
13386 
13387   // Don't descend into unevaluated contexts.
13388   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13389 
13390   // Now just recurse over the expression's children.
13391   CC = E->getExprLoc();
13392   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13393   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13394   for (Stmt *SubStmt : E->children()) {
13395     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13396     if (!ChildExpr)
13397       continue;
13398 
13399     if (IsLogicalAndOperator &&
13400         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13401       // Ignore checking string literals that are in logical and operators.
13402       // This is a common pattern for asserts.
13403       continue;
13404     WorkList.push_back({ChildExpr, CC, IsListInit});
13405   }
13406 
13407   if (BO && BO->isLogicalOp()) {
13408     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13409     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13410       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13411 
13412     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13413     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13414       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13415   }
13416 
13417   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13418     if (U->getOpcode() == UO_LNot) {
13419       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13420     } else if (U->getOpcode() != UO_AddrOf) {
13421       if (U->getSubExpr()->getType()->isAtomicType())
13422         S.Diag(U->getSubExpr()->getBeginLoc(),
13423                diag::warn_atomic_implicit_seq_cst);
13424     }
13425   }
13426 }
13427 
13428 /// AnalyzeImplicitConversions - Find and report any interesting
13429 /// implicit conversions in the given expression.  There are a couple
13430 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13431 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13432                                        bool IsListInit/*= false*/) {
13433   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13434   WorkList.push_back({OrigE, CC, IsListInit});
13435   while (!WorkList.empty())
13436     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13437 }
13438 
13439 /// Diagnose integer type and any valid implicit conversion to it.
13440 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13441   // Taking into account implicit conversions,
13442   // allow any integer.
13443   if (!E->getType()->isIntegerType()) {
13444     S.Diag(E->getBeginLoc(),
13445            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13446     return true;
13447   }
13448   // Potentially emit standard warnings for implicit conversions if enabled
13449   // using -Wconversion.
13450   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13451   return false;
13452 }
13453 
13454 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13455 // Returns true when emitting a warning about taking the address of a reference.
13456 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13457                               const PartialDiagnostic &PD) {
13458   E = E->IgnoreParenImpCasts();
13459 
13460   const FunctionDecl *FD = nullptr;
13461 
13462   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13463     if (!DRE->getDecl()->getType()->isReferenceType())
13464       return false;
13465   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13466     if (!M->getMemberDecl()->getType()->isReferenceType())
13467       return false;
13468   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13469     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13470       return false;
13471     FD = Call->getDirectCallee();
13472   } else {
13473     return false;
13474   }
13475 
13476   SemaRef.Diag(E->getExprLoc(), PD);
13477 
13478   // If possible, point to location of function.
13479   if (FD) {
13480     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13481   }
13482 
13483   return true;
13484 }
13485 
13486 // Returns true if the SourceLocation is expanded from any macro body.
13487 // Returns false if the SourceLocation is invalid, is from not in a macro
13488 // expansion, or is from expanded from a top-level macro argument.
13489 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13490   if (Loc.isInvalid())
13491     return false;
13492 
13493   while (Loc.isMacroID()) {
13494     if (SM.isMacroBodyExpansion(Loc))
13495       return true;
13496     Loc = SM.getImmediateMacroCallerLoc(Loc);
13497   }
13498 
13499   return false;
13500 }
13501 
13502 /// Diagnose pointers that are always non-null.
13503 /// \param E the expression containing the pointer
13504 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13505 /// compared to a null pointer
13506 /// \param IsEqual True when the comparison is equal to a null pointer
13507 /// \param Range Extra SourceRange to highlight in the diagnostic
13508 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13509                                         Expr::NullPointerConstantKind NullKind,
13510                                         bool IsEqual, SourceRange Range) {
13511   if (!E)
13512     return;
13513 
13514   // Don't warn inside macros.
13515   if (E->getExprLoc().isMacroID()) {
13516     const SourceManager &SM = getSourceManager();
13517     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13518         IsInAnyMacroBody(SM, Range.getBegin()))
13519       return;
13520   }
13521   E = E->IgnoreImpCasts();
13522 
13523   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13524 
13525   if (isa<CXXThisExpr>(E)) {
13526     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13527                                 : diag::warn_this_bool_conversion;
13528     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13529     return;
13530   }
13531 
13532   bool IsAddressOf = false;
13533 
13534   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13535     if (UO->getOpcode() != UO_AddrOf)
13536       return;
13537     IsAddressOf = true;
13538     E = UO->getSubExpr();
13539   }
13540 
13541   if (IsAddressOf) {
13542     unsigned DiagID = IsCompare
13543                           ? diag::warn_address_of_reference_null_compare
13544                           : diag::warn_address_of_reference_bool_conversion;
13545     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13546                                          << IsEqual;
13547     if (CheckForReference(*this, E, PD)) {
13548       return;
13549     }
13550   }
13551 
13552   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13553     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13554     std::string Str;
13555     llvm::raw_string_ostream S(Str);
13556     E->printPretty(S, nullptr, getPrintingPolicy());
13557     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13558                                 : diag::warn_cast_nonnull_to_bool;
13559     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13560       << E->getSourceRange() << Range << IsEqual;
13561     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13562   };
13563 
13564   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13565   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13566     if (auto *Callee = Call->getDirectCallee()) {
13567       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13568         ComplainAboutNonnullParamOrCall(A);
13569         return;
13570       }
13571     }
13572   }
13573 
13574   // Expect to find a single Decl.  Skip anything more complicated.
13575   ValueDecl *D = nullptr;
13576   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13577     D = R->getDecl();
13578   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13579     D = M->getMemberDecl();
13580   }
13581 
13582   // Weak Decls can be null.
13583   if (!D || D->isWeak())
13584     return;
13585 
13586   // Check for parameter decl with nonnull attribute
13587   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13588     if (getCurFunction() &&
13589         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13590       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13591         ComplainAboutNonnullParamOrCall(A);
13592         return;
13593       }
13594 
13595       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13596         // Skip function template not specialized yet.
13597         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13598           return;
13599         auto ParamIter = llvm::find(FD->parameters(), PV);
13600         assert(ParamIter != FD->param_end());
13601         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13602 
13603         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13604           if (!NonNull->args_size()) {
13605               ComplainAboutNonnullParamOrCall(NonNull);
13606               return;
13607           }
13608 
13609           for (const ParamIdx &ArgNo : NonNull->args()) {
13610             if (ArgNo.getASTIndex() == ParamNo) {
13611               ComplainAboutNonnullParamOrCall(NonNull);
13612               return;
13613             }
13614           }
13615         }
13616       }
13617     }
13618   }
13619 
13620   QualType T = D->getType();
13621   const bool IsArray = T->isArrayType();
13622   const bool IsFunction = T->isFunctionType();
13623 
13624   // Address of function is used to silence the function warning.
13625   if (IsAddressOf && IsFunction) {
13626     return;
13627   }
13628 
13629   // Found nothing.
13630   if (!IsAddressOf && !IsFunction && !IsArray)
13631     return;
13632 
13633   // Pretty print the expression for the diagnostic.
13634   std::string Str;
13635   llvm::raw_string_ostream S(Str);
13636   E->printPretty(S, nullptr, getPrintingPolicy());
13637 
13638   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13639                               : diag::warn_impcast_pointer_to_bool;
13640   enum {
13641     AddressOf,
13642     FunctionPointer,
13643     ArrayPointer
13644   } DiagType;
13645   if (IsAddressOf)
13646     DiagType = AddressOf;
13647   else if (IsFunction)
13648     DiagType = FunctionPointer;
13649   else if (IsArray)
13650     DiagType = ArrayPointer;
13651   else
13652     llvm_unreachable("Could not determine diagnostic.");
13653   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13654                                 << Range << IsEqual;
13655 
13656   if (!IsFunction)
13657     return;
13658 
13659   // Suggest '&' to silence the function warning.
13660   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13661       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13662 
13663   // Check to see if '()' fixit should be emitted.
13664   QualType ReturnType;
13665   UnresolvedSet<4> NonTemplateOverloads;
13666   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13667   if (ReturnType.isNull())
13668     return;
13669 
13670   if (IsCompare) {
13671     // There are two cases here.  If there is null constant, the only suggest
13672     // for a pointer return type.  If the null is 0, then suggest if the return
13673     // type is a pointer or an integer type.
13674     if (!ReturnType->isPointerType()) {
13675       if (NullKind == Expr::NPCK_ZeroExpression ||
13676           NullKind == Expr::NPCK_ZeroLiteral) {
13677         if (!ReturnType->isIntegerType())
13678           return;
13679       } else {
13680         return;
13681       }
13682     }
13683   } else { // !IsCompare
13684     // For function to bool, only suggest if the function pointer has bool
13685     // return type.
13686     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13687       return;
13688   }
13689   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13690       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13691 }
13692 
13693 /// Diagnoses "dangerous" implicit conversions within the given
13694 /// expression (which is a full expression).  Implements -Wconversion
13695 /// and -Wsign-compare.
13696 ///
13697 /// \param CC the "context" location of the implicit conversion, i.e.
13698 ///   the most location of the syntactic entity requiring the implicit
13699 ///   conversion
13700 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13701   // Don't diagnose in unevaluated contexts.
13702   if (isUnevaluatedContext())
13703     return;
13704 
13705   // Don't diagnose for value- or type-dependent expressions.
13706   if (E->isTypeDependent() || E->isValueDependent())
13707     return;
13708 
13709   // Check for array bounds violations in cases where the check isn't triggered
13710   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13711   // ArraySubscriptExpr is on the RHS of a variable initialization.
13712   CheckArrayAccess(E);
13713 
13714   // This is not the right CC for (e.g.) a variable initialization.
13715   AnalyzeImplicitConversions(*this, E, CC);
13716 }
13717 
13718 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13719 /// Input argument E is a logical expression.
13720 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13721   ::CheckBoolLikeConversion(*this, E, CC);
13722 }
13723 
13724 /// Diagnose when expression is an integer constant expression and its evaluation
13725 /// results in integer overflow
13726 void Sema::CheckForIntOverflow (Expr *E) {
13727   // Use a work list to deal with nested struct initializers.
13728   SmallVector<Expr *, 2> Exprs(1, E);
13729 
13730   do {
13731     Expr *OriginalE = Exprs.pop_back_val();
13732     Expr *E = OriginalE->IgnoreParenCasts();
13733 
13734     if (isa<BinaryOperator>(E)) {
13735       E->EvaluateForOverflow(Context);
13736       continue;
13737     }
13738 
13739     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13740       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13741     else if (isa<ObjCBoxedExpr>(OriginalE))
13742       E->EvaluateForOverflow(Context);
13743     else if (auto Call = dyn_cast<CallExpr>(E))
13744       Exprs.append(Call->arg_begin(), Call->arg_end());
13745     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13746       Exprs.append(Message->arg_begin(), Message->arg_end());
13747   } while (!Exprs.empty());
13748 }
13749 
13750 namespace {
13751 
13752 /// Visitor for expressions which looks for unsequenced operations on the
13753 /// same object.
13754 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13755   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13756 
13757   /// A tree of sequenced regions within an expression. Two regions are
13758   /// unsequenced if one is an ancestor or a descendent of the other. When we
13759   /// finish processing an expression with sequencing, such as a comma
13760   /// expression, we fold its tree nodes into its parent, since they are
13761   /// unsequenced with respect to nodes we will visit later.
13762   class SequenceTree {
13763     struct Value {
13764       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13765       unsigned Parent : 31;
13766       unsigned Merged : 1;
13767     };
13768     SmallVector<Value, 8> Values;
13769 
13770   public:
13771     /// A region within an expression which may be sequenced with respect
13772     /// to some other region.
13773     class Seq {
13774       friend class SequenceTree;
13775 
13776       unsigned Index;
13777 
13778       explicit Seq(unsigned N) : Index(N) {}
13779 
13780     public:
13781       Seq() : Index(0) {}
13782     };
13783 
13784     SequenceTree() { Values.push_back(Value(0)); }
13785     Seq root() const { return Seq(0); }
13786 
13787     /// Create a new sequence of operations, which is an unsequenced
13788     /// subset of \p Parent. This sequence of operations is sequenced with
13789     /// respect to other children of \p Parent.
13790     Seq allocate(Seq Parent) {
13791       Values.push_back(Value(Parent.Index));
13792       return Seq(Values.size() - 1);
13793     }
13794 
13795     /// Merge a sequence of operations into its parent.
13796     void merge(Seq S) {
13797       Values[S.Index].Merged = true;
13798     }
13799 
13800     /// Determine whether two operations are unsequenced. This operation
13801     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13802     /// should have been merged into its parent as appropriate.
13803     bool isUnsequenced(Seq Cur, Seq Old) {
13804       unsigned C = representative(Cur.Index);
13805       unsigned Target = representative(Old.Index);
13806       while (C >= Target) {
13807         if (C == Target)
13808           return true;
13809         C = Values[C].Parent;
13810       }
13811       return false;
13812     }
13813 
13814   private:
13815     /// Pick a representative for a sequence.
13816     unsigned representative(unsigned K) {
13817       if (Values[K].Merged)
13818         // Perform path compression as we go.
13819         return Values[K].Parent = representative(Values[K].Parent);
13820       return K;
13821     }
13822   };
13823 
13824   /// An object for which we can track unsequenced uses.
13825   using Object = const NamedDecl *;
13826 
13827   /// Different flavors of object usage which we track. We only track the
13828   /// least-sequenced usage of each kind.
13829   enum UsageKind {
13830     /// A read of an object. Multiple unsequenced reads are OK.
13831     UK_Use,
13832 
13833     /// A modification of an object which is sequenced before the value
13834     /// computation of the expression, such as ++n in C++.
13835     UK_ModAsValue,
13836 
13837     /// A modification of an object which is not sequenced before the value
13838     /// computation of the expression, such as n++.
13839     UK_ModAsSideEffect,
13840 
13841     UK_Count = UK_ModAsSideEffect + 1
13842   };
13843 
13844   /// Bundle together a sequencing region and the expression corresponding
13845   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13846   struct Usage {
13847     const Expr *UsageExpr;
13848     SequenceTree::Seq Seq;
13849 
13850     Usage() : UsageExpr(nullptr), Seq() {}
13851   };
13852 
13853   struct UsageInfo {
13854     Usage Uses[UK_Count];
13855 
13856     /// Have we issued a diagnostic for this object already?
13857     bool Diagnosed;
13858 
13859     UsageInfo() : Uses(), Diagnosed(false) {}
13860   };
13861   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13862 
13863   Sema &SemaRef;
13864 
13865   /// Sequenced regions within the expression.
13866   SequenceTree Tree;
13867 
13868   /// Declaration modifications and references which we have seen.
13869   UsageInfoMap UsageMap;
13870 
13871   /// The region we are currently within.
13872   SequenceTree::Seq Region;
13873 
13874   /// Filled in with declarations which were modified as a side-effect
13875   /// (that is, post-increment operations).
13876   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13877 
13878   /// Expressions to check later. We defer checking these to reduce
13879   /// stack usage.
13880   SmallVectorImpl<const Expr *> &WorkList;
13881 
13882   /// RAII object wrapping the visitation of a sequenced subexpression of an
13883   /// expression. At the end of this process, the side-effects of the evaluation
13884   /// become sequenced with respect to the value computation of the result, so
13885   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13886   /// UK_ModAsValue.
13887   struct SequencedSubexpression {
13888     SequencedSubexpression(SequenceChecker &Self)
13889       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13890       Self.ModAsSideEffect = &ModAsSideEffect;
13891     }
13892 
13893     ~SequencedSubexpression() {
13894       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13895         // Add a new usage with usage kind UK_ModAsValue, and then restore
13896         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13897         // the previous one was empty).
13898         UsageInfo &UI = Self.UsageMap[M.first];
13899         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13900         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13901         SideEffectUsage = M.second;
13902       }
13903       Self.ModAsSideEffect = OldModAsSideEffect;
13904     }
13905 
13906     SequenceChecker &Self;
13907     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13908     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13909   };
13910 
13911   /// RAII object wrapping the visitation of a subexpression which we might
13912   /// choose to evaluate as a constant. If any subexpression is evaluated and
13913   /// found to be non-constant, this allows us to suppress the evaluation of
13914   /// the outer expression.
13915   class EvaluationTracker {
13916   public:
13917     EvaluationTracker(SequenceChecker &Self)
13918         : Self(Self), Prev(Self.EvalTracker) {
13919       Self.EvalTracker = this;
13920     }
13921 
13922     ~EvaluationTracker() {
13923       Self.EvalTracker = Prev;
13924       if (Prev)
13925         Prev->EvalOK &= EvalOK;
13926     }
13927 
13928     bool evaluate(const Expr *E, bool &Result) {
13929       if (!EvalOK || E->isValueDependent())
13930         return false;
13931       EvalOK = E->EvaluateAsBooleanCondition(
13932           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13933       return EvalOK;
13934     }
13935 
13936   private:
13937     SequenceChecker &Self;
13938     EvaluationTracker *Prev;
13939     bool EvalOK = true;
13940   } *EvalTracker = nullptr;
13941 
13942   /// Find the object which is produced by the specified expression,
13943   /// if any.
13944   Object getObject(const Expr *E, bool Mod) const {
13945     E = E->IgnoreParenCasts();
13946     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13947       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13948         return getObject(UO->getSubExpr(), Mod);
13949     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13950       if (BO->getOpcode() == BO_Comma)
13951         return getObject(BO->getRHS(), Mod);
13952       if (Mod && BO->isAssignmentOp())
13953         return getObject(BO->getLHS(), Mod);
13954     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13955       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13956       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13957         return ME->getMemberDecl();
13958     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13959       // FIXME: If this is a reference, map through to its value.
13960       return DRE->getDecl();
13961     return nullptr;
13962   }
13963 
13964   /// Note that an object \p O was modified or used by an expression
13965   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13966   /// the object \p O as obtained via the \p UsageMap.
13967   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13968     // Get the old usage for the given object and usage kind.
13969     Usage &U = UI.Uses[UK];
13970     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13971       // If we have a modification as side effect and are in a sequenced
13972       // subexpression, save the old Usage so that we can restore it later
13973       // in SequencedSubexpression::~SequencedSubexpression.
13974       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13975         ModAsSideEffect->push_back(std::make_pair(O, U));
13976       // Then record the new usage with the current sequencing region.
13977       U.UsageExpr = UsageExpr;
13978       U.Seq = Region;
13979     }
13980   }
13981 
13982   /// Check whether a modification or use of an object \p O in an expression
13983   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13984   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13985   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13986   /// usage and false we are checking for a mod-use unsequenced usage.
13987   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13988                   UsageKind OtherKind, bool IsModMod) {
13989     if (UI.Diagnosed)
13990       return;
13991 
13992     const Usage &U = UI.Uses[OtherKind];
13993     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13994       return;
13995 
13996     const Expr *Mod = U.UsageExpr;
13997     const Expr *ModOrUse = UsageExpr;
13998     if (OtherKind == UK_Use)
13999       std::swap(Mod, ModOrUse);
14000 
14001     SemaRef.DiagRuntimeBehavior(
14002         Mod->getExprLoc(), {Mod, ModOrUse},
14003         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14004                                : diag::warn_unsequenced_mod_use)
14005             << O << SourceRange(ModOrUse->getExprLoc()));
14006     UI.Diagnosed = true;
14007   }
14008 
14009   // A note on note{Pre, Post}{Use, Mod}:
14010   //
14011   // (It helps to follow the algorithm with an expression such as
14012   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14013   //  operations before C++17 and both are well-defined in C++17).
14014   //
14015   // When visiting a node which uses/modify an object we first call notePreUse
14016   // or notePreMod before visiting its sub-expression(s). At this point the
14017   // children of the current node have not yet been visited and so the eventual
14018   // uses/modifications resulting from the children of the current node have not
14019   // been recorded yet.
14020   //
14021   // We then visit the children of the current node. After that notePostUse or
14022   // notePostMod is called. These will 1) detect an unsequenced modification
14023   // as side effect (as in "k++ + k") and 2) add a new usage with the
14024   // appropriate usage kind.
14025   //
14026   // We also have to be careful that some operation sequences modification as
14027   // side effect as well (for example: || or ,). To account for this we wrap
14028   // the visitation of such a sub-expression (for example: the LHS of || or ,)
14029   // with SequencedSubexpression. SequencedSubexpression is an RAII object
14030   // which record usages which are modifications as side effect, and then
14031   // downgrade them (or more accurately restore the previous usage which was a
14032   // modification as side effect) when exiting the scope of the sequenced
14033   // subexpression.
14034 
14035   void notePreUse(Object O, const Expr *UseExpr) {
14036     UsageInfo &UI = UsageMap[O];
14037     // Uses conflict with other modifications.
14038     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14039   }
14040 
14041   void notePostUse(Object O, const Expr *UseExpr) {
14042     UsageInfo &UI = UsageMap[O];
14043     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14044                /*IsModMod=*/false);
14045     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14046   }
14047 
14048   void notePreMod(Object O, const Expr *ModExpr) {
14049     UsageInfo &UI = UsageMap[O];
14050     // Modifications conflict with other modifications and with uses.
14051     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14052     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14053   }
14054 
14055   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14056     UsageInfo &UI = UsageMap[O];
14057     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14058                /*IsModMod=*/true);
14059     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14060   }
14061 
14062 public:
14063   SequenceChecker(Sema &S, const Expr *E,
14064                   SmallVectorImpl<const Expr *> &WorkList)
14065       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14066     Visit(E);
14067     // Silence a -Wunused-private-field since WorkList is now unused.
14068     // TODO: Evaluate if it can be used, and if not remove it.
14069     (void)this->WorkList;
14070   }
14071 
14072   void VisitStmt(const Stmt *S) {
14073     // Skip all statements which aren't expressions for now.
14074   }
14075 
14076   void VisitExpr(const Expr *E) {
14077     // By default, just recurse to evaluated subexpressions.
14078     Base::VisitStmt(E);
14079   }
14080 
14081   void VisitCastExpr(const CastExpr *E) {
14082     Object O = Object();
14083     if (E->getCastKind() == CK_LValueToRValue)
14084       O = getObject(E->getSubExpr(), false);
14085 
14086     if (O)
14087       notePreUse(O, E);
14088     VisitExpr(E);
14089     if (O)
14090       notePostUse(O, E);
14091   }
14092 
14093   void VisitSequencedExpressions(const Expr *SequencedBefore,
14094                                  const Expr *SequencedAfter) {
14095     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14096     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14097     SequenceTree::Seq OldRegion = Region;
14098 
14099     {
14100       SequencedSubexpression SeqBefore(*this);
14101       Region = BeforeRegion;
14102       Visit(SequencedBefore);
14103     }
14104 
14105     Region = AfterRegion;
14106     Visit(SequencedAfter);
14107 
14108     Region = OldRegion;
14109 
14110     Tree.merge(BeforeRegion);
14111     Tree.merge(AfterRegion);
14112   }
14113 
14114   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14115     // C++17 [expr.sub]p1:
14116     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14117     //   expression E1 is sequenced before the expression E2.
14118     if (SemaRef.getLangOpts().CPlusPlus17)
14119       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14120     else {
14121       Visit(ASE->getLHS());
14122       Visit(ASE->getRHS());
14123     }
14124   }
14125 
14126   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14127   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14128   void VisitBinPtrMem(const BinaryOperator *BO) {
14129     // C++17 [expr.mptr.oper]p4:
14130     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14131     //  the expression E1 is sequenced before the expression E2.
14132     if (SemaRef.getLangOpts().CPlusPlus17)
14133       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14134     else {
14135       Visit(BO->getLHS());
14136       Visit(BO->getRHS());
14137     }
14138   }
14139 
14140   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14141   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14142   void VisitBinShlShr(const BinaryOperator *BO) {
14143     // C++17 [expr.shift]p4:
14144     //  The expression E1 is sequenced before the expression E2.
14145     if (SemaRef.getLangOpts().CPlusPlus17)
14146       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14147     else {
14148       Visit(BO->getLHS());
14149       Visit(BO->getRHS());
14150     }
14151   }
14152 
14153   void VisitBinComma(const BinaryOperator *BO) {
14154     // C++11 [expr.comma]p1:
14155     //   Every value computation and side effect associated with the left
14156     //   expression is sequenced before every value computation and side
14157     //   effect associated with the right expression.
14158     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14159   }
14160 
14161   void VisitBinAssign(const BinaryOperator *BO) {
14162     SequenceTree::Seq RHSRegion;
14163     SequenceTree::Seq LHSRegion;
14164     if (SemaRef.getLangOpts().CPlusPlus17) {
14165       RHSRegion = Tree.allocate(Region);
14166       LHSRegion = Tree.allocate(Region);
14167     } else {
14168       RHSRegion = Region;
14169       LHSRegion = Region;
14170     }
14171     SequenceTree::Seq OldRegion = Region;
14172 
14173     // C++11 [expr.ass]p1:
14174     //  [...] the assignment is sequenced after the value computation
14175     //  of the right and left operands, [...]
14176     //
14177     // so check it before inspecting the operands and update the
14178     // map afterwards.
14179     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14180     if (O)
14181       notePreMod(O, BO);
14182 
14183     if (SemaRef.getLangOpts().CPlusPlus17) {
14184       // C++17 [expr.ass]p1:
14185       //  [...] The right operand is sequenced before the left operand. [...]
14186       {
14187         SequencedSubexpression SeqBefore(*this);
14188         Region = RHSRegion;
14189         Visit(BO->getRHS());
14190       }
14191 
14192       Region = LHSRegion;
14193       Visit(BO->getLHS());
14194 
14195       if (O && isa<CompoundAssignOperator>(BO))
14196         notePostUse(O, BO);
14197 
14198     } else {
14199       // C++11 does not specify any sequencing between the LHS and RHS.
14200       Region = LHSRegion;
14201       Visit(BO->getLHS());
14202 
14203       if (O && isa<CompoundAssignOperator>(BO))
14204         notePostUse(O, BO);
14205 
14206       Region = RHSRegion;
14207       Visit(BO->getRHS());
14208     }
14209 
14210     // C++11 [expr.ass]p1:
14211     //  the assignment is sequenced [...] before the value computation of the
14212     //  assignment expression.
14213     // C11 6.5.16/3 has no such rule.
14214     Region = OldRegion;
14215     if (O)
14216       notePostMod(O, BO,
14217                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14218                                                   : UK_ModAsSideEffect);
14219     if (SemaRef.getLangOpts().CPlusPlus17) {
14220       Tree.merge(RHSRegion);
14221       Tree.merge(LHSRegion);
14222     }
14223   }
14224 
14225   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14226     VisitBinAssign(CAO);
14227   }
14228 
14229   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14230   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14231   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14232     Object O = getObject(UO->getSubExpr(), true);
14233     if (!O)
14234       return VisitExpr(UO);
14235 
14236     notePreMod(O, UO);
14237     Visit(UO->getSubExpr());
14238     // C++11 [expr.pre.incr]p1:
14239     //   the expression ++x is equivalent to x+=1
14240     notePostMod(O, UO,
14241                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14242                                                 : UK_ModAsSideEffect);
14243   }
14244 
14245   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14246   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14247   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14248     Object O = getObject(UO->getSubExpr(), true);
14249     if (!O)
14250       return VisitExpr(UO);
14251 
14252     notePreMod(O, UO);
14253     Visit(UO->getSubExpr());
14254     notePostMod(O, UO, UK_ModAsSideEffect);
14255   }
14256 
14257   void VisitBinLOr(const BinaryOperator *BO) {
14258     // C++11 [expr.log.or]p2:
14259     //  If the second expression is evaluated, every value computation and
14260     //  side effect associated with the first expression is sequenced before
14261     //  every value computation and side effect associated with the
14262     //  second expression.
14263     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14264     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14265     SequenceTree::Seq OldRegion = Region;
14266 
14267     EvaluationTracker Eval(*this);
14268     {
14269       SequencedSubexpression Sequenced(*this);
14270       Region = LHSRegion;
14271       Visit(BO->getLHS());
14272     }
14273 
14274     // C++11 [expr.log.or]p1:
14275     //  [...] the second operand is not evaluated if the first operand
14276     //  evaluates to true.
14277     bool EvalResult = false;
14278     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14279     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14280     if (ShouldVisitRHS) {
14281       Region = RHSRegion;
14282       Visit(BO->getRHS());
14283     }
14284 
14285     Region = OldRegion;
14286     Tree.merge(LHSRegion);
14287     Tree.merge(RHSRegion);
14288   }
14289 
14290   void VisitBinLAnd(const BinaryOperator *BO) {
14291     // C++11 [expr.log.and]p2:
14292     //  If the second expression is evaluated, every value computation and
14293     //  side effect associated with the first expression is sequenced before
14294     //  every value computation and side effect associated with the
14295     //  second expression.
14296     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14297     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14298     SequenceTree::Seq OldRegion = Region;
14299 
14300     EvaluationTracker Eval(*this);
14301     {
14302       SequencedSubexpression Sequenced(*this);
14303       Region = LHSRegion;
14304       Visit(BO->getLHS());
14305     }
14306 
14307     // C++11 [expr.log.and]p1:
14308     //  [...] the second operand is not evaluated if the first operand is false.
14309     bool EvalResult = false;
14310     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14311     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14312     if (ShouldVisitRHS) {
14313       Region = RHSRegion;
14314       Visit(BO->getRHS());
14315     }
14316 
14317     Region = OldRegion;
14318     Tree.merge(LHSRegion);
14319     Tree.merge(RHSRegion);
14320   }
14321 
14322   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14323     // C++11 [expr.cond]p1:
14324     //  [...] Every value computation and side effect associated with the first
14325     //  expression is sequenced before every value computation and side effect
14326     //  associated with the second or third expression.
14327     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14328 
14329     // No sequencing is specified between the true and false expression.
14330     // However since exactly one of both is going to be evaluated we can
14331     // consider them to be sequenced. This is needed to avoid warning on
14332     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14333     // both the true and false expressions because we can't evaluate x.
14334     // This will still allow us to detect an expression like (pre C++17)
14335     // "(x ? y += 1 : y += 2) = y".
14336     //
14337     // We don't wrap the visitation of the true and false expression with
14338     // SequencedSubexpression because we don't want to downgrade modifications
14339     // as side effect in the true and false expressions after the visition
14340     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14341     // not warn between the two "y++", but we should warn between the "y++"
14342     // and the "y".
14343     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14344     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14345     SequenceTree::Seq OldRegion = Region;
14346 
14347     EvaluationTracker Eval(*this);
14348     {
14349       SequencedSubexpression Sequenced(*this);
14350       Region = ConditionRegion;
14351       Visit(CO->getCond());
14352     }
14353 
14354     // C++11 [expr.cond]p1:
14355     // [...] The first expression is contextually converted to bool (Clause 4).
14356     // It is evaluated and if it is true, the result of the conditional
14357     // expression is the value of the second expression, otherwise that of the
14358     // third expression. Only one of the second and third expressions is
14359     // evaluated. [...]
14360     bool EvalResult = false;
14361     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14362     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14363     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14364     if (ShouldVisitTrueExpr) {
14365       Region = TrueRegion;
14366       Visit(CO->getTrueExpr());
14367     }
14368     if (ShouldVisitFalseExpr) {
14369       Region = FalseRegion;
14370       Visit(CO->getFalseExpr());
14371     }
14372 
14373     Region = OldRegion;
14374     Tree.merge(ConditionRegion);
14375     Tree.merge(TrueRegion);
14376     Tree.merge(FalseRegion);
14377   }
14378 
14379   void VisitCallExpr(const CallExpr *CE) {
14380     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14381 
14382     if (CE->isUnevaluatedBuiltinCall(Context))
14383       return;
14384 
14385     // C++11 [intro.execution]p15:
14386     //   When calling a function [...], every value computation and side effect
14387     //   associated with any argument expression, or with the postfix expression
14388     //   designating the called function, is sequenced before execution of every
14389     //   expression or statement in the body of the function [and thus before
14390     //   the value computation of its result].
14391     SequencedSubexpression Sequenced(*this);
14392     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14393       // C++17 [expr.call]p5
14394       //   The postfix-expression is sequenced before each expression in the
14395       //   expression-list and any default argument. [...]
14396       SequenceTree::Seq CalleeRegion;
14397       SequenceTree::Seq OtherRegion;
14398       if (SemaRef.getLangOpts().CPlusPlus17) {
14399         CalleeRegion = Tree.allocate(Region);
14400         OtherRegion = Tree.allocate(Region);
14401       } else {
14402         CalleeRegion = Region;
14403         OtherRegion = Region;
14404       }
14405       SequenceTree::Seq OldRegion = Region;
14406 
14407       // Visit the callee expression first.
14408       Region = CalleeRegion;
14409       if (SemaRef.getLangOpts().CPlusPlus17) {
14410         SequencedSubexpression Sequenced(*this);
14411         Visit(CE->getCallee());
14412       } else {
14413         Visit(CE->getCallee());
14414       }
14415 
14416       // Then visit the argument expressions.
14417       Region = OtherRegion;
14418       for (const Expr *Argument : CE->arguments())
14419         Visit(Argument);
14420 
14421       Region = OldRegion;
14422       if (SemaRef.getLangOpts().CPlusPlus17) {
14423         Tree.merge(CalleeRegion);
14424         Tree.merge(OtherRegion);
14425       }
14426     });
14427   }
14428 
14429   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14430     // C++17 [over.match.oper]p2:
14431     //   [...] the operator notation is first transformed to the equivalent
14432     //   function-call notation as summarized in Table 12 (where @ denotes one
14433     //   of the operators covered in the specified subclause). However, the
14434     //   operands are sequenced in the order prescribed for the built-in
14435     //   operator (Clause 8).
14436     //
14437     // From the above only overloaded binary operators and overloaded call
14438     // operators have sequencing rules in C++17 that we need to handle
14439     // separately.
14440     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14441         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14442       return VisitCallExpr(CXXOCE);
14443 
14444     enum {
14445       NoSequencing,
14446       LHSBeforeRHS,
14447       RHSBeforeLHS,
14448       LHSBeforeRest
14449     } SequencingKind;
14450     switch (CXXOCE->getOperator()) {
14451     case OO_Equal:
14452     case OO_PlusEqual:
14453     case OO_MinusEqual:
14454     case OO_StarEqual:
14455     case OO_SlashEqual:
14456     case OO_PercentEqual:
14457     case OO_CaretEqual:
14458     case OO_AmpEqual:
14459     case OO_PipeEqual:
14460     case OO_LessLessEqual:
14461     case OO_GreaterGreaterEqual:
14462       SequencingKind = RHSBeforeLHS;
14463       break;
14464 
14465     case OO_LessLess:
14466     case OO_GreaterGreater:
14467     case OO_AmpAmp:
14468     case OO_PipePipe:
14469     case OO_Comma:
14470     case OO_ArrowStar:
14471     case OO_Subscript:
14472       SequencingKind = LHSBeforeRHS;
14473       break;
14474 
14475     case OO_Call:
14476       SequencingKind = LHSBeforeRest;
14477       break;
14478 
14479     default:
14480       SequencingKind = NoSequencing;
14481       break;
14482     }
14483 
14484     if (SequencingKind == NoSequencing)
14485       return VisitCallExpr(CXXOCE);
14486 
14487     // This is a call, so all subexpressions are sequenced before the result.
14488     SequencedSubexpression Sequenced(*this);
14489 
14490     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14491       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14492              "Should only get there with C++17 and above!");
14493       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14494              "Should only get there with an overloaded binary operator"
14495              " or an overloaded call operator!");
14496 
14497       if (SequencingKind == LHSBeforeRest) {
14498         assert(CXXOCE->getOperator() == OO_Call &&
14499                "We should only have an overloaded call operator here!");
14500 
14501         // This is very similar to VisitCallExpr, except that we only have the
14502         // C++17 case. The postfix-expression is the first argument of the
14503         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14504         // are in the following arguments.
14505         //
14506         // Note that we intentionally do not visit the callee expression since
14507         // it is just a decayed reference to a function.
14508         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14509         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14510         SequenceTree::Seq OldRegion = Region;
14511 
14512         assert(CXXOCE->getNumArgs() >= 1 &&
14513                "An overloaded call operator must have at least one argument"
14514                " for the postfix-expression!");
14515         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14516         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14517                                           CXXOCE->getNumArgs() - 1);
14518 
14519         // Visit the postfix-expression first.
14520         {
14521           Region = PostfixExprRegion;
14522           SequencedSubexpression Sequenced(*this);
14523           Visit(PostfixExpr);
14524         }
14525 
14526         // Then visit the argument expressions.
14527         Region = ArgsRegion;
14528         for (const Expr *Arg : Args)
14529           Visit(Arg);
14530 
14531         Region = OldRegion;
14532         Tree.merge(PostfixExprRegion);
14533         Tree.merge(ArgsRegion);
14534       } else {
14535         assert(CXXOCE->getNumArgs() == 2 &&
14536                "Should only have two arguments here!");
14537         assert((SequencingKind == LHSBeforeRHS ||
14538                 SequencingKind == RHSBeforeLHS) &&
14539                "Unexpected sequencing kind!");
14540 
14541         // We do not visit the callee expression since it is just a decayed
14542         // reference to a function.
14543         const Expr *E1 = CXXOCE->getArg(0);
14544         const Expr *E2 = CXXOCE->getArg(1);
14545         if (SequencingKind == RHSBeforeLHS)
14546           std::swap(E1, E2);
14547 
14548         return VisitSequencedExpressions(E1, E2);
14549       }
14550     });
14551   }
14552 
14553   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14554     // This is a call, so all subexpressions are sequenced before the result.
14555     SequencedSubexpression Sequenced(*this);
14556 
14557     if (!CCE->isListInitialization())
14558       return VisitExpr(CCE);
14559 
14560     // In C++11, list initializations are sequenced.
14561     SmallVector<SequenceTree::Seq, 32> Elts;
14562     SequenceTree::Seq Parent = Region;
14563     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14564                                               E = CCE->arg_end();
14565          I != E; ++I) {
14566       Region = Tree.allocate(Parent);
14567       Elts.push_back(Region);
14568       Visit(*I);
14569     }
14570 
14571     // Forget that the initializers are sequenced.
14572     Region = Parent;
14573     for (unsigned I = 0; I < Elts.size(); ++I)
14574       Tree.merge(Elts[I]);
14575   }
14576 
14577   void VisitInitListExpr(const InitListExpr *ILE) {
14578     if (!SemaRef.getLangOpts().CPlusPlus11)
14579       return VisitExpr(ILE);
14580 
14581     // In C++11, list initializations are sequenced.
14582     SmallVector<SequenceTree::Seq, 32> Elts;
14583     SequenceTree::Seq Parent = Region;
14584     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14585       const Expr *E = ILE->getInit(I);
14586       if (!E)
14587         continue;
14588       Region = Tree.allocate(Parent);
14589       Elts.push_back(Region);
14590       Visit(E);
14591     }
14592 
14593     // Forget that the initializers are sequenced.
14594     Region = Parent;
14595     for (unsigned I = 0; I < Elts.size(); ++I)
14596       Tree.merge(Elts[I]);
14597   }
14598 };
14599 
14600 } // namespace
14601 
14602 void Sema::CheckUnsequencedOperations(const Expr *E) {
14603   SmallVector<const Expr *, 8> WorkList;
14604   WorkList.push_back(E);
14605   while (!WorkList.empty()) {
14606     const Expr *Item = WorkList.pop_back_val();
14607     SequenceChecker(*this, Item, WorkList);
14608   }
14609 }
14610 
14611 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14612                               bool IsConstexpr) {
14613   llvm::SaveAndRestore<bool> ConstantContext(
14614       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14615   CheckImplicitConversions(E, CheckLoc);
14616   if (!E->isInstantiationDependent())
14617     CheckUnsequencedOperations(E);
14618   if (!IsConstexpr && !E->isValueDependent())
14619     CheckForIntOverflow(E);
14620   DiagnoseMisalignedMembers();
14621 }
14622 
14623 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14624                                        FieldDecl *BitField,
14625                                        Expr *Init) {
14626   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14627 }
14628 
14629 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14630                                          SourceLocation Loc) {
14631   if (!PType->isVariablyModifiedType())
14632     return;
14633   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14634     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14635     return;
14636   }
14637   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14638     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14639     return;
14640   }
14641   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14642     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14643     return;
14644   }
14645 
14646   const ArrayType *AT = S.Context.getAsArrayType(PType);
14647   if (!AT)
14648     return;
14649 
14650   if (AT->getSizeModifier() != ArrayType::Star) {
14651     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14652     return;
14653   }
14654 
14655   S.Diag(Loc, diag::err_array_star_in_function_definition);
14656 }
14657 
14658 /// CheckParmsForFunctionDef - Check that the parameters of the given
14659 /// function are appropriate for the definition of a function. This
14660 /// takes care of any checks that cannot be performed on the
14661 /// declaration itself, e.g., that the types of each of the function
14662 /// parameters are complete.
14663 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14664                                     bool CheckParameterNames) {
14665   bool HasInvalidParm = false;
14666   for (ParmVarDecl *Param : Parameters) {
14667     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14668     // function declarator that is part of a function definition of
14669     // that function shall not have incomplete type.
14670     //
14671     // This is also C++ [dcl.fct]p6.
14672     if (!Param->isInvalidDecl() &&
14673         RequireCompleteType(Param->getLocation(), Param->getType(),
14674                             diag::err_typecheck_decl_incomplete_type)) {
14675       Param->setInvalidDecl();
14676       HasInvalidParm = true;
14677     }
14678 
14679     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14680     // declaration of each parameter shall include an identifier.
14681     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14682         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14683       // Diagnose this as an extension in C17 and earlier.
14684       if (!getLangOpts().C2x)
14685         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14686     }
14687 
14688     // C99 6.7.5.3p12:
14689     //   If the function declarator is not part of a definition of that
14690     //   function, parameters may have incomplete type and may use the [*]
14691     //   notation in their sequences of declarator specifiers to specify
14692     //   variable length array types.
14693     QualType PType = Param->getOriginalType();
14694     // FIXME: This diagnostic should point the '[*]' if source-location
14695     // information is added for it.
14696     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14697 
14698     // If the parameter is a c++ class type and it has to be destructed in the
14699     // callee function, declare the destructor so that it can be called by the
14700     // callee function. Do not perform any direct access check on the dtor here.
14701     if (!Param->isInvalidDecl()) {
14702       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14703         if (!ClassDecl->isInvalidDecl() &&
14704             !ClassDecl->hasIrrelevantDestructor() &&
14705             !ClassDecl->isDependentContext() &&
14706             ClassDecl->isParamDestroyedInCallee()) {
14707           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14708           MarkFunctionReferenced(Param->getLocation(), Destructor);
14709           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14710         }
14711       }
14712     }
14713 
14714     // Parameters with the pass_object_size attribute only need to be marked
14715     // constant at function definitions. Because we lack information about
14716     // whether we're on a declaration or definition when we're instantiating the
14717     // attribute, we need to check for constness here.
14718     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14719       if (!Param->getType().isConstQualified())
14720         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14721             << Attr->getSpelling() << 1;
14722 
14723     // Check for parameter names shadowing fields from the class.
14724     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14725       // The owning context for the parameter should be the function, but we
14726       // want to see if this function's declaration context is a record.
14727       DeclContext *DC = Param->getDeclContext();
14728       if (DC && DC->isFunctionOrMethod()) {
14729         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14730           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14731                                      RD, /*DeclIsField*/ false);
14732       }
14733     }
14734   }
14735 
14736   return HasInvalidParm;
14737 }
14738 
14739 Optional<std::pair<CharUnits, CharUnits>>
14740 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14741 
14742 /// Compute the alignment and offset of the base class object given the
14743 /// derived-to-base cast expression and the alignment and offset of the derived
14744 /// class object.
14745 static std::pair<CharUnits, CharUnits>
14746 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14747                                    CharUnits BaseAlignment, CharUnits Offset,
14748                                    ASTContext &Ctx) {
14749   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14750        ++PathI) {
14751     const CXXBaseSpecifier *Base = *PathI;
14752     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14753     if (Base->isVirtual()) {
14754       // The complete object may have a lower alignment than the non-virtual
14755       // alignment of the base, in which case the base may be misaligned. Choose
14756       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14757       // conservative lower bound of the complete object alignment.
14758       CharUnits NonVirtualAlignment =
14759           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14760       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14761       Offset = CharUnits::Zero();
14762     } else {
14763       const ASTRecordLayout &RL =
14764           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14765       Offset += RL.getBaseClassOffset(BaseDecl);
14766     }
14767     DerivedType = Base->getType();
14768   }
14769 
14770   return std::make_pair(BaseAlignment, Offset);
14771 }
14772 
14773 /// Compute the alignment and offset of a binary additive operator.
14774 static Optional<std::pair<CharUnits, CharUnits>>
14775 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14776                                      bool IsSub, ASTContext &Ctx) {
14777   QualType PointeeType = PtrE->getType()->getPointeeType();
14778 
14779   if (!PointeeType->isConstantSizeType())
14780     return llvm::None;
14781 
14782   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14783 
14784   if (!P)
14785     return llvm::None;
14786 
14787   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14788   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14789     CharUnits Offset = EltSize * IdxRes->getExtValue();
14790     if (IsSub)
14791       Offset = -Offset;
14792     return std::make_pair(P->first, P->second + Offset);
14793   }
14794 
14795   // If the integer expression isn't a constant expression, compute the lower
14796   // bound of the alignment using the alignment and offset of the pointer
14797   // expression and the element size.
14798   return std::make_pair(
14799       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14800       CharUnits::Zero());
14801 }
14802 
14803 /// This helper function takes an lvalue expression and returns the alignment of
14804 /// a VarDecl and a constant offset from the VarDecl.
14805 Optional<std::pair<CharUnits, CharUnits>>
14806 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14807   E = E->IgnoreParens();
14808   switch (E->getStmtClass()) {
14809   default:
14810     break;
14811   case Stmt::CStyleCastExprClass:
14812   case Stmt::CXXStaticCastExprClass:
14813   case Stmt::ImplicitCastExprClass: {
14814     auto *CE = cast<CastExpr>(E);
14815     const Expr *From = CE->getSubExpr();
14816     switch (CE->getCastKind()) {
14817     default:
14818       break;
14819     case CK_NoOp:
14820       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14821     case CK_UncheckedDerivedToBase:
14822     case CK_DerivedToBase: {
14823       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14824       if (!P)
14825         break;
14826       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14827                                                 P->second, Ctx);
14828     }
14829     }
14830     break;
14831   }
14832   case Stmt::ArraySubscriptExprClass: {
14833     auto *ASE = cast<ArraySubscriptExpr>(E);
14834     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14835                                                 false, Ctx);
14836   }
14837   case Stmt::DeclRefExprClass: {
14838     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14839       // FIXME: If VD is captured by copy or is an escaping __block variable,
14840       // use the alignment of VD's type.
14841       if (!VD->getType()->isReferenceType())
14842         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14843       if (VD->hasInit())
14844         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14845     }
14846     break;
14847   }
14848   case Stmt::MemberExprClass: {
14849     auto *ME = cast<MemberExpr>(E);
14850     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14851     if (!FD || FD->getType()->isReferenceType() ||
14852         FD->getParent()->isInvalidDecl())
14853       break;
14854     Optional<std::pair<CharUnits, CharUnits>> P;
14855     if (ME->isArrow())
14856       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14857     else
14858       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14859     if (!P)
14860       break;
14861     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14862     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14863     return std::make_pair(P->first,
14864                           P->second + CharUnits::fromQuantity(Offset));
14865   }
14866   case Stmt::UnaryOperatorClass: {
14867     auto *UO = cast<UnaryOperator>(E);
14868     switch (UO->getOpcode()) {
14869     default:
14870       break;
14871     case UO_Deref:
14872       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14873     }
14874     break;
14875   }
14876   case Stmt::BinaryOperatorClass: {
14877     auto *BO = cast<BinaryOperator>(E);
14878     auto Opcode = BO->getOpcode();
14879     switch (Opcode) {
14880     default:
14881       break;
14882     case BO_Comma:
14883       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14884     }
14885     break;
14886   }
14887   }
14888   return llvm::None;
14889 }
14890 
14891 /// This helper function takes a pointer expression and returns the alignment of
14892 /// a VarDecl and a constant offset from the VarDecl.
14893 Optional<std::pair<CharUnits, CharUnits>>
14894 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14895   E = E->IgnoreParens();
14896   switch (E->getStmtClass()) {
14897   default:
14898     break;
14899   case Stmt::CStyleCastExprClass:
14900   case Stmt::CXXStaticCastExprClass:
14901   case Stmt::ImplicitCastExprClass: {
14902     auto *CE = cast<CastExpr>(E);
14903     const Expr *From = CE->getSubExpr();
14904     switch (CE->getCastKind()) {
14905     default:
14906       break;
14907     case CK_NoOp:
14908       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14909     case CK_ArrayToPointerDecay:
14910       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14911     case CK_UncheckedDerivedToBase:
14912     case CK_DerivedToBase: {
14913       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14914       if (!P)
14915         break;
14916       return getDerivedToBaseAlignmentAndOffset(
14917           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14918     }
14919     }
14920     break;
14921   }
14922   case Stmt::CXXThisExprClass: {
14923     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14924     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14925     return std::make_pair(Alignment, CharUnits::Zero());
14926   }
14927   case Stmt::UnaryOperatorClass: {
14928     auto *UO = cast<UnaryOperator>(E);
14929     if (UO->getOpcode() == UO_AddrOf)
14930       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14931     break;
14932   }
14933   case Stmt::BinaryOperatorClass: {
14934     auto *BO = cast<BinaryOperator>(E);
14935     auto Opcode = BO->getOpcode();
14936     switch (Opcode) {
14937     default:
14938       break;
14939     case BO_Add:
14940     case BO_Sub: {
14941       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14942       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14943         std::swap(LHS, RHS);
14944       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14945                                                   Ctx);
14946     }
14947     case BO_Comma:
14948       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14949     }
14950     break;
14951   }
14952   }
14953   return llvm::None;
14954 }
14955 
14956 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14957   // See if we can compute the alignment of a VarDecl and an offset from it.
14958   Optional<std::pair<CharUnits, CharUnits>> P =
14959       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14960 
14961   if (P)
14962     return P->first.alignmentAtOffset(P->second);
14963 
14964   // If that failed, return the type's alignment.
14965   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14966 }
14967 
14968 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14969 /// pointer cast increases the alignment requirements.
14970 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14971   // This is actually a lot of work to potentially be doing on every
14972   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14973   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14974     return;
14975 
14976   // Ignore dependent types.
14977   if (T->isDependentType() || Op->getType()->isDependentType())
14978     return;
14979 
14980   // Require that the destination be a pointer type.
14981   const PointerType *DestPtr = T->getAs<PointerType>();
14982   if (!DestPtr) return;
14983 
14984   // If the destination has alignment 1, we're done.
14985   QualType DestPointee = DestPtr->getPointeeType();
14986   if (DestPointee->isIncompleteType()) return;
14987   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14988   if (DestAlign.isOne()) return;
14989 
14990   // Require that the source be a pointer type.
14991   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14992   if (!SrcPtr) return;
14993   QualType SrcPointee = SrcPtr->getPointeeType();
14994 
14995   // Explicitly allow casts from cv void*.  We already implicitly
14996   // allowed casts to cv void*, since they have alignment 1.
14997   // Also allow casts involving incomplete types, which implicitly
14998   // includes 'void'.
14999   if (SrcPointee->isIncompleteType()) return;
15000 
15001   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15002 
15003   if (SrcAlign >= DestAlign) return;
15004 
15005   Diag(TRange.getBegin(), diag::warn_cast_align)
15006     << Op->getType() << T
15007     << static_cast<unsigned>(SrcAlign.getQuantity())
15008     << static_cast<unsigned>(DestAlign.getQuantity())
15009     << TRange << Op->getSourceRange();
15010 }
15011 
15012 /// Check whether this array fits the idiom of a size-one tail padded
15013 /// array member of a struct.
15014 ///
15015 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
15016 /// commonly used to emulate flexible arrays in C89 code.
15017 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
15018                                     const NamedDecl *ND) {
15019   if (Size != 1 || !ND) return false;
15020 
15021   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
15022   if (!FD) return false;
15023 
15024   // Don't consider sizes resulting from macro expansions or template argument
15025   // substitution to form C89 tail-padded arrays.
15026 
15027   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
15028   while (TInfo) {
15029     TypeLoc TL = TInfo->getTypeLoc();
15030     // Look through typedefs.
15031     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
15032       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
15033       TInfo = TDL->getTypeSourceInfo();
15034       continue;
15035     }
15036     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
15037       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
15038       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
15039         return false;
15040     }
15041     break;
15042   }
15043 
15044   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
15045   if (!RD) return false;
15046   if (RD->isUnion()) return false;
15047   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15048     if (!CRD->isStandardLayout()) return false;
15049   }
15050 
15051   // See if this is the last field decl in the record.
15052   const Decl *D = FD;
15053   while ((D = D->getNextDeclInContext()))
15054     if (isa<FieldDecl>(D))
15055       return false;
15056   return true;
15057 }
15058 
15059 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15060                             const ArraySubscriptExpr *ASE,
15061                             bool AllowOnePastEnd, bool IndexNegated) {
15062   // Already diagnosed by the constant evaluator.
15063   if (isConstantEvaluated())
15064     return;
15065 
15066   IndexExpr = IndexExpr->IgnoreParenImpCasts();
15067   if (IndexExpr->isValueDependent())
15068     return;
15069 
15070   const Type *EffectiveType =
15071       BaseExpr->getType()->getPointeeOrArrayElementType();
15072   BaseExpr = BaseExpr->IgnoreParenCasts();
15073   const ConstantArrayType *ArrayTy =
15074       Context.getAsConstantArrayType(BaseExpr->getType());
15075 
15076   const Type *BaseType =
15077       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15078   bool IsUnboundedArray = (BaseType == nullptr);
15079   if (EffectiveType->isDependentType() ||
15080       (!IsUnboundedArray && BaseType->isDependentType()))
15081     return;
15082 
15083   Expr::EvalResult Result;
15084   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15085     return;
15086 
15087   llvm::APSInt index = Result.Val.getInt();
15088   if (IndexNegated) {
15089     index.setIsUnsigned(false);
15090     index = -index;
15091   }
15092 
15093   const NamedDecl *ND = nullptr;
15094   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15095     ND = DRE->getDecl();
15096   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
15097     ND = ME->getMemberDecl();
15098 
15099   if (IsUnboundedArray) {
15100     if (index.isUnsigned() || !index.isNegative()) {
15101       const auto &ASTC = getASTContext();
15102       unsigned AddrBits =
15103           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
15104               EffectiveType->getCanonicalTypeInternal()));
15105       if (index.getBitWidth() < AddrBits)
15106         index = index.zext(AddrBits);
15107       Optional<CharUnits> ElemCharUnits =
15108           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15109       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15110       // pointer) bounds-checking isn't meaningful.
15111       if (!ElemCharUnits)
15112         return;
15113       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15114       // If index has more active bits than address space, we already know
15115       // we have a bounds violation to warn about.  Otherwise, compute
15116       // address of (index + 1)th element, and warn about bounds violation
15117       // only if that address exceeds address space.
15118       if (index.getActiveBits() <= AddrBits) {
15119         bool Overflow;
15120         llvm::APInt Product(index);
15121         Product += 1;
15122         Product = Product.umul_ov(ElemBytes, Overflow);
15123         if (!Overflow && Product.getActiveBits() <= AddrBits)
15124           return;
15125       }
15126 
15127       // Need to compute max possible elements in address space, since that
15128       // is included in diag message.
15129       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15130       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15131       MaxElems += 1;
15132       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15133       MaxElems = MaxElems.udiv(ElemBytes);
15134 
15135       unsigned DiagID =
15136           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15137               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15138 
15139       // Diag message shows element size in bits and in "bytes" (platform-
15140       // dependent CharUnits)
15141       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15142                           PDiag(DiagID)
15143                               << toString(index, 10, true) << AddrBits
15144                               << (unsigned)ASTC.toBits(*ElemCharUnits)
15145                               << toString(ElemBytes, 10, false)
15146                               << toString(MaxElems, 10, false)
15147                               << (unsigned)MaxElems.getLimitedValue(~0U)
15148                               << IndexExpr->getSourceRange());
15149 
15150       if (!ND) {
15151         // Try harder to find a NamedDecl to point at in the note.
15152         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15153           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15154         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15155           ND = DRE->getDecl();
15156         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15157           ND = ME->getMemberDecl();
15158       }
15159 
15160       if (ND)
15161         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15162                             PDiag(diag::note_array_declared_here) << ND);
15163     }
15164     return;
15165   }
15166 
15167   if (index.isUnsigned() || !index.isNegative()) {
15168     // It is possible that the type of the base expression after
15169     // IgnoreParenCasts is incomplete, even though the type of the base
15170     // expression before IgnoreParenCasts is complete (see PR39746 for an
15171     // example). In this case we have no information about whether the array
15172     // access exceeds the array bounds. However we can still diagnose an array
15173     // access which precedes the array bounds.
15174     if (BaseType->isIncompleteType())
15175       return;
15176 
15177     llvm::APInt size = ArrayTy->getSize();
15178     if (!size.isStrictlyPositive())
15179       return;
15180 
15181     if (BaseType != EffectiveType) {
15182       // Make sure we're comparing apples to apples when comparing index to size
15183       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15184       uint64_t array_typesize = Context.getTypeSize(BaseType);
15185       // Handle ptrarith_typesize being zero, such as when casting to void*
15186       if (!ptrarith_typesize) ptrarith_typesize = 1;
15187       if (ptrarith_typesize != array_typesize) {
15188         // There's a cast to a different size type involved
15189         uint64_t ratio = array_typesize / ptrarith_typesize;
15190         // TODO: Be smarter about handling cases where array_typesize is not a
15191         // multiple of ptrarith_typesize
15192         if (ptrarith_typesize * ratio == array_typesize)
15193           size *= llvm::APInt(size.getBitWidth(), ratio);
15194       }
15195     }
15196 
15197     if (size.getBitWidth() > index.getBitWidth())
15198       index = index.zext(size.getBitWidth());
15199     else if (size.getBitWidth() < index.getBitWidth())
15200       size = size.zext(index.getBitWidth());
15201 
15202     // For array subscripting the index must be less than size, but for pointer
15203     // arithmetic also allow the index (offset) to be equal to size since
15204     // computing the next address after the end of the array is legal and
15205     // commonly done e.g. in C++ iterators and range-based for loops.
15206     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15207       return;
15208 
15209     // Also don't warn for arrays of size 1 which are members of some
15210     // structure. These are often used to approximate flexible arrays in C89
15211     // code.
15212     if (IsTailPaddedMemberArray(*this, size, ND))
15213       return;
15214 
15215     // Suppress the warning if the subscript expression (as identified by the
15216     // ']' location) and the index expression are both from macro expansions
15217     // within a system header.
15218     if (ASE) {
15219       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15220           ASE->getRBracketLoc());
15221       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15222         SourceLocation IndexLoc =
15223             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15224         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15225           return;
15226       }
15227     }
15228 
15229     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15230                           : diag::warn_ptr_arith_exceeds_bounds;
15231 
15232     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15233                         PDiag(DiagID) << toString(index, 10, true)
15234                                       << toString(size, 10, true)
15235                                       << (unsigned)size.getLimitedValue(~0U)
15236                                       << IndexExpr->getSourceRange());
15237   } else {
15238     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15239     if (!ASE) {
15240       DiagID = diag::warn_ptr_arith_precedes_bounds;
15241       if (index.isNegative()) index = -index;
15242     }
15243 
15244     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15245                         PDiag(DiagID) << toString(index, 10, true)
15246                                       << IndexExpr->getSourceRange());
15247   }
15248 
15249   if (!ND) {
15250     // Try harder to find a NamedDecl to point at in the note.
15251     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15252       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15253     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15254       ND = DRE->getDecl();
15255     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15256       ND = ME->getMemberDecl();
15257   }
15258 
15259   if (ND)
15260     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15261                         PDiag(diag::note_array_declared_here) << ND);
15262 }
15263 
15264 void Sema::CheckArrayAccess(const Expr *expr) {
15265   int AllowOnePastEnd = 0;
15266   while (expr) {
15267     expr = expr->IgnoreParenImpCasts();
15268     switch (expr->getStmtClass()) {
15269       case Stmt::ArraySubscriptExprClass: {
15270         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15271         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15272                          AllowOnePastEnd > 0);
15273         expr = ASE->getBase();
15274         break;
15275       }
15276       case Stmt::MemberExprClass: {
15277         expr = cast<MemberExpr>(expr)->getBase();
15278         break;
15279       }
15280       case Stmt::OMPArraySectionExprClass: {
15281         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15282         if (ASE->getLowerBound())
15283           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15284                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15285         return;
15286       }
15287       case Stmt::UnaryOperatorClass: {
15288         // Only unwrap the * and & unary operators
15289         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15290         expr = UO->getSubExpr();
15291         switch (UO->getOpcode()) {
15292           case UO_AddrOf:
15293             AllowOnePastEnd++;
15294             break;
15295           case UO_Deref:
15296             AllowOnePastEnd--;
15297             break;
15298           default:
15299             return;
15300         }
15301         break;
15302       }
15303       case Stmt::ConditionalOperatorClass: {
15304         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15305         if (const Expr *lhs = cond->getLHS())
15306           CheckArrayAccess(lhs);
15307         if (const Expr *rhs = cond->getRHS())
15308           CheckArrayAccess(rhs);
15309         return;
15310       }
15311       case Stmt::CXXOperatorCallExprClass: {
15312         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15313         for (const auto *Arg : OCE->arguments())
15314           CheckArrayAccess(Arg);
15315         return;
15316       }
15317       default:
15318         return;
15319     }
15320   }
15321 }
15322 
15323 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15324 
15325 namespace {
15326 
15327 struct RetainCycleOwner {
15328   VarDecl *Variable = nullptr;
15329   SourceRange Range;
15330   SourceLocation Loc;
15331   bool Indirect = false;
15332 
15333   RetainCycleOwner() = default;
15334 
15335   void setLocsFrom(Expr *e) {
15336     Loc = e->getExprLoc();
15337     Range = e->getSourceRange();
15338   }
15339 };
15340 
15341 } // namespace
15342 
15343 /// Consider whether capturing the given variable can possibly lead to
15344 /// a retain cycle.
15345 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15346   // In ARC, it's captured strongly iff the variable has __strong
15347   // lifetime.  In MRR, it's captured strongly if the variable is
15348   // __block and has an appropriate type.
15349   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15350     return false;
15351 
15352   owner.Variable = var;
15353   if (ref)
15354     owner.setLocsFrom(ref);
15355   return true;
15356 }
15357 
15358 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15359   while (true) {
15360     e = e->IgnoreParens();
15361     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15362       switch (cast->getCastKind()) {
15363       case CK_BitCast:
15364       case CK_LValueBitCast:
15365       case CK_LValueToRValue:
15366       case CK_ARCReclaimReturnedObject:
15367         e = cast->getSubExpr();
15368         continue;
15369 
15370       default:
15371         return false;
15372       }
15373     }
15374 
15375     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15376       ObjCIvarDecl *ivar = ref->getDecl();
15377       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15378         return false;
15379 
15380       // Try to find a retain cycle in the base.
15381       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15382         return false;
15383 
15384       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15385       owner.Indirect = true;
15386       return true;
15387     }
15388 
15389     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15390       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15391       if (!var) return false;
15392       return considerVariable(var, ref, owner);
15393     }
15394 
15395     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15396       if (member->isArrow()) return false;
15397 
15398       // Don't count this as an indirect ownership.
15399       e = member->getBase();
15400       continue;
15401     }
15402 
15403     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15404       // Only pay attention to pseudo-objects on property references.
15405       ObjCPropertyRefExpr *pre
15406         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15407                                               ->IgnoreParens());
15408       if (!pre) return false;
15409       if (pre->isImplicitProperty()) return false;
15410       ObjCPropertyDecl *property = pre->getExplicitProperty();
15411       if (!property->isRetaining() &&
15412           !(property->getPropertyIvarDecl() &&
15413             property->getPropertyIvarDecl()->getType()
15414               .getObjCLifetime() == Qualifiers::OCL_Strong))
15415           return false;
15416 
15417       owner.Indirect = true;
15418       if (pre->isSuperReceiver()) {
15419         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15420         if (!owner.Variable)
15421           return false;
15422         owner.Loc = pre->getLocation();
15423         owner.Range = pre->getSourceRange();
15424         return true;
15425       }
15426       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15427                               ->getSourceExpr());
15428       continue;
15429     }
15430 
15431     // Array ivars?
15432 
15433     return false;
15434   }
15435 }
15436 
15437 namespace {
15438 
15439   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15440     ASTContext &Context;
15441     VarDecl *Variable;
15442     Expr *Capturer = nullptr;
15443     bool VarWillBeReased = false;
15444 
15445     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15446         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15447           Context(Context), Variable(variable) {}
15448 
15449     void VisitDeclRefExpr(DeclRefExpr *ref) {
15450       if (ref->getDecl() == Variable && !Capturer)
15451         Capturer = ref;
15452     }
15453 
15454     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15455       if (Capturer) return;
15456       Visit(ref->getBase());
15457       if (Capturer && ref->isFreeIvar())
15458         Capturer = ref;
15459     }
15460 
15461     void VisitBlockExpr(BlockExpr *block) {
15462       // Look inside nested blocks
15463       if (block->getBlockDecl()->capturesVariable(Variable))
15464         Visit(block->getBlockDecl()->getBody());
15465     }
15466 
15467     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15468       if (Capturer) return;
15469       if (OVE->getSourceExpr())
15470         Visit(OVE->getSourceExpr());
15471     }
15472 
15473     void VisitBinaryOperator(BinaryOperator *BinOp) {
15474       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15475         return;
15476       Expr *LHS = BinOp->getLHS();
15477       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15478         if (DRE->getDecl() != Variable)
15479           return;
15480         if (Expr *RHS = BinOp->getRHS()) {
15481           RHS = RHS->IgnoreParenCasts();
15482           Optional<llvm::APSInt> Value;
15483           VarWillBeReased =
15484               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15485                *Value == 0);
15486         }
15487       }
15488     }
15489   };
15490 
15491 } // namespace
15492 
15493 /// Check whether the given argument is a block which captures a
15494 /// variable.
15495 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15496   assert(owner.Variable && owner.Loc.isValid());
15497 
15498   e = e->IgnoreParenCasts();
15499 
15500   // Look through [^{...} copy] and Block_copy(^{...}).
15501   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15502     Selector Cmd = ME->getSelector();
15503     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15504       e = ME->getInstanceReceiver();
15505       if (!e)
15506         return nullptr;
15507       e = e->IgnoreParenCasts();
15508     }
15509   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15510     if (CE->getNumArgs() == 1) {
15511       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15512       if (Fn) {
15513         const IdentifierInfo *FnI = Fn->getIdentifier();
15514         if (FnI && FnI->isStr("_Block_copy")) {
15515           e = CE->getArg(0)->IgnoreParenCasts();
15516         }
15517       }
15518     }
15519   }
15520 
15521   BlockExpr *block = dyn_cast<BlockExpr>(e);
15522   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15523     return nullptr;
15524 
15525   FindCaptureVisitor visitor(S.Context, owner.Variable);
15526   visitor.Visit(block->getBlockDecl()->getBody());
15527   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15528 }
15529 
15530 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15531                                 RetainCycleOwner &owner) {
15532   assert(capturer);
15533   assert(owner.Variable && owner.Loc.isValid());
15534 
15535   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15536     << owner.Variable << capturer->getSourceRange();
15537   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15538     << owner.Indirect << owner.Range;
15539 }
15540 
15541 /// Check for a keyword selector that starts with the word 'add' or
15542 /// 'set'.
15543 static bool isSetterLikeSelector(Selector sel) {
15544   if (sel.isUnarySelector()) return false;
15545 
15546   StringRef str = sel.getNameForSlot(0);
15547   while (!str.empty() && str.front() == '_') str = str.substr(1);
15548   if (str.startswith("set"))
15549     str = str.substr(3);
15550   else if (str.startswith("add")) {
15551     // Specially allow 'addOperationWithBlock:'.
15552     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15553       return false;
15554     str = str.substr(3);
15555   }
15556   else
15557     return false;
15558 
15559   if (str.empty()) return true;
15560   return !isLowercase(str.front());
15561 }
15562 
15563 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15564                                                     ObjCMessageExpr *Message) {
15565   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15566                                                 Message->getReceiverInterface(),
15567                                                 NSAPI::ClassId_NSMutableArray);
15568   if (!IsMutableArray) {
15569     return None;
15570   }
15571 
15572   Selector Sel = Message->getSelector();
15573 
15574   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15575     S.NSAPIObj->getNSArrayMethodKind(Sel);
15576   if (!MKOpt) {
15577     return None;
15578   }
15579 
15580   NSAPI::NSArrayMethodKind MK = *MKOpt;
15581 
15582   switch (MK) {
15583     case NSAPI::NSMutableArr_addObject:
15584     case NSAPI::NSMutableArr_insertObjectAtIndex:
15585     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15586       return 0;
15587     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15588       return 1;
15589 
15590     default:
15591       return None;
15592   }
15593 
15594   return None;
15595 }
15596 
15597 static
15598 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15599                                                   ObjCMessageExpr *Message) {
15600   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15601                                             Message->getReceiverInterface(),
15602                                             NSAPI::ClassId_NSMutableDictionary);
15603   if (!IsMutableDictionary) {
15604     return None;
15605   }
15606 
15607   Selector Sel = Message->getSelector();
15608 
15609   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15610     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15611   if (!MKOpt) {
15612     return None;
15613   }
15614 
15615   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15616 
15617   switch (MK) {
15618     case NSAPI::NSMutableDict_setObjectForKey:
15619     case NSAPI::NSMutableDict_setValueForKey:
15620     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15621       return 0;
15622 
15623     default:
15624       return None;
15625   }
15626 
15627   return None;
15628 }
15629 
15630 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15631   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15632                                                 Message->getReceiverInterface(),
15633                                                 NSAPI::ClassId_NSMutableSet);
15634 
15635   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15636                                             Message->getReceiverInterface(),
15637                                             NSAPI::ClassId_NSMutableOrderedSet);
15638   if (!IsMutableSet && !IsMutableOrderedSet) {
15639     return None;
15640   }
15641 
15642   Selector Sel = Message->getSelector();
15643 
15644   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15645   if (!MKOpt) {
15646     return None;
15647   }
15648 
15649   NSAPI::NSSetMethodKind MK = *MKOpt;
15650 
15651   switch (MK) {
15652     case NSAPI::NSMutableSet_addObject:
15653     case NSAPI::NSOrderedSet_setObjectAtIndex:
15654     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15655     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15656       return 0;
15657     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15658       return 1;
15659   }
15660 
15661   return None;
15662 }
15663 
15664 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15665   if (!Message->isInstanceMessage()) {
15666     return;
15667   }
15668 
15669   Optional<int> ArgOpt;
15670 
15671   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15672       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15673       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15674     return;
15675   }
15676 
15677   int ArgIndex = *ArgOpt;
15678 
15679   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15680   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15681     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15682   }
15683 
15684   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15685     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15686       if (ArgRE->isObjCSelfExpr()) {
15687         Diag(Message->getSourceRange().getBegin(),
15688              diag::warn_objc_circular_container)
15689           << ArgRE->getDecl() << StringRef("'super'");
15690       }
15691     }
15692   } else {
15693     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15694 
15695     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15696       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15697     }
15698 
15699     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15700       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15701         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15702           ValueDecl *Decl = ReceiverRE->getDecl();
15703           Diag(Message->getSourceRange().getBegin(),
15704                diag::warn_objc_circular_container)
15705             << Decl << Decl;
15706           if (!ArgRE->isObjCSelfExpr()) {
15707             Diag(Decl->getLocation(),
15708                  diag::note_objc_circular_container_declared_here)
15709               << Decl;
15710           }
15711         }
15712       }
15713     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15714       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15715         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15716           ObjCIvarDecl *Decl = IvarRE->getDecl();
15717           Diag(Message->getSourceRange().getBegin(),
15718                diag::warn_objc_circular_container)
15719             << Decl << Decl;
15720           Diag(Decl->getLocation(),
15721                diag::note_objc_circular_container_declared_here)
15722             << Decl;
15723         }
15724       }
15725     }
15726   }
15727 }
15728 
15729 /// Check a message send to see if it's likely to cause a retain cycle.
15730 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15731   // Only check instance methods whose selector looks like a setter.
15732   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15733     return;
15734 
15735   // Try to find a variable that the receiver is strongly owned by.
15736   RetainCycleOwner owner;
15737   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15738     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15739       return;
15740   } else {
15741     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15742     owner.Variable = getCurMethodDecl()->getSelfDecl();
15743     owner.Loc = msg->getSuperLoc();
15744     owner.Range = msg->getSuperLoc();
15745   }
15746 
15747   // Check whether the receiver is captured by any of the arguments.
15748   const ObjCMethodDecl *MD = msg->getMethodDecl();
15749   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15750     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15751       // noescape blocks should not be retained by the method.
15752       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15753         continue;
15754       return diagnoseRetainCycle(*this, capturer, owner);
15755     }
15756   }
15757 }
15758 
15759 /// Check a property assign to see if it's likely to cause a retain cycle.
15760 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15761   RetainCycleOwner owner;
15762   if (!findRetainCycleOwner(*this, receiver, owner))
15763     return;
15764 
15765   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15766     diagnoseRetainCycle(*this, capturer, owner);
15767 }
15768 
15769 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15770   RetainCycleOwner Owner;
15771   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15772     return;
15773 
15774   // Because we don't have an expression for the variable, we have to set the
15775   // location explicitly here.
15776   Owner.Loc = Var->getLocation();
15777   Owner.Range = Var->getSourceRange();
15778 
15779   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15780     diagnoseRetainCycle(*this, Capturer, Owner);
15781 }
15782 
15783 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15784                                      Expr *RHS, bool isProperty) {
15785   // Check if RHS is an Objective-C object literal, which also can get
15786   // immediately zapped in a weak reference.  Note that we explicitly
15787   // allow ObjCStringLiterals, since those are designed to never really die.
15788   RHS = RHS->IgnoreParenImpCasts();
15789 
15790   // This enum needs to match with the 'select' in
15791   // warn_objc_arc_literal_assign (off-by-1).
15792   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15793   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15794     return false;
15795 
15796   S.Diag(Loc, diag::warn_arc_literal_assign)
15797     << (unsigned) Kind
15798     << (isProperty ? 0 : 1)
15799     << RHS->getSourceRange();
15800 
15801   return true;
15802 }
15803 
15804 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15805                                     Qualifiers::ObjCLifetime LT,
15806                                     Expr *RHS, bool isProperty) {
15807   // Strip off any implicit cast added to get to the one ARC-specific.
15808   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15809     if (cast->getCastKind() == CK_ARCConsumeObject) {
15810       S.Diag(Loc, diag::warn_arc_retained_assign)
15811         << (LT == Qualifiers::OCL_ExplicitNone)
15812         << (isProperty ? 0 : 1)
15813         << RHS->getSourceRange();
15814       return true;
15815     }
15816     RHS = cast->getSubExpr();
15817   }
15818 
15819   if (LT == Qualifiers::OCL_Weak &&
15820       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15821     return true;
15822 
15823   return false;
15824 }
15825 
15826 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15827                               QualType LHS, Expr *RHS) {
15828   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15829 
15830   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15831     return false;
15832 
15833   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15834     return true;
15835 
15836   return false;
15837 }
15838 
15839 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15840                               Expr *LHS, Expr *RHS) {
15841   QualType LHSType;
15842   // PropertyRef on LHS type need be directly obtained from
15843   // its declaration as it has a PseudoType.
15844   ObjCPropertyRefExpr *PRE
15845     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15846   if (PRE && !PRE->isImplicitProperty()) {
15847     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15848     if (PD)
15849       LHSType = PD->getType();
15850   }
15851 
15852   if (LHSType.isNull())
15853     LHSType = LHS->getType();
15854 
15855   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15856 
15857   if (LT == Qualifiers::OCL_Weak) {
15858     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15859       getCurFunction()->markSafeWeakUse(LHS);
15860   }
15861 
15862   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15863     return;
15864 
15865   // FIXME. Check for other life times.
15866   if (LT != Qualifiers::OCL_None)
15867     return;
15868 
15869   if (PRE) {
15870     if (PRE->isImplicitProperty())
15871       return;
15872     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15873     if (!PD)
15874       return;
15875 
15876     unsigned Attributes = PD->getPropertyAttributes();
15877     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15878       // when 'assign' attribute was not explicitly specified
15879       // by user, ignore it and rely on property type itself
15880       // for lifetime info.
15881       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15882       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15883           LHSType->isObjCRetainableType())
15884         return;
15885 
15886       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15887         if (cast->getCastKind() == CK_ARCConsumeObject) {
15888           Diag(Loc, diag::warn_arc_retained_property_assign)
15889           << RHS->getSourceRange();
15890           return;
15891         }
15892         RHS = cast->getSubExpr();
15893       }
15894     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15895       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15896         return;
15897     }
15898   }
15899 }
15900 
15901 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15902 
15903 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15904                                         SourceLocation StmtLoc,
15905                                         const NullStmt *Body) {
15906   // Do not warn if the body is a macro that expands to nothing, e.g:
15907   //
15908   // #define CALL(x)
15909   // if (condition)
15910   //   CALL(0);
15911   if (Body->hasLeadingEmptyMacro())
15912     return false;
15913 
15914   // Get line numbers of statement and body.
15915   bool StmtLineInvalid;
15916   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15917                                                       &StmtLineInvalid);
15918   if (StmtLineInvalid)
15919     return false;
15920 
15921   bool BodyLineInvalid;
15922   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15923                                                       &BodyLineInvalid);
15924   if (BodyLineInvalid)
15925     return false;
15926 
15927   // Warn if null statement and body are on the same line.
15928   if (StmtLine != BodyLine)
15929     return false;
15930 
15931   return true;
15932 }
15933 
15934 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15935                                  const Stmt *Body,
15936                                  unsigned DiagID) {
15937   // Since this is a syntactic check, don't emit diagnostic for template
15938   // instantiations, this just adds noise.
15939   if (CurrentInstantiationScope)
15940     return;
15941 
15942   // The body should be a null statement.
15943   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15944   if (!NBody)
15945     return;
15946 
15947   // Do the usual checks.
15948   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15949     return;
15950 
15951   Diag(NBody->getSemiLoc(), DiagID);
15952   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15953 }
15954 
15955 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15956                                  const Stmt *PossibleBody) {
15957   assert(!CurrentInstantiationScope); // Ensured by caller
15958 
15959   SourceLocation StmtLoc;
15960   const Stmt *Body;
15961   unsigned DiagID;
15962   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15963     StmtLoc = FS->getRParenLoc();
15964     Body = FS->getBody();
15965     DiagID = diag::warn_empty_for_body;
15966   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15967     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15968     Body = WS->getBody();
15969     DiagID = diag::warn_empty_while_body;
15970   } else
15971     return; // Neither `for' nor `while'.
15972 
15973   // The body should be a null statement.
15974   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15975   if (!NBody)
15976     return;
15977 
15978   // Skip expensive checks if diagnostic is disabled.
15979   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15980     return;
15981 
15982   // Do the usual checks.
15983   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15984     return;
15985 
15986   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15987   // noise level low, emit diagnostics only if for/while is followed by a
15988   // CompoundStmt, e.g.:
15989   //    for (int i = 0; i < n; i++);
15990   //    {
15991   //      a(i);
15992   //    }
15993   // or if for/while is followed by a statement with more indentation
15994   // than for/while itself:
15995   //    for (int i = 0; i < n; i++);
15996   //      a(i);
15997   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15998   if (!ProbableTypo) {
15999     bool BodyColInvalid;
16000     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16001         PossibleBody->getBeginLoc(), &BodyColInvalid);
16002     if (BodyColInvalid)
16003       return;
16004 
16005     bool StmtColInvalid;
16006     unsigned StmtCol =
16007         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16008     if (StmtColInvalid)
16009       return;
16010 
16011     if (BodyCol > StmtCol)
16012       ProbableTypo = true;
16013   }
16014 
16015   if (ProbableTypo) {
16016     Diag(NBody->getSemiLoc(), DiagID);
16017     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16018   }
16019 }
16020 
16021 //===--- CHECK: Warn on self move with std::move. -------------------------===//
16022 
16023 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
16024 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16025                              SourceLocation OpLoc) {
16026   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16027     return;
16028 
16029   if (inTemplateInstantiation())
16030     return;
16031 
16032   // Strip parens and casts away.
16033   LHSExpr = LHSExpr->IgnoreParenImpCasts();
16034   RHSExpr = RHSExpr->IgnoreParenImpCasts();
16035 
16036   // Check for a call expression
16037   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
16038   if (!CE || CE->getNumArgs() != 1)
16039     return;
16040 
16041   // Check for a call to std::move
16042   if (!CE->isCallToStdMove())
16043     return;
16044 
16045   // Get argument from std::move
16046   RHSExpr = CE->getArg(0);
16047 
16048   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16049   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16050 
16051   // Two DeclRefExpr's, check that the decls are the same.
16052   if (LHSDeclRef && RHSDeclRef) {
16053     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16054       return;
16055     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16056         RHSDeclRef->getDecl()->getCanonicalDecl())
16057       return;
16058 
16059     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16060                                         << LHSExpr->getSourceRange()
16061                                         << RHSExpr->getSourceRange();
16062     return;
16063   }
16064 
16065   // Member variables require a different approach to check for self moves.
16066   // MemberExpr's are the same if every nested MemberExpr refers to the same
16067   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16068   // the base Expr's are CXXThisExpr's.
16069   const Expr *LHSBase = LHSExpr;
16070   const Expr *RHSBase = RHSExpr;
16071   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16072   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16073   if (!LHSME || !RHSME)
16074     return;
16075 
16076   while (LHSME && RHSME) {
16077     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16078         RHSME->getMemberDecl()->getCanonicalDecl())
16079       return;
16080 
16081     LHSBase = LHSME->getBase();
16082     RHSBase = RHSME->getBase();
16083     LHSME = dyn_cast<MemberExpr>(LHSBase);
16084     RHSME = dyn_cast<MemberExpr>(RHSBase);
16085   }
16086 
16087   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16088   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16089   if (LHSDeclRef && RHSDeclRef) {
16090     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16091       return;
16092     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16093         RHSDeclRef->getDecl()->getCanonicalDecl())
16094       return;
16095 
16096     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16097                                         << LHSExpr->getSourceRange()
16098                                         << RHSExpr->getSourceRange();
16099     return;
16100   }
16101 
16102   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16103     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16104                                         << LHSExpr->getSourceRange()
16105                                         << RHSExpr->getSourceRange();
16106 }
16107 
16108 //===--- Layout compatibility ----------------------------------------------//
16109 
16110 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
16111 
16112 /// Check if two enumeration types are layout-compatible.
16113 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
16114   // C++11 [dcl.enum] p8:
16115   // Two enumeration types are layout-compatible if they have the same
16116   // underlying type.
16117   return ED1->isComplete() && ED2->isComplete() &&
16118          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16119 }
16120 
16121 /// Check if two fields are layout-compatible.
16122 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
16123                                FieldDecl *Field2) {
16124   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16125     return false;
16126 
16127   if (Field1->isBitField() != Field2->isBitField())
16128     return false;
16129 
16130   if (Field1->isBitField()) {
16131     // Make sure that the bit-fields are the same length.
16132     unsigned Bits1 = Field1->getBitWidthValue(C);
16133     unsigned Bits2 = Field2->getBitWidthValue(C);
16134 
16135     if (Bits1 != Bits2)
16136       return false;
16137   }
16138 
16139   return true;
16140 }
16141 
16142 /// Check if two standard-layout structs are layout-compatible.
16143 /// (C++11 [class.mem] p17)
16144 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
16145                                      RecordDecl *RD2) {
16146   // If both records are C++ classes, check that base classes match.
16147   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
16148     // If one of records is a CXXRecordDecl we are in C++ mode,
16149     // thus the other one is a CXXRecordDecl, too.
16150     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
16151     // Check number of base classes.
16152     if (D1CXX->getNumBases() != D2CXX->getNumBases())
16153       return false;
16154 
16155     // Check the base classes.
16156     for (CXXRecordDecl::base_class_const_iterator
16157                Base1 = D1CXX->bases_begin(),
16158            BaseEnd1 = D1CXX->bases_end(),
16159               Base2 = D2CXX->bases_begin();
16160          Base1 != BaseEnd1;
16161          ++Base1, ++Base2) {
16162       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16163         return false;
16164     }
16165   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16166     // If only RD2 is a C++ class, it should have zero base classes.
16167     if (D2CXX->getNumBases() > 0)
16168       return false;
16169   }
16170 
16171   // Check the fields.
16172   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16173                              Field2End = RD2->field_end(),
16174                              Field1 = RD1->field_begin(),
16175                              Field1End = RD1->field_end();
16176   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16177     if (!isLayoutCompatible(C, *Field1, *Field2))
16178       return false;
16179   }
16180   if (Field1 != Field1End || Field2 != Field2End)
16181     return false;
16182 
16183   return true;
16184 }
16185 
16186 /// Check if two standard-layout unions are layout-compatible.
16187 /// (C++11 [class.mem] p18)
16188 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16189                                     RecordDecl *RD2) {
16190   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16191   for (auto *Field2 : RD2->fields())
16192     UnmatchedFields.insert(Field2);
16193 
16194   for (auto *Field1 : RD1->fields()) {
16195     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16196         I = UnmatchedFields.begin(),
16197         E = UnmatchedFields.end();
16198 
16199     for ( ; I != E; ++I) {
16200       if (isLayoutCompatible(C, Field1, *I)) {
16201         bool Result = UnmatchedFields.erase(*I);
16202         (void) Result;
16203         assert(Result);
16204         break;
16205       }
16206     }
16207     if (I == E)
16208       return false;
16209   }
16210 
16211   return UnmatchedFields.empty();
16212 }
16213 
16214 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16215                                RecordDecl *RD2) {
16216   if (RD1->isUnion() != RD2->isUnion())
16217     return false;
16218 
16219   if (RD1->isUnion())
16220     return isLayoutCompatibleUnion(C, RD1, RD2);
16221   else
16222     return isLayoutCompatibleStruct(C, RD1, RD2);
16223 }
16224 
16225 /// Check if two types are layout-compatible in C++11 sense.
16226 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16227   if (T1.isNull() || T2.isNull())
16228     return false;
16229 
16230   // C++11 [basic.types] p11:
16231   // If two types T1 and T2 are the same type, then T1 and T2 are
16232   // layout-compatible types.
16233   if (C.hasSameType(T1, T2))
16234     return true;
16235 
16236   T1 = T1.getCanonicalType().getUnqualifiedType();
16237   T2 = T2.getCanonicalType().getUnqualifiedType();
16238 
16239   const Type::TypeClass TC1 = T1->getTypeClass();
16240   const Type::TypeClass TC2 = T2->getTypeClass();
16241 
16242   if (TC1 != TC2)
16243     return false;
16244 
16245   if (TC1 == Type::Enum) {
16246     return isLayoutCompatible(C,
16247                               cast<EnumType>(T1)->getDecl(),
16248                               cast<EnumType>(T2)->getDecl());
16249   } else if (TC1 == Type::Record) {
16250     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16251       return false;
16252 
16253     return isLayoutCompatible(C,
16254                               cast<RecordType>(T1)->getDecl(),
16255                               cast<RecordType>(T2)->getDecl());
16256   }
16257 
16258   return false;
16259 }
16260 
16261 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16262 
16263 /// Given a type tag expression find the type tag itself.
16264 ///
16265 /// \param TypeExpr Type tag expression, as it appears in user's code.
16266 ///
16267 /// \param VD Declaration of an identifier that appears in a type tag.
16268 ///
16269 /// \param MagicValue Type tag magic value.
16270 ///
16271 /// \param isConstantEvaluated whether the evalaution should be performed in
16272 
16273 /// constant context.
16274 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16275                             const ValueDecl **VD, uint64_t *MagicValue,
16276                             bool isConstantEvaluated) {
16277   while(true) {
16278     if (!TypeExpr)
16279       return false;
16280 
16281     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16282 
16283     switch (TypeExpr->getStmtClass()) {
16284     case Stmt::UnaryOperatorClass: {
16285       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16286       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16287         TypeExpr = UO->getSubExpr();
16288         continue;
16289       }
16290       return false;
16291     }
16292 
16293     case Stmt::DeclRefExprClass: {
16294       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16295       *VD = DRE->getDecl();
16296       return true;
16297     }
16298 
16299     case Stmt::IntegerLiteralClass: {
16300       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16301       llvm::APInt MagicValueAPInt = IL->getValue();
16302       if (MagicValueAPInt.getActiveBits() <= 64) {
16303         *MagicValue = MagicValueAPInt.getZExtValue();
16304         return true;
16305       } else
16306         return false;
16307     }
16308 
16309     case Stmt::BinaryConditionalOperatorClass:
16310     case Stmt::ConditionalOperatorClass: {
16311       const AbstractConditionalOperator *ACO =
16312           cast<AbstractConditionalOperator>(TypeExpr);
16313       bool Result;
16314       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16315                                                      isConstantEvaluated)) {
16316         if (Result)
16317           TypeExpr = ACO->getTrueExpr();
16318         else
16319           TypeExpr = ACO->getFalseExpr();
16320         continue;
16321       }
16322       return false;
16323     }
16324 
16325     case Stmt::BinaryOperatorClass: {
16326       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16327       if (BO->getOpcode() == BO_Comma) {
16328         TypeExpr = BO->getRHS();
16329         continue;
16330       }
16331       return false;
16332     }
16333 
16334     default:
16335       return false;
16336     }
16337   }
16338 }
16339 
16340 /// Retrieve the C type corresponding to type tag TypeExpr.
16341 ///
16342 /// \param TypeExpr Expression that specifies a type tag.
16343 ///
16344 /// \param MagicValues Registered magic values.
16345 ///
16346 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16347 ///        kind.
16348 ///
16349 /// \param TypeInfo Information about the corresponding C type.
16350 ///
16351 /// \param isConstantEvaluated whether the evalaution should be performed in
16352 /// constant context.
16353 ///
16354 /// \returns true if the corresponding C type was found.
16355 static bool GetMatchingCType(
16356     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16357     const ASTContext &Ctx,
16358     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16359         *MagicValues,
16360     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16361     bool isConstantEvaluated) {
16362   FoundWrongKind = false;
16363 
16364   // Variable declaration that has type_tag_for_datatype attribute.
16365   const ValueDecl *VD = nullptr;
16366 
16367   uint64_t MagicValue;
16368 
16369   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16370     return false;
16371 
16372   if (VD) {
16373     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16374       if (I->getArgumentKind() != ArgumentKind) {
16375         FoundWrongKind = true;
16376         return false;
16377       }
16378       TypeInfo.Type = I->getMatchingCType();
16379       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16380       TypeInfo.MustBeNull = I->getMustBeNull();
16381       return true;
16382     }
16383     return false;
16384   }
16385 
16386   if (!MagicValues)
16387     return false;
16388 
16389   llvm::DenseMap<Sema::TypeTagMagicValue,
16390                  Sema::TypeTagData>::const_iterator I =
16391       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16392   if (I == MagicValues->end())
16393     return false;
16394 
16395   TypeInfo = I->second;
16396   return true;
16397 }
16398 
16399 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16400                                       uint64_t MagicValue, QualType Type,
16401                                       bool LayoutCompatible,
16402                                       bool MustBeNull) {
16403   if (!TypeTagForDatatypeMagicValues)
16404     TypeTagForDatatypeMagicValues.reset(
16405         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16406 
16407   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16408   (*TypeTagForDatatypeMagicValues)[Magic] =
16409       TypeTagData(Type, LayoutCompatible, MustBeNull);
16410 }
16411 
16412 static bool IsSameCharType(QualType T1, QualType T2) {
16413   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16414   if (!BT1)
16415     return false;
16416 
16417   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16418   if (!BT2)
16419     return false;
16420 
16421   BuiltinType::Kind T1Kind = BT1->getKind();
16422   BuiltinType::Kind T2Kind = BT2->getKind();
16423 
16424   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16425          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16426          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16427          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16428 }
16429 
16430 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16431                                     const ArrayRef<const Expr *> ExprArgs,
16432                                     SourceLocation CallSiteLoc) {
16433   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16434   bool IsPointerAttr = Attr->getIsPointer();
16435 
16436   // Retrieve the argument representing the 'type_tag'.
16437   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16438   if (TypeTagIdxAST >= ExprArgs.size()) {
16439     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16440         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16441     return;
16442   }
16443   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16444   bool FoundWrongKind;
16445   TypeTagData TypeInfo;
16446   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16447                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16448                         TypeInfo, isConstantEvaluated())) {
16449     if (FoundWrongKind)
16450       Diag(TypeTagExpr->getExprLoc(),
16451            diag::warn_type_tag_for_datatype_wrong_kind)
16452         << TypeTagExpr->getSourceRange();
16453     return;
16454   }
16455 
16456   // Retrieve the argument representing the 'arg_idx'.
16457   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16458   if (ArgumentIdxAST >= ExprArgs.size()) {
16459     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16460         << 1 << Attr->getArgumentIdx().getSourceIndex();
16461     return;
16462   }
16463   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16464   if (IsPointerAttr) {
16465     // Skip implicit cast of pointer to `void *' (as a function argument).
16466     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16467       if (ICE->getType()->isVoidPointerType() &&
16468           ICE->getCastKind() == CK_BitCast)
16469         ArgumentExpr = ICE->getSubExpr();
16470   }
16471   QualType ArgumentType = ArgumentExpr->getType();
16472 
16473   // Passing a `void*' pointer shouldn't trigger a warning.
16474   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16475     return;
16476 
16477   if (TypeInfo.MustBeNull) {
16478     // Type tag with matching void type requires a null pointer.
16479     if (!ArgumentExpr->isNullPointerConstant(Context,
16480                                              Expr::NPC_ValueDependentIsNotNull)) {
16481       Diag(ArgumentExpr->getExprLoc(),
16482            diag::warn_type_safety_null_pointer_required)
16483           << ArgumentKind->getName()
16484           << ArgumentExpr->getSourceRange()
16485           << TypeTagExpr->getSourceRange();
16486     }
16487     return;
16488   }
16489 
16490   QualType RequiredType = TypeInfo.Type;
16491   if (IsPointerAttr)
16492     RequiredType = Context.getPointerType(RequiredType);
16493 
16494   bool mismatch = false;
16495   if (!TypeInfo.LayoutCompatible) {
16496     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16497 
16498     // C++11 [basic.fundamental] p1:
16499     // Plain char, signed char, and unsigned char are three distinct types.
16500     //
16501     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16502     // char' depending on the current char signedness mode.
16503     if (mismatch)
16504       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16505                                            RequiredType->getPointeeType())) ||
16506           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16507         mismatch = false;
16508   } else
16509     if (IsPointerAttr)
16510       mismatch = !isLayoutCompatible(Context,
16511                                      ArgumentType->getPointeeType(),
16512                                      RequiredType->getPointeeType());
16513     else
16514       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16515 
16516   if (mismatch)
16517     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16518         << ArgumentType << ArgumentKind
16519         << TypeInfo.LayoutCompatible << RequiredType
16520         << ArgumentExpr->getSourceRange()
16521         << TypeTagExpr->getSourceRange();
16522 }
16523 
16524 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16525                                          CharUnits Alignment) {
16526   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16527 }
16528 
16529 void Sema::DiagnoseMisalignedMembers() {
16530   for (MisalignedMember &m : MisalignedMembers) {
16531     const NamedDecl *ND = m.RD;
16532     if (ND->getName().empty()) {
16533       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16534         ND = TD;
16535     }
16536     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16537         << m.MD << ND << m.E->getSourceRange();
16538   }
16539   MisalignedMembers.clear();
16540 }
16541 
16542 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16543   E = E->IgnoreParens();
16544   if (!T->isPointerType() && !T->isIntegerType())
16545     return;
16546   if (isa<UnaryOperator>(E) &&
16547       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16548     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16549     if (isa<MemberExpr>(Op)) {
16550       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16551       if (MA != MisalignedMembers.end() &&
16552           (T->isIntegerType() ||
16553            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16554                                    Context.getTypeAlignInChars(
16555                                        T->getPointeeType()) <= MA->Alignment))))
16556         MisalignedMembers.erase(MA);
16557     }
16558   }
16559 }
16560 
16561 void Sema::RefersToMemberWithReducedAlignment(
16562     Expr *E,
16563     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16564         Action) {
16565   const auto *ME = dyn_cast<MemberExpr>(E);
16566   if (!ME)
16567     return;
16568 
16569   // No need to check expressions with an __unaligned-qualified type.
16570   if (E->getType().getQualifiers().hasUnaligned())
16571     return;
16572 
16573   // For a chain of MemberExpr like "a.b.c.d" this list
16574   // will keep FieldDecl's like [d, c, b].
16575   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16576   const MemberExpr *TopME = nullptr;
16577   bool AnyIsPacked = false;
16578   do {
16579     QualType BaseType = ME->getBase()->getType();
16580     if (BaseType->isDependentType())
16581       return;
16582     if (ME->isArrow())
16583       BaseType = BaseType->getPointeeType();
16584     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16585     if (RD->isInvalidDecl())
16586       return;
16587 
16588     ValueDecl *MD = ME->getMemberDecl();
16589     auto *FD = dyn_cast<FieldDecl>(MD);
16590     // We do not care about non-data members.
16591     if (!FD || FD->isInvalidDecl())
16592       return;
16593 
16594     AnyIsPacked =
16595         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16596     ReverseMemberChain.push_back(FD);
16597 
16598     TopME = ME;
16599     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16600   } while (ME);
16601   assert(TopME && "We did not compute a topmost MemberExpr!");
16602 
16603   // Not the scope of this diagnostic.
16604   if (!AnyIsPacked)
16605     return;
16606 
16607   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16608   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16609   // TODO: The innermost base of the member expression may be too complicated.
16610   // For now, just disregard these cases. This is left for future
16611   // improvement.
16612   if (!DRE && !isa<CXXThisExpr>(TopBase))
16613       return;
16614 
16615   // Alignment expected by the whole expression.
16616   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16617 
16618   // No need to do anything else with this case.
16619   if (ExpectedAlignment.isOne())
16620     return;
16621 
16622   // Synthesize offset of the whole access.
16623   CharUnits Offset;
16624   for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16625     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16626 
16627   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16628   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16629       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16630 
16631   // The base expression of the innermost MemberExpr may give
16632   // stronger guarantees than the class containing the member.
16633   if (DRE && !TopME->isArrow()) {
16634     const ValueDecl *VD = DRE->getDecl();
16635     if (!VD->getType()->isReferenceType())
16636       CompleteObjectAlignment =
16637           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16638   }
16639 
16640   // Check if the synthesized offset fulfills the alignment.
16641   if (Offset % ExpectedAlignment != 0 ||
16642       // It may fulfill the offset it but the effective alignment may still be
16643       // lower than the expected expression alignment.
16644       CompleteObjectAlignment < ExpectedAlignment) {
16645     // If this happens, we want to determine a sensible culprit of this.
16646     // Intuitively, watching the chain of member expressions from right to
16647     // left, we start with the required alignment (as required by the field
16648     // type) but some packed attribute in that chain has reduced the alignment.
16649     // It may happen that another packed structure increases it again. But if
16650     // we are here such increase has not been enough. So pointing the first
16651     // FieldDecl that either is packed or else its RecordDecl is,
16652     // seems reasonable.
16653     FieldDecl *FD = nullptr;
16654     CharUnits Alignment;
16655     for (FieldDecl *FDI : ReverseMemberChain) {
16656       if (FDI->hasAttr<PackedAttr>() ||
16657           FDI->getParent()->hasAttr<PackedAttr>()) {
16658         FD = FDI;
16659         Alignment = std::min(
16660             Context.getTypeAlignInChars(FD->getType()),
16661             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16662         break;
16663       }
16664     }
16665     assert(FD && "We did not find a packed FieldDecl!");
16666     Action(E, FD->getParent(), FD, Alignment);
16667   }
16668 }
16669 
16670 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16671   using namespace std::placeholders;
16672 
16673   RefersToMemberWithReducedAlignment(
16674       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16675                      _2, _3, _4));
16676 }
16677 
16678 // Check if \p Ty is a valid type for the elementwise math builtins. If it is
16679 // not a valid type, emit an error message and return true. Otherwise return
16680 // false.
16681 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc,
16682                                         QualType Ty) {
16683   if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) {
16684     S.Diag(Loc, diag::err_builtin_invalid_arg_type)
16685         << 1 << /* vector, integer or float ty*/ 0 << Ty;
16686     return true;
16687   }
16688   return false;
16689 }
16690 
16691 bool Sema::SemaBuiltinElementwiseMathOneArg(CallExpr *TheCall) {
16692   if (checkArgCount(*this, TheCall, 1))
16693     return true;
16694 
16695   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16696   SourceLocation ArgLoc = TheCall->getArg(0)->getBeginLoc();
16697   if (A.isInvalid())
16698     return true;
16699 
16700   TheCall->setArg(0, A.get());
16701   QualType TyA = A.get()->getType();
16702   if (checkMathBuiltinElementType(*this, ArgLoc, TyA))
16703     return true;
16704 
16705   QualType EltTy = TyA;
16706   if (auto *VecTy = EltTy->getAs<VectorType>())
16707     EltTy = VecTy->getElementType();
16708   if (EltTy->isUnsignedIntegerType())
16709     return Diag(ArgLoc, diag::err_builtin_invalid_arg_type)
16710            << 1 << /*signed integer or float ty*/ 3 << TyA;
16711 
16712   TheCall->setType(TyA);
16713   return false;
16714 }
16715 
16716 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) {
16717   if (checkArgCount(*this, TheCall, 2))
16718     return true;
16719 
16720   ExprResult A = TheCall->getArg(0);
16721   ExprResult B = TheCall->getArg(1);
16722   // Do standard promotions between the two arguments, returning their common
16723   // type.
16724   QualType Res =
16725       UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
16726   if (A.isInvalid() || B.isInvalid())
16727     return true;
16728 
16729   QualType TyA = A.get()->getType();
16730   QualType TyB = B.get()->getType();
16731 
16732   if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
16733     return Diag(A.get()->getBeginLoc(),
16734                 diag::err_typecheck_call_different_arg_types)
16735            << TyA << TyB;
16736 
16737   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
16738     return true;
16739 
16740   TheCall->setArg(0, A.get());
16741   TheCall->setArg(1, B.get());
16742   TheCall->setType(Res);
16743   return false;
16744 }
16745 
16746 bool Sema::SemaBuiltinReduceMath(CallExpr *TheCall) {
16747   if (checkArgCount(*this, TheCall, 1))
16748     return true;
16749 
16750   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16751   if (A.isInvalid())
16752     return true;
16753 
16754   TheCall->setArg(0, A.get());
16755   const VectorType *TyA = A.get()->getType()->getAs<VectorType>();
16756   if (!TyA) {
16757     SourceLocation ArgLoc = TheCall->getArg(0)->getBeginLoc();
16758     return Diag(ArgLoc, diag::err_builtin_invalid_arg_type)
16759            << 1 << /* vector ty*/ 4 << A.get()->getType();
16760   }
16761 
16762   TheCall->setType(TyA->getElementType());
16763   return false;
16764 }
16765 
16766 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16767                                             ExprResult CallResult) {
16768   if (checkArgCount(*this, TheCall, 1))
16769     return ExprError();
16770 
16771   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16772   if (MatrixArg.isInvalid())
16773     return MatrixArg;
16774   Expr *Matrix = MatrixArg.get();
16775 
16776   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16777   if (!MType) {
16778     Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16779         << 1 << /* matrix ty*/ 1 << Matrix->getType();
16780     return ExprError();
16781   }
16782 
16783   // Create returned matrix type by swapping rows and columns of the argument
16784   // matrix type.
16785   QualType ResultType = Context.getConstantMatrixType(
16786       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16787 
16788   // Change the return type to the type of the returned matrix.
16789   TheCall->setType(ResultType);
16790 
16791   // Update call argument to use the possibly converted matrix argument.
16792   TheCall->setArg(0, Matrix);
16793   return CallResult;
16794 }
16795 
16796 // Get and verify the matrix dimensions.
16797 static llvm::Optional<unsigned>
16798 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16799   SourceLocation ErrorPos;
16800   Optional<llvm::APSInt> Value =
16801       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16802   if (!Value) {
16803     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16804         << Name;
16805     return {};
16806   }
16807   uint64_t Dim = Value->getZExtValue();
16808   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16809     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16810         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16811     return {};
16812   }
16813   return Dim;
16814 }
16815 
16816 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16817                                                   ExprResult CallResult) {
16818   if (!getLangOpts().MatrixTypes) {
16819     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16820     return ExprError();
16821   }
16822 
16823   if (checkArgCount(*this, TheCall, 4))
16824     return ExprError();
16825 
16826   unsigned PtrArgIdx = 0;
16827   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16828   Expr *RowsExpr = TheCall->getArg(1);
16829   Expr *ColumnsExpr = TheCall->getArg(2);
16830   Expr *StrideExpr = TheCall->getArg(3);
16831 
16832   bool ArgError = false;
16833 
16834   // Check pointer argument.
16835   {
16836     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16837     if (PtrConv.isInvalid())
16838       return PtrConv;
16839     PtrExpr = PtrConv.get();
16840     TheCall->setArg(0, PtrExpr);
16841     if (PtrExpr->isTypeDependent()) {
16842       TheCall->setType(Context.DependentTy);
16843       return TheCall;
16844     }
16845   }
16846 
16847   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16848   QualType ElementTy;
16849   if (!PtrTy) {
16850     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16851         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
16852     ArgError = true;
16853   } else {
16854     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16855 
16856     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16857       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16858           << PtrArgIdx + 1 << /* pointer to element ty*/ 2
16859           << PtrExpr->getType();
16860       ArgError = true;
16861     }
16862   }
16863 
16864   // Apply default Lvalue conversions and convert the expression to size_t.
16865   auto ApplyArgumentConversions = [this](Expr *E) {
16866     ExprResult Conv = DefaultLvalueConversion(E);
16867     if (Conv.isInvalid())
16868       return Conv;
16869 
16870     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16871   };
16872 
16873   // Apply conversion to row and column expressions.
16874   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16875   if (!RowsConv.isInvalid()) {
16876     RowsExpr = RowsConv.get();
16877     TheCall->setArg(1, RowsExpr);
16878   } else
16879     RowsExpr = nullptr;
16880 
16881   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16882   if (!ColumnsConv.isInvalid()) {
16883     ColumnsExpr = ColumnsConv.get();
16884     TheCall->setArg(2, ColumnsExpr);
16885   } else
16886     ColumnsExpr = nullptr;
16887 
16888   // If any any part of the result matrix type is still pending, just use
16889   // Context.DependentTy, until all parts are resolved.
16890   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16891       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16892     TheCall->setType(Context.DependentTy);
16893     return CallResult;
16894   }
16895 
16896   // Check row and column dimensions.
16897   llvm::Optional<unsigned> MaybeRows;
16898   if (RowsExpr)
16899     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16900 
16901   llvm::Optional<unsigned> MaybeColumns;
16902   if (ColumnsExpr)
16903     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16904 
16905   // Check stride argument.
16906   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16907   if (StrideConv.isInvalid())
16908     return ExprError();
16909   StrideExpr = StrideConv.get();
16910   TheCall->setArg(3, StrideExpr);
16911 
16912   if (MaybeRows) {
16913     if (Optional<llvm::APSInt> Value =
16914             StrideExpr->getIntegerConstantExpr(Context)) {
16915       uint64_t Stride = Value->getZExtValue();
16916       if (Stride < *MaybeRows) {
16917         Diag(StrideExpr->getBeginLoc(),
16918              diag::err_builtin_matrix_stride_too_small);
16919         ArgError = true;
16920       }
16921     }
16922   }
16923 
16924   if (ArgError || !MaybeRows || !MaybeColumns)
16925     return ExprError();
16926 
16927   TheCall->setType(
16928       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16929   return CallResult;
16930 }
16931 
16932 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16933                                                    ExprResult CallResult) {
16934   if (checkArgCount(*this, TheCall, 3))
16935     return ExprError();
16936 
16937   unsigned PtrArgIdx = 1;
16938   Expr *MatrixExpr = TheCall->getArg(0);
16939   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16940   Expr *StrideExpr = TheCall->getArg(2);
16941 
16942   bool ArgError = false;
16943 
16944   {
16945     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16946     if (MatrixConv.isInvalid())
16947       return MatrixConv;
16948     MatrixExpr = MatrixConv.get();
16949     TheCall->setArg(0, MatrixExpr);
16950   }
16951   if (MatrixExpr->isTypeDependent()) {
16952     TheCall->setType(Context.DependentTy);
16953     return TheCall;
16954   }
16955 
16956   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16957   if (!MatrixTy) {
16958     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16959         << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
16960     ArgError = true;
16961   }
16962 
16963   {
16964     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16965     if (PtrConv.isInvalid())
16966       return PtrConv;
16967     PtrExpr = PtrConv.get();
16968     TheCall->setArg(1, PtrExpr);
16969     if (PtrExpr->isTypeDependent()) {
16970       TheCall->setType(Context.DependentTy);
16971       return TheCall;
16972     }
16973   }
16974 
16975   // Check pointer argument.
16976   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16977   if (!PtrTy) {
16978     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16979         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
16980     ArgError = true;
16981   } else {
16982     QualType ElementTy = PtrTy->getPointeeType();
16983     if (ElementTy.isConstQualified()) {
16984       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16985       ArgError = true;
16986     }
16987     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16988     if (MatrixTy &&
16989         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16990       Diag(PtrExpr->getBeginLoc(),
16991            diag::err_builtin_matrix_pointer_arg_mismatch)
16992           << ElementTy << MatrixTy->getElementType();
16993       ArgError = true;
16994     }
16995   }
16996 
16997   // Apply default Lvalue conversions and convert the stride expression to
16998   // size_t.
16999   {
17000     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17001     if (StrideConv.isInvalid())
17002       return StrideConv;
17003 
17004     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17005     if (StrideConv.isInvalid())
17006       return StrideConv;
17007     StrideExpr = StrideConv.get();
17008     TheCall->setArg(2, StrideExpr);
17009   }
17010 
17011   // Check stride argument.
17012   if (MatrixTy) {
17013     if (Optional<llvm::APSInt> Value =
17014             StrideExpr->getIntegerConstantExpr(Context)) {
17015       uint64_t Stride = Value->getZExtValue();
17016       if (Stride < MatrixTy->getNumRows()) {
17017         Diag(StrideExpr->getBeginLoc(),
17018              diag::err_builtin_matrix_stride_too_small);
17019         ArgError = true;
17020       }
17021     }
17022   }
17023 
17024   if (ArgError)
17025     return ExprError();
17026 
17027   return CallResult;
17028 }
17029 
17030 /// \brief Enforce the bounds of a TCB
17031 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
17032 /// directly calls other functions in the same TCB as marked by the enforce_tcb
17033 /// and enforce_tcb_leaf attributes.
17034 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
17035                                const FunctionDecl *Callee) {
17036   const FunctionDecl *Caller = getCurFunctionDecl();
17037 
17038   // Calls to builtins are not enforced.
17039   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
17040       Callee->getBuiltinID() != 0)
17041     return;
17042 
17043   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17044   // all TCBs the callee is a part of.
17045   llvm::StringSet<> CalleeTCBs;
17046   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
17047            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17048   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
17049            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17050 
17051   // Go through the TCBs the caller is a part of and emit warnings if Caller
17052   // is in a TCB that the Callee is not.
17053   for_each(
17054       Caller->specific_attrs<EnforceTCBAttr>(),
17055       [&](const auto *A) {
17056         StringRef CallerTCB = A->getTCBName();
17057         if (CalleeTCBs.count(CallerTCB) == 0) {
17058           this->Diag(TheCall->getExprLoc(),
17059                      diag::warn_tcb_enforcement_violation) << Callee
17060                                                            << CallerTCB;
17061         }
17062       });
17063 }
17064